pulse-analytics-sdk 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,1368 @@
1
+ "use client";
2
+ var __defProp = Object.defineProperty;
3
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
5
+
6
+ // src/index.ts
7
+ import { useEffect, useRef } from "react";
8
+
9
+ // ../../node_modules/.pnpm/web-vitals@6.2.3/node_modules/web-vitals/dist/web-vitals.js
10
+ var t = -1;
11
+ var n = () => t;
12
+ var e = (n2) => {
13
+ addEventListener("pageshow", (e2) => {
14
+ e2.persisted && (t = e2.timeStamp, n2(e2));
15
+ }, true);
16
+ };
17
+ var i = (t2, n2, e2, i2) => {
18
+ let o2, s2;
19
+ return (a2) => {
20
+ n2.value >= 0 && (a2 || i2) && (s2 = n2.value - (o2 ?? 0), (s2 || void 0 === o2) && (o2 = n2.value, n2.delta = s2, n2.rating = ((t3, n3) => t3 > n3[1] ? "poor" : t3 > n3[0] ? "needs-improvement" : "good")(n2.value, e2), t2(n2)));
21
+ };
22
+ };
23
+ var o = (t2) => {
24
+ requestAnimationFrame(() => requestAnimationFrame(() => t2()));
25
+ };
26
+ var s = () => {
27
+ const t2 = performance.getEntriesByType("navigation")[0];
28
+ if (t2 && t2.responseStart > 0 && t2.responseStart < performance.now()) return t2;
29
+ };
30
+ var a = () => s()?.activationStart ?? 0;
31
+ var r = -1;
32
+ var c = /* @__PURE__ */ new Set();
33
+ var f = () => "hidden" !== document.visibilityState || document.prerendering ? 1 / 0 : 0;
34
+ var h = (t2) => {
35
+ if ("hidden" === document.visibilityState) {
36
+ if ("visibilitychange" === t2.type) for (const t3 of c) t3();
37
+ isFinite(r) || (r = "visibilitychange" === t2.type ? t2.timeStamp : 0, removeEventListener("prerenderingchange", h, true));
38
+ }
39
+ };
40
+ var d = (t2 = false) => {
41
+ if (t2 && (r = 1 / 0), r < 0) {
42
+ const t3 = a(), n2 = document.prerendering ? void 0 : globalThis.performance.getEntriesByType("visibility-state").find((n3) => "hidden" === n3.name && n3.startTime >= t3)?.startTime;
43
+ r = n2 ?? f(), addEventListener("visibilitychange", h, true), addEventListener("prerenderingchange", h, true), e(() => {
44
+ setTimeout(() => {
45
+ r = f();
46
+ });
47
+ });
48
+ }
49
+ return { get firstHiddenTime() {
50
+ return r;
51
+ }, onHidden(t3) {
52
+ c.add(t3);
53
+ } };
54
+ };
55
+ var l = (t2, e2 = -1, i2, o2 = 0, r2, c2, f2) => {
56
+ const h2 = s(), d2 = h2?.navigationId || 0;
57
+ let l2 = "navigate";
58
+ i2 ? l2 = i2 : n() >= 0 ? l2 = "back-forward-cache" : h2 && (document.prerendering || a() > 0 ? l2 = "prerender" : document.wasDiscarded ? l2 = "restore" : h2.type && (l2 = h2.type.replace(/_/g, "-")));
59
+ return { name: t2, value: e2, rating: "good", delta: 0, entries: [], id: `v6-${Date.now()}-${Math.floor(8999999999999 * Math.random()) + 1e12}`, navigationType: l2, navigationId: o2 || d2, navigationInteractionId: r2, navigationURL: c2 || h2?.name, navigationStartTime: f2 || 0 };
60
+ };
61
+ var g = /* @__PURE__ */ new WeakMap();
62
+ function u(t2, n2) {
63
+ let e2 = g.get(n2);
64
+ return e2 || (e2 = /* @__PURE__ */ new WeakMap(), g.set(n2, e2)), e2.get(t2) || e2.set(t2, new n2()), e2.get(t2);
65
+ }
66
+ var v = class {
67
+ constructor() {
68
+ __publicField(this, "t");
69
+ __publicField(this, "i", 0);
70
+ __publicField(this, "o", []);
71
+ }
72
+ h(t2) {
73
+ if (t2.hadRecentInput) return;
74
+ const n2 = this.o[0], e2 = this.o.at(-1);
75
+ this.i && n2 && e2 && t2.startTime - e2.startTime < 1e3 && t2.startTime - n2.startTime < 5e3 ? (this.i += t2.value, this.o.push(t2)) : (this.i = t2.value, this.o = [t2]), this.t?.(t2);
76
+ }
77
+ };
78
+ var m = (t2, n2, e2 = {}) => {
79
+ try {
80
+ const i2 = t2.filter((t3) => PerformanceObserver.supportedEntryTypes.includes(t3));
81
+ if (i2.length > 0) {
82
+ const t3 = new PerformanceObserver((t4) => {
83
+ queueMicrotask(() => {
84
+ const e3 = t4.getEntries();
85
+ i2.length > 1 && e3.sort((t5, n3) => t5.startTime + t5.duration - (n3.startTime + n3.duration)), n2(e3);
86
+ });
87
+ });
88
+ for (const n3 of i2) t3.observe({ type: n3, buffered: true, ...e2 });
89
+ return t3;
90
+ }
91
+ } catch {
92
+ }
93
+ };
94
+ var p = (t2) => globalThis.PerformanceObserver?.supportedEntryTypes?.includes("soft-navigation") && "function" == typeof globalThis.PerformanceSoftNavigation?.prototype?.getLargestInteractionContentfulPaint && t2 && t2.reportSoftNavs;
95
+ var b = (t2, n2) => {
96
+ if (t2.set(n2.navigationId, n2), t2.size > 2) {
97
+ const n3 = t2.keys().next().value;
98
+ void 0 !== n3 && t2.delete(n3);
99
+ }
100
+ };
101
+ var T = (t2) => {
102
+ let n2 = false;
103
+ return () => {
104
+ n2 || (t2(), n2 = true);
105
+ };
106
+ };
107
+ var y = class {
108
+ constructor() {
109
+ __publicField(this, "l");
110
+ }
111
+ };
112
+ var _ = (t2) => {
113
+ document.prerendering ? addEventListener("prerenderingchange", t2, true) : t2();
114
+ };
115
+ var E = [1800, 3e3];
116
+ var M = (t2, s2 = {}) => {
117
+ const r2 = p(s2);
118
+ _(() => {
119
+ const c2 = u(s2, y), f2 = d();
120
+ let h2, g2 = l("FCP");
121
+ const v2 = m(["paint"], (t3) => {
122
+ for (const n2 of t3) "first-contentful-paint" === n2.name && (v2.disconnect(), n2.startTime < f2.firstHiddenTime && (g2.value = Math.max(n2.startTime - a(), 0), g2.entries.push(n2), g2.navigationId = n2.navigationId || g2.navigationId, h2(true)));
123
+ });
124
+ if (v2 && (h2 = i(t2, g2, E, s2.reportAllChanges), e((e2) => {
125
+ g2 = l("FCP", -1, "back-forward-cache", g2.navigationId, g2.navigationInteractionId, g2.navigationURL, n()), h2 = i(t2, g2, E, s2.reportAllChanges), o(() => {
126
+ g2.value = performance.now() - e2.timeStamp, h2(true);
127
+ });
128
+ })), r2) {
129
+ m(["soft-navigation"], (n2) => {
130
+ n2.forEach((n3) => {
131
+ c2.l && n3.navigationId && b(c2.l, n3);
132
+ const e2 = Math.max((n3.presentationTime || n3.paintTime || 0) - n3.startTime, 0);
133
+ g2 = l("FCP", e2, "soft-navigation", n3.navigationId, n3.interactionId, n3.name, n3.startTime), h2 = i(t2, g2, E, s2.reportAllChanges), h2(true);
134
+ });
135
+ }, s2);
136
+ }
137
+ });
138
+ };
139
+ var L = [0.1, 0.25];
140
+ var P = (t2, s2 = {}) => {
141
+ const a2 = d();
142
+ M(T(() => {
143
+ let r2, c2 = l("CLS", 0);
144
+ const f2 = u(s2, v), h2 = (n2, e2, o2, a3, h3) => {
145
+ c2 = l("CLS", 0, n2, e2, o2, a3, h3), f2.i = 0, r2 = i(t2, c2, L, s2.reportAllChanges);
146
+ }, d2 = (t3 = false) => {
147
+ f2.i > c2.value && (c2.value = f2.i, c2.entries = f2.o), r2(t3);
148
+ }, g2 = (t3) => {
149
+ d2(true), h2("soft-navigation", t3.navigationId, t3.interactionId, t3.name, t3.startTime);
150
+ }, b2 = (t3) => {
151
+ for (const n2 of t3) "soft-navigation" !== n2.entryType ? f2.h(n2) : g2(n2);
152
+ d2();
153
+ }, T2 = ["layout-shift"];
154
+ p(s2) && T2.push("soft-navigation");
155
+ const y2 = m(T2, b2);
156
+ y2 && (r2 = i(t2, c2, L, s2.reportAllChanges), a2.onHidden(() => {
157
+ b2(y2.takeRecords()), r2(true);
158
+ }), e(() => {
159
+ h2("back-forward-cache", c2.navigationId, c2.navigationInteractionId, c2.navigationURL, n()), o(r2);
160
+ }), setTimeout(r2));
161
+ }));
162
+ };
163
+ var w = 0;
164
+ var I = 1 / 0;
165
+ var k = 0;
166
+ var C = (t2) => {
167
+ for (const n2 of t2) n2.interactionId && (I = Math.min(I, n2.interactionId), k = Math.max(k, n2.interactionId), w = k ? (k - I) / 7 + 1 : 0);
168
+ };
169
+ var F;
170
+ var N = () => F ? w : performance.interactionCount ?? 0;
171
+ var B = () => {
172
+ "interactionCount" in performance || F || (F = m(["event"], C, { durationThreshold: 0 }));
173
+ };
174
+ var S = class {
175
+ constructor() {
176
+ __publicField(this, "u", 0);
177
+ __publicField(this, "v", []);
178
+ __publicField(this, "m", /* @__PURE__ */ new Map());
179
+ __publicField(this, "p");
180
+ __publicField(this, "T");
181
+ }
182
+ _() {
183
+ return N() - this.u;
184
+ }
185
+ M() {
186
+ this.u = N(), this.v.length = 0, this.m.clear();
187
+ }
188
+ L(t2) {
189
+ const n2 = this._(), e2 = Math.min(this.v.length - 1, Math.floor(n2 / 50));
190
+ return !n2 || -1 !== e2 || "soft-navigation" !== t2 && "back-forward-cache" !== t2 ? this.v[e2] : { P: 8, id: -1, entries: [] };
191
+ }
192
+ h(t2) {
193
+ if (this.p?.(t2), !t2.interactionId) return;
194
+ const n2 = this.v.at(-1);
195
+ let e2 = this.m.get(t2.interactionId);
196
+ if (e2 || this.v.length < 10 || t2.duration > n2.P) {
197
+ if (e2 ? t2.duration > e2.P ? (e2.entries = [t2], e2.P = t2.duration) : t2.duration === e2.P && t2.startTime === e2.entries[0].startTime && e2.entries.push(t2) : (e2 = { id: t2.interactionId, entries: [t2], P: t2.duration }, this.m.set(e2.id, e2), this.v.push(e2)), this.v.sort((t3, n3) => n3.P - t3.P), this.v.length > 10) {
198
+ const t3 = this.v.splice(10);
199
+ for (const n3 of t3) this.m.delete(n3.id);
200
+ }
201
+ this.T?.(e2);
202
+ }
203
+ }
204
+ };
205
+ var q = (t2) => {
206
+ const n2 = "requestIdleCallback" in globalThis ? 1e3 : 0, e2 = globalThis.requestIdleCallback || setTimeout, i2 = globalThis.cancelIdleCallback || clearTimeout;
207
+ if ("hidden" === document.visibilityState) t2();
208
+ else {
209
+ const o2 = T(t2);
210
+ let s2 = -1;
211
+ const a2 = () => {
212
+ i2(s2), o2();
213
+ };
214
+ addEventListener("visibilitychange", a2, { once: true, capture: true }), s2 = e2(() => {
215
+ removeEventListener("visibilitychange", a2, { capture: true }), o2();
216
+ }, { timeout: n2 });
217
+ }
218
+ };
219
+ var A = [200, 500];
220
+ var x = (t2, o2 = {}) => {
221
+ if (!globalThis.PerformanceEventTiming || !("interactionId" in PerformanceEventTiming.prototype)) return;
222
+ const s2 = d();
223
+ _(() => {
224
+ B();
225
+ let a2, r2 = l("INP");
226
+ const c2 = u(o2, S), f2 = (n2, e2, s3, f3, h3) => {
227
+ c2.M(), r2 = l("INP", -1, n2, e2, s3, f3, h3), a2 = i(t2, r2, A, o2.reportAllChanges);
228
+ }, h2 = () => {
229
+ const t3 = c2.L(r2.navigationType);
230
+ t3 && t3.P !== r2.value && (r2.value = t3.P, r2.entries = t3.entries, a2());
231
+ }, d2 = (t3) => {
232
+ h2(), a2(true), f2("soft-navigation", t3.navigationId, t3.interactionId, t3.name, t3.startTime);
233
+ }, g2 = (t3, n2 = false) => {
234
+ q(() => {
235
+ for (const n3 of t3) "soft-navigation" !== n3.entryType ? c2.h(n3) : d2(n3);
236
+ h2(), n2 && a2(true);
237
+ });
238
+ }, v2 = ["event", "first-input"];
239
+ p(o2) && v2.push("soft-navigation");
240
+ const b2 = m(v2, g2, { ...o2, durationThreshold: o2.durationThreshold ?? 40 });
241
+ a2 = i(t2, r2, A, o2.reportAllChanges), b2 && (s2.onHidden(() => {
242
+ g2(b2.takeRecords(), true);
243
+ }), e(() => {
244
+ f2("back-forward-cache", r2.navigationId, r2.navigationInteractionId, r2.navigationURL, n());
245
+ }));
246
+ });
247
+ };
248
+ var H = class {
249
+ constructor() {
250
+ __publicField(this, "p");
251
+ __publicField(this, "l");
252
+ }
253
+ h(t2) {
254
+ this.p?.(t2);
255
+ }
256
+ };
257
+ var O = [2500, 4e3];
258
+ var U = (t2, s2 = {}) => {
259
+ let r2 = false;
260
+ const c2 = p(s2);
261
+ _(() => {
262
+ let f2, h2 = d(), g2 = l("LCP");
263
+ const v2 = u(s2, H), p2 = (n2, e2, o2, a2, c3) => {
264
+ g2 = l("LCP", -1, n2, e2, o2, a2, c3), f2 = i(t2, g2, O, s2.reportAllChanges), r2 = false, "soft-navigation" === n2 && (h2 = d(true));
265
+ }, T2 = (t3) => {
266
+ v2.l && t3.navigationId && b(v2.l, t3), r2 || f2(true), p2("soft-navigation", t3.navigationId, t3.interactionId, t3.name, t3.startTime);
267
+ const n2 = t3.getLargestInteractionContentfulPaint?.();
268
+ n2 && y2([n2]);
269
+ }, y2 = (t3) => {
270
+ s2.reportAllChanges || c2 || (t3 = t3.slice(-1));
271
+ for (const n2 of t3) {
272
+ if (!n2) continue;
273
+ if ("soft-navigation" === n2.entryType) {
274
+ T2(n2);
275
+ continue;
276
+ }
277
+ let t4 = 0, e2 = [], i2 = n2.startTime;
278
+ if ("largest-contentful-paint" === n2.entryType) t4 = Math.max(n2.startTime - a(), 0), v2.h(n2), e2 = [n2];
279
+ else if ("interaction-contentful-paint" === n2.entryType) {
280
+ const o2 = n2;
281
+ if (!g2.navigationId) continue;
282
+ if ("interactionId" in o2 && o2.interactionId != g2.navigationInteractionId) continue;
283
+ i2 = o2.largestContentfulPaint?.renderTime || 0, t4 = Math.max(i2 - n2.startTime, 0), o2.largestContentfulPaint && (v2.h(o2.largestContentfulPaint), e2 = [o2.largestContentfulPaint]);
284
+ }
285
+ i2 < h2.firstHiddenTime && (g2.value = t4, g2.entries = e2, f2());
286
+ }
287
+ }, _2 = ["largest-contentful-paint"];
288
+ c2 && _2.push("interaction-contentful-paint", "soft-navigation");
289
+ const E2 = m(_2, y2);
290
+ if (E2) {
291
+ f2 = i(t2, g2, O, s2.reportAllChanges);
292
+ const a2 = ["keydown", "click", "visibilitychange"], h3 = (t3) => {
293
+ if (t3.isTrusted && !r2) {
294
+ const t4 = g2.id;
295
+ q(() => {
296
+ if (!r2) {
297
+ if (!c2) {
298
+ E2.disconnect();
299
+ for (const t5 of a2) removeEventListener(t5, h3, { capture: true });
300
+ }
301
+ t4 === g2.id && (r2 = true, f2(true));
302
+ }
303
+ });
304
+ }
305
+ };
306
+ for (const t3 of a2) addEventListener(t3, h3, { capture: true });
307
+ e((e2) => {
308
+ p2("back-forward-cache", g2.navigationId, g2.navigationInteractionId, g2.navigationURL, n()), f2 = i(t2, g2, O, s2.reportAllChanges), o(() => {
309
+ g2.value = performance.now() - e2.timeStamp, r2 = true, f2(true);
310
+ });
311
+ });
312
+ }
313
+ });
314
+ };
315
+ var W = [800, 1800];
316
+ var $ = (t2) => {
317
+ document.prerendering ? _(() => $(t2)) : "complete" !== document.readyState ? addEventListener("load", () => $(t2), true) : setTimeout(t2);
318
+ };
319
+ var D = (t2, o2 = {}) => {
320
+ const r2 = p(o2);
321
+ let c2 = l("TTFB"), f2 = i(t2, c2, W, o2.reportAllChanges);
322
+ $(() => {
323
+ const h2 = s();
324
+ if (h2) {
325
+ const s2 = h2.responseStart;
326
+ if (c2.value = Math.max(s2 - a(), 0), c2.entries = [h2], f2(true), e(() => {
327
+ c2 = l("TTFB", 0, "back-forward-cache", c2.navigationId, c2.navigationInteractionId, c2.navigationURL, n()), f2 = i(t2, c2, W, o2.reportAllChanges), f2(true);
328
+ }), r2) {
329
+ m(["soft-navigation"], (n2) => {
330
+ n2.forEach((n3) => {
331
+ n3.navigationId && (c2 = l("TTFB", 0, "soft-navigation", n3.navigationId, n3.interactionId, n3.name, n3.startTime), c2.entries = [n3], f2 = i(t2, c2, W, o2.reportAllChanges), f2(true));
332
+ });
333
+ }, o2);
334
+ }
335
+ }
336
+ });
337
+ };
338
+
339
+ // src/dom.ts
340
+ var INTERACTIVE_SELECTOR = "a, button, input, select, textarea, label, option, summary, details, video[controls], audio[controls], [role='button'], [role='link'], [role='menuitem'], [role='tab'], [role='checkbox'], [role='radio'], [role='switch'], [role='option'], [role='combobox'], [contenteditable='true'], [tabindex]:not([tabindex='-1'])";
341
+ var DOWNLOAD_EXT_RE = /\.(pdf|zip|tar|gz|tgz|rar|7z|csv|xlsx?|docx?|pptx?|json|txt|exe|dmg|pkg|msi|apk)$/i;
342
+ function getCssSelector(el) {
343
+ const parts = [];
344
+ let current = el;
345
+ let depth = 0;
346
+ while (current && current.nodeType === 1 && depth < 4) {
347
+ let part = current.tagName.toLowerCase();
348
+ if (current.id) {
349
+ part += `#${current.id}`;
350
+ parts.unshift(part);
351
+ break;
352
+ }
353
+ if (typeof current.className === "string" && current.className.trim()) {
354
+ const classes = current.className.trim().split(/\s+/).filter((cls) => cls && !cls.includes(":")).slice(0, 2).join(".");
355
+ if (classes) part += `.${classes}`;
356
+ }
357
+ parts.unshift(part);
358
+ current = current.parentElement;
359
+ depth += 1;
360
+ }
361
+ return parts.join(" > ").slice(0, 500);
362
+ }
363
+ function getClickLabel(el) {
364
+ const aria = el.getAttribute("aria-label") || el.getAttribute("title");
365
+ if (aria && aria.trim()) return aria.trim().slice(0, 160);
366
+ const text = el.innerText || el.textContent || "";
367
+ return text.replace(/\s+/g, " ").trim().slice(0, 160);
368
+ }
369
+ function parseQueryParams(searchParams) {
370
+ const result = {};
371
+ let count = 0;
372
+ searchParams.forEach((rawValue, rawKey) => {
373
+ if (count >= 25) return;
374
+ const key = rawKey.slice(0, 80);
375
+ const value = rawValue.slice(0, 240);
376
+ const existing = result[key];
377
+ if (existing === void 0) {
378
+ result[key] = value;
379
+ count += 1;
380
+ } else if (Array.isArray(existing)) {
381
+ if (existing.length < 10) existing.push(value);
382
+ } else {
383
+ result[key] = [existing, value];
384
+ }
385
+ });
386
+ return result;
387
+ }
388
+ function getScrollPercent() {
389
+ const doc = document.documentElement;
390
+ const body = document.body;
391
+ const scrollHeight = Math.max(
392
+ doc?.scrollHeight || 0,
393
+ body?.scrollHeight || 0,
394
+ window.innerHeight || 1,
395
+ 1
396
+ );
397
+ const viewportBottom = window.scrollY + (window.innerHeight || 0);
398
+ const pct = Math.round(viewportBottom / scrollHeight * 100);
399
+ return Math.max(0, Math.min(100, pct));
400
+ }
401
+ function classifyAnchorClick(anchor) {
402
+ const rawHref = anchor.getAttribute("href");
403
+ if (!rawHref || rawHref.startsWith("javascript:") || rawHref.startsWith("#")) {
404
+ return null;
405
+ }
406
+ try {
407
+ const resolved = new URL(rawHref, window.location.href);
408
+ const isHttp = resolved.protocol === "http:" || resolved.protocol === "https:";
409
+ const isExternal = isHttp && resolved.origin !== window.location.origin;
410
+ const downloadAttr = anchor.getAttribute("download");
411
+ const hasDownloadAttr = anchor.hasAttribute("download");
412
+ const extMatch = resolved.pathname.match(DOWNLOAD_EXT_RE);
413
+ if (hasDownloadAttr || isHttp && extMatch) {
414
+ const safeHref = resolved.protocol === "blob:" || resolved.protocol === "data:" ? `${resolved.protocol}//${downloadAttr || "download"}` : resolved.href;
415
+ const filename = downloadAttr && downloadAttr.trim() || resolved.pathname.split("/").pop() || "download";
416
+ const extFromName = filename.includes(".") ? filename.split(".").pop()?.toLowerCase() : void 0;
417
+ return {
418
+ kind: "download",
419
+ href: safeHref.slice(0, 1e3),
420
+ filename: filename.slice(0, 200),
421
+ extension: (extMatch?.[1] || extFromName || "").toLowerCase() || void 0,
422
+ targetHost: isHttp ? resolved.hostname : void 0,
423
+ isExternal
424
+ };
425
+ }
426
+ if (isExternal) {
427
+ return {
428
+ kind: "outbound",
429
+ href: resolved.href.slice(0, 1e3),
430
+ targetHost: resolved.hostname,
431
+ targetOrigin: resolved.origin,
432
+ targetPath: resolved.pathname,
433
+ isExternal: true
434
+ };
435
+ }
436
+ return {
437
+ kind: "internal",
438
+ href: rawHref.slice(0, 1e3),
439
+ isExternal: false
440
+ };
441
+ } catch {
442
+ return null;
443
+ }
444
+ }
445
+ function getFormIdentifier(form) {
446
+ const explicit = form.getAttribute("data-analytics-form") || form.id || form.getAttribute("name") || form.getAttribute("aria-label");
447
+ if (explicit && explicit.trim()) return explicit.trim().slice(0, 160);
448
+ const action = form.getAttribute("action");
449
+ if (action && action.trim()) {
450
+ try {
451
+ const url = new URL(action, window.location.href);
452
+ return `form:${url.pathname}`.slice(0, 160);
453
+ } catch {
454
+ return `form:${action.trim()}`.slice(0, 160);
455
+ }
456
+ }
457
+ return getCssSelector(form).slice(0, 160);
458
+ }
459
+ function getFieldDescriptor(el) {
460
+ if (!(el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement || el instanceof HTMLSelectElement)) {
461
+ return null;
462
+ }
463
+ if (el instanceof HTMLInputElement) {
464
+ if (el.type === "hidden" || el.type === "submit" || el.type === "button") {
465
+ return null;
466
+ }
467
+ if (el.type === "password") {
468
+ return el.name ? `password:${el.name.slice(0, 40)}` : "password_field";
469
+ }
470
+ }
471
+ const label = el.getAttribute("name") || el.id || el.getAttribute("aria-label") || (el instanceof HTMLInputElement ? el.type : el.tagName.toLowerCase());
472
+ return label ? label.trim().slice(0, 80) : null;
473
+ }
474
+
475
+ // src/transport.ts
476
+ var MAX_QUEUE_SIZE = 25;
477
+ var MAX_BATCH_BYTES = 6e3;
478
+ var queue = [];
479
+ var queuedEndpoint = "";
480
+ var queuedAppId = "";
481
+ var fetchLaterResult = null;
482
+ var fetchLaterController = null;
483
+ function randomId(prefix) {
484
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
485
+ return `${prefix}_${crypto.randomUUID()}`;
486
+ }
487
+ return `${prefix}_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;
488
+ }
489
+ function getVisitorId() {
490
+ try {
491
+ const key = "__pulse_vid";
492
+ let vid = window.localStorage.getItem(key);
493
+ if (!vid) {
494
+ vid = randomId("v");
495
+ window.localStorage.setItem(key, vid);
496
+ }
497
+ return vid;
498
+ } catch {
499
+ return randomId("v");
500
+ }
501
+ }
502
+ function getSessionId() {
503
+ try {
504
+ const key = "__pulse_sid";
505
+ const tsKey = "__pulse_sts";
506
+ const now = Date.now();
507
+ const last = Number(window.sessionStorage.getItem(tsKey) || "0");
508
+ let sid = window.sessionStorage.getItem(key);
509
+ if (!sid || now - last > 30 * 60 * 1e3) {
510
+ sid = randomId("s");
511
+ window.sessionStorage.setItem(key, sid);
512
+ }
513
+ window.sessionStorage.setItem(tsKey, String(now));
514
+ return sid;
515
+ } catch {
516
+ return randomId("s");
517
+ }
518
+ }
519
+ function ensureFetchLater() {
520
+ const g2 = globalThis;
521
+ if (typeof g2.fetchLater === "function") {
522
+ return g2.fetchLater.bind(globalThis);
523
+ }
524
+ const polyfill = (url, init = {}) => {
525
+ let timeoutHandle;
526
+ let activated = false;
527
+ function sendNow() {
528
+ if (!(init.signal && init.signal.aborted)) {
529
+ if ("keepalive" in Request.prototype || init.method !== "POST" || init.headers) {
530
+ void fetch(url, Object.assign({}, init, { keepalive: true })).catch(
531
+ () => {
532
+ }
533
+ );
534
+ activated = true;
535
+ } else if (typeof navigator.sendBeacon === "function") {
536
+ activated = navigator.sendBeacon(
537
+ typeof url === "string" ? url : url.toString(),
538
+ init.body
539
+ );
540
+ }
541
+ }
542
+ destroy();
543
+ }
544
+ function destroy() {
545
+ if (typeof document !== "undefined") {
546
+ document.removeEventListener("visibilitychange", sendNow);
547
+ }
548
+ if (timeoutHandle !== void 0) {
549
+ clearTimeout(timeoutHandle);
550
+ }
551
+ }
552
+ if (typeof document !== "undefined" && document.visibilityState === "hidden") {
553
+ queueMicrotask(sendNow);
554
+ } else {
555
+ if (typeof document !== "undefined") {
556
+ document.addEventListener("visibilitychange", sendNow);
557
+ }
558
+ if (typeof init.activateAfter === "number" && init.activateAfter >= 0) {
559
+ timeoutHandle = setTimeout(sendNow, init.activateAfter);
560
+ }
561
+ }
562
+ if (init.signal) {
563
+ init.signal.addEventListener("abort", destroy);
564
+ }
565
+ return {
566
+ get activated() {
567
+ return activated;
568
+ }
569
+ };
570
+ };
571
+ g2.fetchLater = polyfill;
572
+ return polyfill;
573
+ }
574
+ function buildEventRecord(config, payload) {
575
+ const url = new URL(window.location.href);
576
+ const queryStr = url.search || void 0;
577
+ const queryParams = url.search ? parseQueryParams(url.searchParams) : void 0;
578
+ return {
579
+ appId: config.appId,
580
+ visitorId: getVisitorId(),
581
+ sessionId: getSessionId(),
582
+ userId: config.userId ?? void 0,
583
+ userEmail: config.userEmail ?? void 0,
584
+ userTraits: config.userTraits ?? void 0,
585
+ path: payload.path ?? url.pathname,
586
+ query: payload.query ?? queryStr,
587
+ queryParams: payload.queryParams ?? queryParams,
588
+ url: payload.url ?? url.href,
589
+ title: payload.title ?? document.title,
590
+ referrer: document.referrer || void 0,
591
+ screenWidth: window.screen?.width,
592
+ screenHeight: window.screen?.height,
593
+ viewportWidth: window.innerWidth,
594
+ viewportHeight: window.innerHeight,
595
+ language: navigator.language,
596
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
597
+ utmSource: url.searchParams.get("utm_source") ?? void 0,
598
+ utmMedium: url.searchParams.get("utm_medium") ?? void 0,
599
+ utmCampaign: url.searchParams.get("utm_campaign") ?? void 0,
600
+ ...payload
601
+ };
602
+ }
603
+ function resetQueueState() {
604
+ fetchLaterController = null;
605
+ fetchLaterResult = null;
606
+ queue = [];
607
+ }
608
+ function sendFallbackDirect(endpoint, body) {
609
+ try {
610
+ void fetch(endpoint, {
611
+ method: "POST",
612
+ headers: { "Content-Type": "application/json" },
613
+ body,
614
+ keepalive: true
615
+ }).catch(() => {
616
+ });
617
+ } catch {
618
+ if (typeof navigator !== "undefined" && typeof navigator.sendBeacon === "function") {
619
+ navigator.sendBeacon(endpoint, new Blob([body], { type: "text/plain" }));
620
+ }
621
+ }
622
+ }
623
+ function scheduleBatch(endpoint, appId, activateAfterMs) {
624
+ if (queue.length === 0) return;
625
+ const body = JSON.stringify({
626
+ appId,
627
+ events: queue
628
+ });
629
+ if (fetchLaterController) {
630
+ fetchLaterController.abort();
631
+ }
632
+ fetchLaterController = new AbortController();
633
+ try {
634
+ const fetchLater = ensureFetchLater();
635
+ fetchLaterResult = fetchLater(endpoint, {
636
+ method: "POST",
637
+ headers: { "content-type": "application/json" },
638
+ body,
639
+ signal: fetchLaterController.signal,
640
+ activateAfter: activateAfterMs
641
+ });
642
+ } catch {
643
+ resetQueueState();
644
+ sendFallbackDirect(endpoint, body);
645
+ }
646
+ }
647
+ function enqueueEvent(config, payload, immediate = false) {
648
+ if (typeof window === "undefined") return;
649
+ if (fetchLaterResult?.activated || queue.length >= MAX_QUEUE_SIZE || queuedEndpoint && queuedEndpoint !== config.endpoint || queuedAppId && queuedAppId !== config.appId) {
650
+ resetQueueState();
651
+ }
652
+ queuedEndpoint = config.endpoint;
653
+ queuedAppId = config.appId;
654
+ const record = buildEventRecord(config, payload);
655
+ const candidate = [...queue, record];
656
+ const candidateBytes = JSON.stringify({
657
+ appId: config.appId,
658
+ events: candidate
659
+ }).length;
660
+ if (candidateBytes > MAX_BATCH_BYTES && queue.length > 0) {
661
+ const previousBody = JSON.stringify({
662
+ appId: config.appId,
663
+ events: queue
664
+ });
665
+ if (fetchLaterController) {
666
+ fetchLaterController.abort();
667
+ }
668
+ resetQueueState();
669
+ sendFallbackDirect(config.endpoint, previousBody);
670
+ }
671
+ queue.push(record);
672
+ scheduleBatch(
673
+ config.endpoint,
674
+ config.appId,
675
+ immediate ? 0 : config.batchWindowMs
676
+ );
677
+ }
678
+ function flushTelemetryQueue() {
679
+ if (typeof window === "undefined") return;
680
+ if (fetchLaterResult?.activated || queue.length === 0 || !queuedEndpoint) {
681
+ return;
682
+ }
683
+ const body = JSON.stringify({
684
+ appId: queuedAppId,
685
+ events: queue
686
+ });
687
+ if (fetchLaterController) {
688
+ fetchLaterController.abort();
689
+ }
690
+ resetQueueState();
691
+ sendFallbackDirect(queuedEndpoint, body);
692
+ }
693
+
694
+ // src/index.ts
695
+ var IDLE_THRESHOLD_MS = 3e4;
696
+ var RAGE_WINDOW_MS = 1e3;
697
+ var RAGE_MIN_CLICKS = 3;
698
+ var RAGE_RADIUS_PX = 32;
699
+ var DEAD_CLICK_OBSERVE_MS = 350;
700
+ var SCROLL_MILESTONES = [25, 50, 75, 100];
701
+ var activeConfig = null;
702
+ var vitalsRegistered = false;
703
+ var currentVitalPath = "/";
704
+ function trackEvent(eventName, props) {
705
+ if (!activeConfig) return;
706
+ enqueueEvent(activeConfig, {
707
+ eventType: "custom",
708
+ eventName,
709
+ props: props ?? {}
710
+ });
711
+ }
712
+ function identifyUser(userId, traits) {
713
+ if (!activeConfig) return;
714
+ activeConfig.userId = userId;
715
+ if (traits?.email) activeConfig.userEmail = traits.email;
716
+ if (traits) activeConfig.userTraits = traits;
717
+ }
718
+ function flushAnalytics() {
719
+ flushTelemetryQueue();
720
+ }
721
+ function Analytics({
722
+ appId,
723
+ endpoint,
724
+ userId,
725
+ userEmail,
726
+ userTraits,
727
+ trackPageviews = true,
728
+ trackClicks = true,
729
+ trackScrollDepth = true,
730
+ trackEngagement = true,
731
+ trackFriction = true,
732
+ trackOutbound = true,
733
+ trackForms = true,
734
+ trackErrors = true,
735
+ trackWebVitals = true,
736
+ batchWindowMs = 2e3,
737
+ disabled = false
738
+ }) {
739
+ const configRef = useRef({
740
+ appId,
741
+ endpoint,
742
+ userId,
743
+ userEmail,
744
+ userTraits,
745
+ batchWindowMs
746
+ });
747
+ useEffect(() => {
748
+ const nextConfig = {
749
+ appId,
750
+ endpoint,
751
+ userId,
752
+ userEmail,
753
+ userTraits,
754
+ batchWindowMs
755
+ };
756
+ configRef.current = nextConfig;
757
+ activeConfig = disabled ? null : nextConfig;
758
+ }, [appId, endpoint, userId, userEmail, userTraits, batchWindowMs, disabled]);
759
+ useEffect(() => {
760
+ if (disabled || typeof window === "undefined") {
761
+ activeConfig = null;
762
+ return;
763
+ }
764
+ const getConfig = () => configRef.current;
765
+ activeConfig = configRef.current;
766
+ let activeRoute = null;
767
+ const initialPath = window.location.pathname;
768
+ let pageStartTs = Date.now();
769
+ let activeAccumMs = 0;
770
+ let lastTickTs = Date.now();
771
+ let lastInteractionTs = Date.now();
772
+ let lastMouseTs = 0;
773
+ let maxScrollDepth = 0;
774
+ const sentMilestones = /* @__PURE__ */ new Set();
775
+ let titleTimer = null;
776
+ let titleRaf = null;
777
+ let initialScrollTimer = null;
778
+ let pendingPageviewEmit = null;
779
+ let leaveSentForRoute = false;
780
+ const recentClicks = [];
781
+ const trackedForms = /* @__PURE__ */ new Map();
782
+ const reportedErrors = /* @__PURE__ */ new Set();
783
+ const deadClickCleanups = /* @__PURE__ */ new Set();
784
+ const updateActiveTime = () => {
785
+ const now = Date.now();
786
+ const dt = Math.min(Math.max(0, now - lastTickTs), 1500);
787
+ if (trackEngagement && document.visibilityState === "visible" && now - lastInteractionTs <= IDLE_THRESHOLD_MS) {
788
+ activeAccumMs += dt;
789
+ }
790
+ lastTickTs = now;
791
+ };
792
+ const markInteraction = () => {
793
+ const now = Date.now();
794
+ updateActiveTime();
795
+ lastInteractionTs = now;
796
+ };
797
+ const handleMouseMove = () => {
798
+ const now = Date.now();
799
+ if (now - lastMouseTs < 500) return;
800
+ lastMouseTs = now;
801
+ markInteraction();
802
+ };
803
+ const cancelPendingTitleTimer = () => {
804
+ if (titleRaf !== null) {
805
+ window.cancelAnimationFrame(titleRaf);
806
+ titleRaf = null;
807
+ }
808
+ if (titleTimer !== null) {
809
+ window.clearTimeout(titleTimer);
810
+ titleTimer = null;
811
+ }
812
+ if (initialScrollTimer !== null) {
813
+ window.clearTimeout(initialScrollTimer);
814
+ initialScrollTimer = null;
815
+ }
816
+ };
817
+ const emitAbandonedForms = (snapshot, immediate) => {
818
+ if (!trackForms) return;
819
+ for (const state of trackedForms.values()) {
820
+ if (!state.submitted && !state.abandonedReported && state.fieldsTouched.size > 0) {
821
+ state.abandonedReported = true;
822
+ enqueueEvent(
823
+ getConfig(),
824
+ {
825
+ eventType: "form_abandon",
826
+ eventName: state.formId,
827
+ formId: state.formId,
828
+ path: snapshot.path,
829
+ query: snapshot.query,
830
+ queryParams: snapshot.queryParams,
831
+ url: snapshot.url,
832
+ title: document.title || snapshot.title,
833
+ durationMs: Math.max(0, Date.now() - state.startedAt),
834
+ props: {
835
+ formId: state.formId,
836
+ fieldsTouchedCount: state.fieldsTouched.size,
837
+ fieldCount: state.fieldCount,
838
+ fieldsTouched: Array.from(state.fieldsTouched).slice(0, 20)
839
+ }
840
+ },
841
+ immediate
842
+ );
843
+ }
844
+ }
845
+ };
846
+ const finalizeRouteLeave = (immediate) => {
847
+ if (!activeRoute || leaveSentForRoute) return;
848
+ if (pendingPageviewEmit) {
849
+ const flushPv = pendingPageviewEmit;
850
+ pendingPageviewEmit = null;
851
+ flushPv();
852
+ }
853
+ leaveSentForRoute = true;
854
+ updateActiveTime();
855
+ const durationMs = Math.max(0, Date.now() - pageStartTs);
856
+ const activeMs = Math.min(durationMs, Math.round(activeAccumMs));
857
+ if (trackScrollDepth) {
858
+ const doc = document.documentElement;
859
+ const scrollHeight = Math.max(
860
+ doc?.scrollHeight || 0,
861
+ document.body?.scrollHeight || 0,
862
+ 1
863
+ );
864
+ if (scrollHeight <= (window.innerHeight || 0) && activeMs > 300) {
865
+ maxScrollDepth = Math.max(maxScrollDepth, 100);
866
+ } else {
867
+ maxScrollDepth = Math.max(maxScrollDepth, getScrollPercent());
868
+ }
869
+ checkScrollMilestones();
870
+ }
871
+ emitAbandonedForms(activeRoute, immediate);
872
+ if (durationMs > 200) {
873
+ enqueueEvent(
874
+ getConfig(),
875
+ {
876
+ eventType: "leave",
877
+ path: activeRoute.path,
878
+ query: activeRoute.query,
879
+ queryParams: activeRoute.queryParams,
880
+ url: activeRoute.url,
881
+ title: document.title || activeRoute.title,
882
+ durationMs,
883
+ activeMs: trackEngagement ? activeMs : void 0,
884
+ scrollDepth: trackScrollDepth ? maxScrollDepth : void 0
885
+ },
886
+ immediate
887
+ );
888
+ }
889
+ };
890
+ const resetPageState = (url) => {
891
+ pageStartTs = Date.now();
892
+ activeAccumMs = 0;
893
+ lastTickTs = Date.now();
894
+ lastInteractionTs = Date.now();
895
+ maxScrollDepth = 0;
896
+ sentMilestones.clear();
897
+ recentClicks.length = 0;
898
+ trackedForms.clear();
899
+ leaveSentForRoute = false;
900
+ const snapshot = {
901
+ routeKey: url.pathname + url.search,
902
+ path: url.pathname,
903
+ query: url.search || void 0,
904
+ queryParams: url.search ? parseQueryParams(url.searchParams) : void 0,
905
+ url: url.href,
906
+ title: document.title
907
+ };
908
+ activeRoute = snapshot;
909
+ currentVitalPath = snapshot.path;
910
+ return snapshot;
911
+ };
912
+ let scrollThrottleTimer = null;
913
+ const checkScrollMilestones = () => {
914
+ if (!trackScrollDepth || !activeRoute) return;
915
+ const pct = getScrollPercent();
916
+ maxScrollDepth = Math.max(maxScrollDepth, pct);
917
+ for (const milestone of SCROLL_MILESTONES) {
918
+ if (pct >= milestone && !sentMilestones.has(milestone)) {
919
+ sentMilestones.add(milestone);
920
+ updateActiveTime();
921
+ enqueueEvent(getConfig(), {
922
+ eventType: "scroll",
923
+ eventName: `scroll_${milestone}`,
924
+ scrollDepth: milestone,
925
+ activeMs: trackEngagement ? Math.round(activeAccumMs) : void 0,
926
+ path: activeRoute.path,
927
+ query: activeRoute.query,
928
+ queryParams: activeRoute.queryParams,
929
+ url: activeRoute.url
930
+ });
931
+ }
932
+ }
933
+ };
934
+ const recordPageview = (deferMs) => {
935
+ const url = new URL(window.location.href);
936
+ const routeKey = url.pathname + url.search;
937
+ if (activeRoute && routeKey === activeRoute.routeKey) return;
938
+ cancelPendingTitleTimer();
939
+ if (activeRoute) {
940
+ finalizeRouteLeave(false);
941
+ }
942
+ const snapshot = resetPageState(url);
943
+ if (trackScrollDepth) {
944
+ initialScrollTimer = window.setTimeout(() => {
945
+ initialScrollTimer = null;
946
+ checkScrollMilestones();
947
+ }, 400);
948
+ }
949
+ if (!trackPageviews) return;
950
+ const emitPageview = () => {
951
+ pendingPageviewEmit = null;
952
+ snapshot.title = document.title;
953
+ enqueueEvent(getConfig(), {
954
+ eventType: "pageview",
955
+ path: snapshot.path,
956
+ query: snapshot.query,
957
+ queryParams: snapshot.queryParams,
958
+ url: snapshot.url,
959
+ title: snapshot.title
960
+ });
961
+ };
962
+ if (deferMs <= 0) {
963
+ emitPageview();
964
+ return;
965
+ }
966
+ pendingPageviewEmit = emitPageview;
967
+ titleRaf = window.requestAnimationFrame(() => {
968
+ titleRaf = null;
969
+ titleTimer = window.setTimeout(() => {
970
+ titleTimer = null;
971
+ emitPageview();
972
+ }, deferMs);
973
+ });
974
+ };
975
+ recordPageview(50);
976
+ const engagementInterval = trackEngagement ? window.setInterval(updateActiveTime, 1e3) : null;
977
+ if (trackEngagement) {
978
+ window.addEventListener("pointerdown", markInteraction, { passive: true });
979
+ window.addEventListener("keydown", markInteraction, { passive: true });
980
+ window.addEventListener("touchstart", markInteraction, { passive: true });
981
+ window.addEventListener("wheel", markInteraction, { passive: true });
982
+ window.addEventListener("mousemove", handleMouseMove, { passive: true });
983
+ }
984
+ const handleScroll = () => {
985
+ if (trackEngagement) markInteraction();
986
+ if (!trackScrollDepth || scrollThrottleTimer !== null) return;
987
+ scrollThrottleTimer = window.setTimeout(() => {
988
+ scrollThrottleTimer = null;
989
+ checkScrollMilestones();
990
+ }, 150);
991
+ };
992
+ if (trackScrollDepth || trackEngagement) {
993
+ window.addEventListener("scroll", handleScroll, { passive: true });
994
+ }
995
+ const origPushState = window.history.pushState;
996
+ const origReplaceState = window.history.replaceState;
997
+ const handlePopState = () => recordPageview(140);
998
+ const handlePageHide = () => {
999
+ finalizeRouteLeave(true);
1000
+ flushTelemetryQueue();
1001
+ };
1002
+ const handleVisibilityChange = () => {
1003
+ updateActiveTime();
1004
+ if (document.visibilityState === "hidden") {
1005
+ finalizeRouteLeave(true);
1006
+ flushTelemetryQueue();
1007
+ } else {
1008
+ leaveSentForRoute = false;
1009
+ pageStartTs = Date.now();
1010
+ activeAccumMs = 0;
1011
+ lastTickTs = Date.now();
1012
+ lastInteractionTs = Date.now();
1013
+ }
1014
+ };
1015
+ if (trackPageviews || trackEngagement || trackForms || trackScrollDepth) {
1016
+ window.history.pushState = function(...args) {
1017
+ origPushState.apply(this, args);
1018
+ recordPageview(140);
1019
+ };
1020
+ window.history.replaceState = function(...args) {
1021
+ origReplaceState.apply(this, args);
1022
+ recordPageview(140);
1023
+ };
1024
+ window.addEventListener("popstate", handlePopState);
1025
+ window.addEventListener("pagehide", handlePageHide);
1026
+ document.addEventListener("visibilitychange", handleVisibilityChange);
1027
+ }
1028
+ const handleClick = (event) => {
1029
+ if (trackEngagement) markInteraction();
1030
+ const target = event.target;
1031
+ if (!target) return;
1032
+ const interactiveEl = target.closest(INTERACTIVE_SELECTOR) ?? target;
1033
+ const vw = window.innerWidth || 1;
1034
+ const vh = window.innerHeight || 1;
1035
+ const clickX = Math.round(event.clientX);
1036
+ const clickY = Math.round(event.clientY);
1037
+ const clickXPct = Number((event.clientX / vw * 100).toFixed(2));
1038
+ const clickYPct = Number((event.clientY / vh * 100).toFixed(2));
1039
+ const clickTag = interactiveEl.tagName.toLowerCase();
1040
+ const clickText = getClickLabel(interactiveEl);
1041
+ const clickSelector = getCssSelector(interactiveEl);
1042
+ const anchor = target.closest("a");
1043
+ let anchorInfo = null;
1044
+ if (anchor instanceof HTMLAnchorElement) {
1045
+ anchorInfo = classifyAnchorClick(anchor);
1046
+ }
1047
+ if (trackOutbound && anchorInfo) {
1048
+ if (anchorInfo.kind === "download") {
1049
+ enqueueEvent(getConfig(), {
1050
+ eventType: "download",
1051
+ eventName: anchorInfo.filename,
1052
+ clickTag,
1053
+ clickText,
1054
+ clickSelector,
1055
+ clickHref: anchorInfo.href,
1056
+ clickX,
1057
+ clickY,
1058
+ clickXPct,
1059
+ clickYPct,
1060
+ isOutbound: anchorInfo.isExternal,
1061
+ props: {
1062
+ filename: anchorInfo.filename,
1063
+ extension: anchorInfo.extension,
1064
+ targetHost: anchorInfo.targetHost
1065
+ }
1066
+ });
1067
+ } else if (anchorInfo.kind === "outbound") {
1068
+ enqueueEvent(getConfig(), {
1069
+ eventType: "outbound",
1070
+ eventName: anchorInfo.targetHost,
1071
+ clickTag,
1072
+ clickText,
1073
+ clickSelector,
1074
+ clickHref: anchorInfo.href,
1075
+ clickX,
1076
+ clickY,
1077
+ clickXPct,
1078
+ clickYPct,
1079
+ isOutbound: true,
1080
+ props: {
1081
+ targetHost: anchorInfo.targetHost,
1082
+ targetOrigin: anchorInfo.targetOrigin,
1083
+ targetPath: anchorInfo.targetPath
1084
+ }
1085
+ });
1086
+ }
1087
+ }
1088
+ if (trackClicks) {
1089
+ enqueueEvent(getConfig(), {
1090
+ eventType: "click",
1091
+ clickTag,
1092
+ clickText,
1093
+ clickSelector,
1094
+ clickHref: anchor?.getAttribute("href") ?? void 0,
1095
+ clickX,
1096
+ clickY,
1097
+ clickXPct,
1098
+ clickYPct,
1099
+ isOutbound: anchorInfo?.isExternal ?? void 0
1100
+ });
1101
+ }
1102
+ if (trackFriction) {
1103
+ const now = Date.now();
1104
+ while (recentClicks.length > 0 && now - recentClicks[0].ts > RAGE_WINDOW_MS) {
1105
+ recentClicks.shift();
1106
+ }
1107
+ const sample = {
1108
+ ts: now,
1109
+ x: clickX,
1110
+ y: clickY,
1111
+ selector: clickSelector,
1112
+ reported: false
1113
+ };
1114
+ recentClicks.push(sample);
1115
+ const cluster = recentClicks.filter(
1116
+ (c2) => c2.selector === sample.selector && Math.hypot(c2.x - sample.x, c2.y - sample.y) <= 80 || Math.hypot(c2.x - sample.x, c2.y - sample.y) <= RAGE_RADIUS_PX
1117
+ );
1118
+ if (cluster.length >= RAGE_MIN_CLICKS && !cluster.some((c2) => c2.reported)) {
1119
+ for (const c2 of cluster) c2.reported = true;
1120
+ enqueueEvent(getConfig(), {
1121
+ eventType: "rage_click",
1122
+ eventName: "rage_click",
1123
+ clickTag,
1124
+ clickText,
1125
+ clickSelector,
1126
+ clickX,
1127
+ clickY,
1128
+ clickXPct,
1129
+ clickYPct,
1130
+ props: {
1131
+ clickCount: cluster.length,
1132
+ windowMs: RAGE_WINDOW_MS
1133
+ }
1134
+ });
1135
+ }
1136
+ const isRootSurface = target === document.body || target === document.documentElement;
1137
+ const isInteractive = Boolean(target.closest(INTERACTIVE_SELECTOR));
1138
+ const hasTextSelection = Boolean(window.getSelection()?.toString().trim());
1139
+ if (!isRootSurface && !isInteractive && !hasTextSelection && document.body) {
1140
+ const startHref = window.location.href;
1141
+ let domMutated = false;
1142
+ const observer = new MutationObserver(() => {
1143
+ domMutated = true;
1144
+ });
1145
+ observer.observe(document.body, {
1146
+ childList: true,
1147
+ subtree: true,
1148
+ attributes: true,
1149
+ characterData: true
1150
+ });
1151
+ const timerId = window.setTimeout(() => {
1152
+ observer.disconnect();
1153
+ deadClickCleanups.delete(cleanupDeadClick);
1154
+ if (!domMutated && window.location.href === startHref) {
1155
+ enqueueEvent(getConfig(), {
1156
+ eventType: "dead_click",
1157
+ eventName: "dead_click",
1158
+ clickTag: target.tagName.toLowerCase(),
1159
+ clickText: getClickLabel(target),
1160
+ clickSelector: getCssSelector(target),
1161
+ clickX,
1162
+ clickY,
1163
+ clickXPct,
1164
+ clickYPct
1165
+ });
1166
+ }
1167
+ }, DEAD_CLICK_OBSERVE_MS);
1168
+ const cleanupDeadClick = () => {
1169
+ window.clearTimeout(timerId);
1170
+ observer.disconnect();
1171
+ };
1172
+ deadClickCleanups.add(cleanupDeadClick);
1173
+ }
1174
+ }
1175
+ };
1176
+ if (trackClicks || trackFriction || trackOutbound) {
1177
+ document.addEventListener("click", handleClick, { capture: true });
1178
+ }
1179
+ const ensureFormState = (form) => {
1180
+ let state = trackedForms.get(form);
1181
+ if (!state) {
1182
+ const fieldCount = form.querySelectorAll(
1183
+ "input:not([type='hidden']):not([type='submit']):not([type='button']), select, textarea"
1184
+ ).length;
1185
+ state = {
1186
+ formId: getFormIdentifier(form),
1187
+ fieldsTouched: /* @__PURE__ */ new Set(),
1188
+ fieldCount,
1189
+ startedAt: Date.now(),
1190
+ submitted: false,
1191
+ abandonedReported: false
1192
+ };
1193
+ trackedForms.set(form, state);
1194
+ }
1195
+ return state;
1196
+ };
1197
+ const handleFormInteraction = (event) => {
1198
+ if (!trackForms) return;
1199
+ const target = event.target;
1200
+ if (!target) return;
1201
+ const form = target.closest("form");
1202
+ if (!(form instanceof HTMLFormElement)) return;
1203
+ const descriptor = getFieldDescriptor(target);
1204
+ if (!descriptor) return;
1205
+ const state = ensureFormState(form);
1206
+ state.fieldsTouched.add(descriptor);
1207
+ };
1208
+ const handleFormSubmit = (event) => {
1209
+ if (!trackForms) return;
1210
+ const form = event.target;
1211
+ if (!(form instanceof HTMLFormElement)) return;
1212
+ const state = ensureFormState(form);
1213
+ state.submitted = true;
1214
+ enqueueEvent(getConfig(), {
1215
+ eventType: "form_submit",
1216
+ eventName: state.formId,
1217
+ formId: state.formId,
1218
+ durationMs: Math.max(0, Date.now() - state.startedAt),
1219
+ props: {
1220
+ formId: state.formId,
1221
+ fieldsTouchedCount: state.fieldsTouched.size,
1222
+ fieldCount: state.fieldCount
1223
+ }
1224
+ });
1225
+ };
1226
+ if (trackForms) {
1227
+ document.addEventListener("focusin", handleFormInteraction, {
1228
+ capture: true
1229
+ });
1230
+ document.addEventListener("change", handleFormInteraction, {
1231
+ capture: true
1232
+ });
1233
+ document.addEventListener("submit", handleFormSubmit, {
1234
+ capture: true
1235
+ });
1236
+ }
1237
+ const emitError = (kind, name, message, stack, extra) => {
1238
+ const dedupeKey = `${kind}:${message}`;
1239
+ if (reportedErrors.has(dedupeKey) || reportedErrors.size >= 50) return;
1240
+ reportedErrors.add(dedupeKey);
1241
+ enqueueEvent(getConfig(), {
1242
+ eventType: "error",
1243
+ eventName: name.slice(0, 120),
1244
+ errorMessage: message.slice(0, 500),
1245
+ errorStack: stack?.slice(0, 1500),
1246
+ props: {
1247
+ kind,
1248
+ ...extra
1249
+ }
1250
+ });
1251
+ };
1252
+ const handleWindowError = (event) => {
1253
+ const errObj = event.error instanceof Error ? event.error : null;
1254
+ const message = errObj?.message || event.message || "Unknown script error";
1255
+ const name = errObj?.name || "Error";
1256
+ emitError("error", name, message, errObj?.stack, {
1257
+ source: event.filename?.slice(0, 300),
1258
+ lineno: event.lineno,
1259
+ colno: event.colno
1260
+ });
1261
+ };
1262
+ const handleUnhandledRejection = (event) => {
1263
+ const reason = event.reason;
1264
+ const errObj = reason instanceof Error ? reason : null;
1265
+ const message = errObj?.message || (typeof reason === "string" ? reason : "Unhandled promise rejection");
1266
+ const name = errObj?.name || "UnhandledRejection";
1267
+ emitError("unhandledrejection", name, message, errObj?.stack);
1268
+ };
1269
+ if (trackErrors) {
1270
+ window.addEventListener("error", handleWindowError);
1271
+ window.addEventListener("unhandledrejection", handleUnhandledRejection);
1272
+ }
1273
+ if (trackWebVitals && !vitalsRegistered) {
1274
+ vitalsRegistered = true;
1275
+ const reportVital = (metric) => {
1276
+ const cfg = activeConfig;
1277
+ if (!cfg) return;
1278
+ const decimals = metric.name === "CLS" ? 4 : 2;
1279
+ const vitalPath = metric.name === "LCP" || metric.name === "TTFB" ? initialPath : currentVitalPath;
1280
+ enqueueEvent(cfg, {
1281
+ eventType: "web_vital",
1282
+ eventName: metric.name,
1283
+ path: vitalPath,
1284
+ metricName: metric.name,
1285
+ metricValue: Number(metric.value.toFixed(decimals)),
1286
+ metricRating: metric.rating,
1287
+ props: {
1288
+ id: metric.id,
1289
+ delta: Number(metric.delta.toFixed(decimals)),
1290
+ navigationType: metric.navigationType
1291
+ }
1292
+ });
1293
+ };
1294
+ U(reportVital);
1295
+ x(reportVital);
1296
+ P(reportVital);
1297
+ D(reportVital);
1298
+ }
1299
+ return () => {
1300
+ cancelPendingTitleTimer();
1301
+ if (scrollThrottleTimer !== null) {
1302
+ window.clearTimeout(scrollThrottleTimer);
1303
+ }
1304
+ if (engagementInterval !== null) {
1305
+ window.clearInterval(engagementInterval);
1306
+ }
1307
+ for (const cleanup of deadClickCleanups) cleanup();
1308
+ deadClickCleanups.clear();
1309
+ if (trackEngagement) {
1310
+ window.removeEventListener("pointerdown", markInteraction);
1311
+ window.removeEventListener("keydown", markInteraction);
1312
+ window.removeEventListener("touchstart", markInteraction);
1313
+ window.removeEventListener("wheel", markInteraction);
1314
+ window.removeEventListener("mousemove", handleMouseMove);
1315
+ }
1316
+ if (trackScrollDepth || trackEngagement) {
1317
+ window.removeEventListener("scroll", handleScroll);
1318
+ }
1319
+ if (trackPageviews || trackEngagement || trackForms || trackScrollDepth) {
1320
+ window.history.pushState = origPushState;
1321
+ window.history.replaceState = origReplaceState;
1322
+ window.removeEventListener("popstate", handlePopState);
1323
+ window.removeEventListener("pagehide", handlePageHide);
1324
+ document.removeEventListener("visibilitychange", handleVisibilityChange);
1325
+ }
1326
+ if (trackClicks || trackFriction || trackOutbound) {
1327
+ document.removeEventListener("click", handleClick, { capture: true });
1328
+ }
1329
+ if (trackForms) {
1330
+ document.removeEventListener("focusin", handleFormInteraction, {
1331
+ capture: true
1332
+ });
1333
+ document.removeEventListener("change", handleFormInteraction, {
1334
+ capture: true
1335
+ });
1336
+ document.removeEventListener("submit", handleFormSubmit, {
1337
+ capture: true
1338
+ });
1339
+ }
1340
+ if (trackErrors) {
1341
+ window.removeEventListener("error", handleWindowError);
1342
+ window.removeEventListener(
1343
+ "unhandledrejection",
1344
+ handleUnhandledRejection
1345
+ );
1346
+ }
1347
+ activeConfig = null;
1348
+ };
1349
+ }, [
1350
+ disabled,
1351
+ trackPageviews,
1352
+ trackClicks,
1353
+ trackScrollDepth,
1354
+ trackEngagement,
1355
+ trackFriction,
1356
+ trackOutbound,
1357
+ trackForms,
1358
+ trackErrors,
1359
+ trackWebVitals
1360
+ ]);
1361
+ return null;
1362
+ }
1363
+ export {
1364
+ Analytics,
1365
+ flushAnalytics,
1366
+ identifyUser,
1367
+ trackEvent
1368
+ };