@clicklore/browser 0.0.0-stage → 0.1.1

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.js ADDED
@@ -0,0 +1,2194 @@
1
+ //#region ../protocol/src/identity.ts
2
+ /** Attribute written by `@clicklore/annotate` at build time. */
3
+ const ANNOTATION_ATTR = "data-cl";
4
+ /** Put on an element (or ancestor) to stop its text from being captured. */
5
+ const MASK_ATTR = "data-cl-mask";
6
+ /** Put on an element (or ancestor) to stop all capture inside it. */
7
+ const IGNORE_ATTR = "data-cl-ignore";
8
+ /** Put on a field (or ancestor) to capture its value even when `captureInputValues` is off. */
9
+ const CAPTURE_ATTR = "data-cl-capture";
10
+ const SIGNATURE = /^[0-9a-z]{1,16}$/;
11
+ function parseAnnotation(value) {
12
+ if (!value) return null;
13
+ const interactive = value.charCodeAt(0) === 42;
14
+ let body = interactive ? value.slice(1) : value;
15
+ let signature;
16
+ const hash = body.lastIndexOf(" #");
17
+ if (hash > 0 && SIGNATURE.test(body.slice(hash + 2))) {
18
+ signature = body.slice(hash + 2);
19
+ body = body.slice(0, hash);
20
+ }
21
+ const space = body.indexOf(" ");
22
+ if (space <= 0 || space === body.length - 1) return null;
23
+ return {
24
+ interactive,
25
+ component: body.slice(0, space),
26
+ source: body.slice(space + 1),
27
+ signature
28
+ };
29
+ }
30
+ function identityKey(input) {
31
+ if (input.track) return `t|${input.track}`;
32
+ if (input.source && input.signature) return `a|${input.source.replace(/:\d+$/, "")}|${input.component ?? ""}|${input.signature}|${input.kind}`;
33
+ if (input.source) return `s|${input.source}|${input.kind}`;
34
+ return `f|${input.route}|${input.kind}|${input.label ?? ""}|${input.selector ?? ""}`;
35
+ }
36
+ function elementId(input) {
37
+ return cyrb53(identityKey(input)).toString(36);
38
+ }
39
+ /**
40
+ * cyrb53: fast, well-distributed 53-bit string hash (public domain, bryc).
41
+ * 53 bits keep ids exact as JS numbers; collision odds stay negligible at per-project scale.
42
+ */
43
+ function cyrb53(str, seed = 0) {
44
+ let h1 = 3735928559 ^ seed;
45
+ let h2 = 1103547991 ^ seed;
46
+ for (let i = 0; i < str.length; i++) {
47
+ const ch = str.charCodeAt(i);
48
+ h1 = Math.imul(h1 ^ ch, 2654435761);
49
+ h2 = Math.imul(h2 ^ ch, 1597334677);
50
+ }
51
+ h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507);
52
+ h1 ^= Math.imul(h2 ^ h2 >>> 13, 3266489909);
53
+ h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507);
54
+ h2 ^= Math.imul(h1 ^ h1 >>> 13, 3266489909);
55
+ return 4294967296 * (2097151 & h2) + (h1 >>> 0);
56
+ }
57
+ //#endregion
58
+ //#region ../protocol/src/wire.ts
59
+ const INGEST_PATH = "/v1/b";
60
+ /**
61
+ * Ingest response header set to `1` while someone watches the project's Live panel; the SDK then
62
+ * flushes every ~0.5s instead of every few seconds, so testers see their clicks immediately.
63
+ */
64
+ const LIVE_HEADER = "x-cl-live";
65
+ /** Hard limits enforced by the server. The SDK stays well below them. */
66
+ const LIMITS = {
67
+ maxBodyBytes: 524288,
68
+ maxEventsPerBatch: 500,
69
+ maxElementDefsPerBatch: 500,
70
+ maxImpressionsPerEvent: 300,
71
+ maxLabelLength: 80,
72
+ maxMessageLength: 300,
73
+ maxNameLength: 100,
74
+ maxPropKeys: 30,
75
+ maxPropValueLength: 300,
76
+ /** captured field values (opt-in) */
77
+ maxValueLength: 300,
78
+ maxRouteLength: 300,
79
+ maxIdLength: 128,
80
+ /** Events whose timestamp is further than this from server time (after skew correction) are dropped. */
81
+ maxClockDriftMs: 864e5
82
+ };
83
+ //#endregion
84
+ //#region src/safe.ts
85
+ /** Keep synchronous SDK failures out of callbacks owned by the host app or browser. */
86
+ function safe(fn) {
87
+ return (...args) => {
88
+ try {
89
+ return fn(...args);
90
+ } catch {
91
+ return;
92
+ }
93
+ };
94
+ }
95
+ /** Restore a patch only if no other code has wrapped it since. */
96
+ function patch(target, key, wrap) {
97
+ const original = target[key];
98
+ const patched = wrap(original);
99
+ safe(() => target[key] = patched)();
100
+ return safe(() => {
101
+ if (target[key] === patched) target[key] = original;
102
+ });
103
+ }
104
+ //#endregion
105
+ //#region src/context.ts
106
+ function listen(target, type, handler, options) {
107
+ const opts = {
108
+ capture: true,
109
+ passive: true,
110
+ ...options
111
+ };
112
+ const guarded = safe(handler);
113
+ safe(() => target.addEventListener(type, guarded, opts))();
114
+ return safe(() => target.removeEventListener(type, guarded, opts));
115
+ }
116
+ //#endregion
117
+ //#region src/activity.ts
118
+ /**
119
+ * Detects whether the page reacted to a user action. Observers only run while at least one watch
120
+ * window is open, so idle pages pay nothing.
121
+ */
122
+ function createActivity(doc) {
123
+ const open = /* @__PURE__ */ new Set();
124
+ let observer = null;
125
+ let offs = [];
126
+ const signal = safe(() => {
127
+ for (const w of open) w.active = true;
128
+ });
129
+ function start() {
130
+ if (observer) return;
131
+ observer = new MutationObserver(signal);
132
+ observer.observe(doc.documentElement, {
133
+ subtree: true,
134
+ childList: true,
135
+ attributes: true,
136
+ characterData: true
137
+ });
138
+ offs = [listen(doc, "focusin", signal), listen(doc, "scroll", signal)];
139
+ if (doc.defaultView) offs.push(listen(doc.defaultView, "blur", signal, { capture: false }));
140
+ }
141
+ function stop() {
142
+ if (!observer) return;
143
+ observer.disconnect();
144
+ observer = null;
145
+ for (const off of offs.splice(0)) off();
146
+ }
147
+ return {
148
+ signal,
149
+ watch(ms, done) {
150
+ const w = { active: false };
151
+ open.add(w);
152
+ start();
153
+ const finish = safe(() => {
154
+ if (!open.delete(w)) return;
155
+ clearTimeout(timer);
156
+ if (open.size === 0) stop();
157
+ done(w.active);
158
+ });
159
+ const timer = setTimeout(finish, ms);
160
+ return finish;
161
+ },
162
+ dispose() {
163
+ open.clear();
164
+ stop();
165
+ }
166
+ };
167
+ }
168
+ //#endregion
169
+ //#region src/config.ts
170
+ const SDK_VERSION = "0.1.1";
171
+ function resolveConfig(config) {
172
+ const key = typeof config?.projectKey === "string" && config.projectKey.trim();
173
+ if (!key) throw new Error("init() requires a projectKey");
174
+ if (typeof config.host !== "string" || !config.host.trim()) throw new Error("init() requires a host");
175
+ const host = new URL(config.host, document.baseURI);
176
+ if (!/^https?:$/.test(host.protocol) || host.search || host.hash || host.username || host.password) throw new Error("invalid ingest host");
177
+ return {
178
+ projectKey: key,
179
+ endpoint: `${host.origin}${host.pathname.replace(/\/+$/, "")}${INGEST_PATH}?k=${encodeURIComponent(key)}`,
180
+ capture: {
181
+ pages: true,
182
+ clicks: true,
183
+ impressions: true,
184
+ forms: true,
185
+ errors: true,
186
+ network: true,
187
+ slowInteractions: true,
188
+ copy: true,
189
+ ...config.capture
190
+ },
191
+ trackAttribute: config.trackAttribute ?? "data-track",
192
+ maskAllText: config.maskAllText ?? false,
193
+ captureInputValues: config.captureInputValues ?? false,
194
+ requireConsent: config.requireConsent ?? false,
195
+ respectDoNotTrack: config.respectDoNotTrack ?? false,
196
+ route: config.route,
197
+ sanitizeUrl: config.sanitizeUrl,
198
+ slowInteractionMs: config.slowInteractionMs ?? 500,
199
+ flushIntervalMs: config.flushIntervalMs ?? 5e3,
200
+ flushAt: config.flushAt ?? 50,
201
+ sessionTimeoutMs: config.sessionTimeoutMs ?? 18e5,
202
+ storagePrefix: config.storagePrefix ?? "cl",
203
+ debug: config.debug ?? false
204
+ };
205
+ }
206
+ //#endregion
207
+ //#region src/ids.ts
208
+ function randomBytes(n) {
209
+ const bytes = new Uint8Array(n);
210
+ if (typeof crypto !== "undefined" && crypto.getRandomValues) crypto.getRandomValues(bytes);
211
+ else for (let i = 0; i < n; i++) bytes[i] = Math.random() * 256 | 0;
212
+ return bytes;
213
+ }
214
+ function format(bytes) {
215
+ let hex = "";
216
+ for (let i = 0; i < bytes.length; i++) hex += bytes[i].toString(16).padStart(2, "0");
217
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
218
+ }
219
+ function uuidv4() {
220
+ const b = randomBytes(16);
221
+ b[6] = b[6] & 15 | 64;
222
+ b[8] = b[8] & 63 | 128;
223
+ return format(b);
224
+ }
225
+ /** Time-ordered UUID (RFC 9562 v7): sorts and compresses well as a session id. */
226
+ function uuidv7(now = Date.now()) {
227
+ const b = randomBytes(16);
228
+ let ms = now;
229
+ for (let i = 5; i >= 0; i--) {
230
+ b[i] = ms % 256;
231
+ ms = Math.floor(ms / 256);
232
+ }
233
+ b[6] = b[6] & 15 | 112;
234
+ b[8] = b[8] & 63 | 128;
235
+ return format(b);
236
+ }
237
+ /** Random base36 id (64 bits), e.g. batch ids the server uses to drop repeated sends. */
238
+ function randomId() {
239
+ const view = new DataView(randomBytes(8).buffer);
240
+ return view.getUint32(0).toString(36) + view.getUint32(4).toString(36).padStart(7, "0");
241
+ }
242
+ /** UUID pattern, shared by the id check, the route heuristic and text redaction. */
243
+ const UUID_PATTERN = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
244
+ const UUID_RE = new RegExp(`^${UUID_PATTERN}$`, "i");
245
+ function isUuid(value) {
246
+ return typeof value === "string" && UUID_RE.test(value);
247
+ }
248
+ //#endregion
249
+ //#region src/batcher.ts
250
+ const MAX_EVENTS_PER_BATCH = 100;
251
+ /**
252
+ * Holds events until they are flushed. Element definitions ride along with the first batch that
253
+ * needs them (once per page load), user traits with the batch after `identify()`.
254
+ */
255
+ var Batcher = class {
256
+ #queue = [];
257
+ #defs = /* @__PURE__ */ new Map();
258
+ #sentDefs = /* @__PURE__ */ new Set();
259
+ #traits;
260
+ get size() {
261
+ return this.#queue.length;
262
+ }
263
+ push(event, page) {
264
+ this.#queue.push({
265
+ event,
266
+ page
267
+ });
268
+ }
269
+ /** Registers a definition unless it was already sent during this page load. */
270
+ define(def) {
271
+ if (!this.#sentDefs.has(def.id)) this.#defs.set(def.id, def);
272
+ }
273
+ /** Traits ride with the next batch; `undefined` drops unsent ones (the user changed). */
274
+ setTraits(traits) {
275
+ this.#traits = traits && {
276
+ ...this.#traits,
277
+ ...traits
278
+ };
279
+ }
280
+ /** Late route resolution: adapters report the router's template shortly after navigation. */
281
+ rewriteRoute(page, route) {
282
+ for (const q of this.#queue) if (q.page === page) q.event.p = route;
283
+ }
284
+ clear() {
285
+ this.#queue = [];
286
+ this.#defs.clear();
287
+ this.#traits = void 0;
288
+ }
289
+ /**
290
+ * Drains up to one batch worth of events. Definitions are capped too (the server rejects more);
291
+ * the rest ride with the next batch.
292
+ */
293
+ take(identity) {
294
+ if (this.#queue.length === 0 && !this.#traits) return null;
295
+ const events = this.#queue.splice(0, MAX_EVENTS_PER_BATCH).map((q) => q.event);
296
+ const batch = {
297
+ v: 1,
298
+ i: randomId(),
299
+ sdk: `web/${SDK_VERSION}`,
300
+ at: 0,
301
+ a: identity.anonId,
302
+ s: identity.sessionId,
303
+ e: events
304
+ };
305
+ if (identity.userId) batch.u = identity.userId;
306
+ if (identity.groups && Object.keys(identity.groups).length > 0) batch.g = identity.groups;
307
+ if (this.#traits) {
308
+ batch.ut = this.#traits;
309
+ this.#traits = void 0;
310
+ }
311
+ if (this.#defs.size > 0) {
312
+ batch.el = [...this.#defs.values()].slice(0, LIMITS.maxElementDefsPerBatch);
313
+ for (const def of batch.el) {
314
+ this.#sentDefs.add(def.id);
315
+ this.#defs.delete(def.id);
316
+ }
317
+ }
318
+ return batch;
319
+ }
320
+ };
321
+ //#endregion
322
+ //#region src/routes.ts
323
+ /**
324
+ * Heuristic route templates: `/projects/8f2c…/settings` -> `/projects/:id/settings`.
325
+ * Framework adapters replace this with the router's real template via `setRoute()`.
326
+ */
327
+ const NUMERIC = /^\d+$/;
328
+ const HEX = /^[0-9a-f]{12,}$/i;
329
+ /** nanoid / cuid / base62 ids: long, mixes digits and letters, no word separators. */
330
+ const OPAQUE = /^(?=.*\d)(?=.*[a-z])[a-z0-9_-]{16,}$/i;
331
+ const JWT = /^ey[\w-]{6,}(?:\.[\w-]*){2,4}$/;
332
+ const EMAIL$1 = /[^/@]+@[^/@]+/;
333
+ /** Prefixed ids such as `cl_x8f2k`, `prj_123`, `usr-9a8b7c`. */
334
+ const PREFIXED = /^[a-z]{2,6}[_-](?=.*\d)[a-z0-9]{4,}$/i;
335
+ function isIdSegment(segment) {
336
+ return NUMERIC.test(segment) || isUuid(segment) || HEX.test(segment) || OPAQUE.test(segment) || PREFIXED.test(segment) || JWT.test(segment) || EMAIL$1.test(segment);
337
+ }
338
+ function routeTemplate(pathname) {
339
+ if (pathname === "" || pathname === "/") return "/";
340
+ let out = "";
341
+ for (const raw of pathname.split("/")) {
342
+ if (!raw) continue;
343
+ let segment = raw;
344
+ try {
345
+ segment = decodeURIComponent(raw);
346
+ } catch {}
347
+ out += `/${isIdSegment(segment) ? ":id" : segment}`;
348
+ }
349
+ return out || "/";
350
+ }
351
+ //#endregion
352
+ //#region src/text.ts
353
+ /**
354
+ * Text hygiene for anything captured from the page: collapse whitespace, redact values that look
355
+ * personal or secret, truncate. Applied to labels, titles, error messages and captured values.
356
+ * Custom event props get the personal part only (emails, long numbers): ids and tokens there are
357
+ * usually what the developer meant to send. User traits are sent as given.
358
+ */
359
+ const WHITESPACE = /\s+/g;
360
+ const EMAIL = /[^\s@<>()[\]"']+@[^\s@<>()[\]"']+\.[a-z]{2,}/gi;
361
+ const UUID = new RegExp(`\\b${UUID_PATTERN}\\b`, "gi");
362
+ const TOKEN = /\b(?=[A-Za-z0-9_-]*\d)(?=[A-Za-z0-9_-]*[A-Za-z])[A-Za-z0-9_-]{24,}\b/g;
363
+ const LONG_NUMBER = /\+?\d(?:[\d\s().-]{6,}\d)/g;
364
+ const ISO_DATE = /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/;
365
+ const YEAR_RANGE = /^(?:19|20)\d\d\s+-\s+(?:19|20)\d\d$/;
366
+ function redactNumber(value, offset, text) {
367
+ const years = text[offset - 1] === "Q" && /^[1-4] /.test(value) ? value.slice(2) : value;
368
+ return ISO_DATE.test(value) || YEAR_RANGE.test(years) ? value : "[number]";
369
+ }
370
+ function redact(text) {
371
+ return text.replace(EMAIL, "[email]").replace(UUID, "[id]").replace(TOKEN, "[token]").replace(LONG_NUMBER, redactNumber);
372
+ }
373
+ /** Emails and long digit runs (phone, card and account numbers), for custom event props. */
374
+ function redactPersonal(text) {
375
+ return text.replace(EMAIL, "[email]").replace(LONG_NUMBER, redactNumber);
376
+ }
377
+ /**
378
+ * Cuts a string to at most `max` UTF-16 units without splitting a surrogate pair, and replaces
379
+ * any lone surrogate: half an emoji is invalid JSON for ClickHouse and would fail the whole insert.
380
+ */
381
+ function truncate(text, max) {
382
+ let out = text.length > max ? text.slice(0, max) : text;
383
+ const last = out.charCodeAt(out.length - 1);
384
+ if (out.length < text.length && last >= 55296 && last <= 56319) out = out.slice(0, -1);
385
+ return typeof out.toWellFormed === "function" ? out.toWellFormed() : out;
386
+ }
387
+ function clean(text, max) {
388
+ if (!text) return "";
389
+ const collapsed = text.replace(WHITESPACE, " ").trim();
390
+ if (!collapsed) return "";
391
+ const safe = redact(truncate(collapsed, max * 4));
392
+ return safe.length > max ? `${truncate(safe, max - 1)}…` : safe;
393
+ }
394
+ //#endregion
395
+ //#region src/elements.ts
396
+ /**
397
+ * Element resolution and description: which element did the user interact with, what kind of
398
+ * element is it, what is it called, and what is its stable identity?
399
+ */
400
+ const INTERACTIVE_ROLES = "button,link,tab,menuitem,menuitemcheckbox,menuitemradio,checkbox,radio,switch,option,combobox,treeitem".split(",");
401
+ function interactiveSelector(trackAttr) {
402
+ return [
403
+ "a[href]",
404
+ "button",
405
+ "input:not([type=hidden])",
406
+ "select",
407
+ "textarea",
408
+ "summary",
409
+ "[contenteditable=\"\"]",
410
+ "[contenteditable=true]",
411
+ `[${trackAttr}]`,
412
+ `[${ANNOTATION_ATTR}^="*"]`,
413
+ ...INTERACTIVE_ROLES.map((r) => `[role=${r}]`)
414
+ ].join(",");
415
+ }
416
+ const ROLE_KIND = {
417
+ button: "button",
418
+ link: "link",
419
+ tab: "tab",
420
+ menuitem: "menuitem",
421
+ menuitemcheckbox: "menuitem",
422
+ menuitemradio: "menuitem",
423
+ checkbox: "checkbox",
424
+ radio: "radio",
425
+ switch: "switch",
426
+ option: "option",
427
+ combobox: "select"
428
+ };
429
+ const INPUT_KIND = {
430
+ checkbox: "checkbox",
431
+ radio: "radio",
432
+ button: "button",
433
+ submit: "button",
434
+ reset: "button",
435
+ image: "button"
436
+ };
437
+ /**
438
+ * Elements that only look clickable (`cursor: pointer`, e.g. a styled span or a `div` with a React
439
+ * onClick and no annotation). They act as buttons, so they are named and classified like buttons.
440
+ */
441
+ const pointerTargets = /* @__PURE__ */ new WeakSet();
442
+ function kindOf(el) {
443
+ const role = el.getAttribute("role");
444
+ if (role && ROLE_KIND[role]) return ROLE_KIND[role];
445
+ if (pointerTargets.has(el)) return "button";
446
+ switch (el.localName) {
447
+ case "a": return "link";
448
+ case "button":
449
+ case "summary": return "button";
450
+ case "select": return "select";
451
+ case "textarea": return "textarea";
452
+ case "form": return "form";
453
+ case "input": return INPUT_KIND[el.type] ?? "input";
454
+ default: return "other";
455
+ }
456
+ }
457
+ /** Kinds whose visible text names the control (as opposed to fields, whose text is user data). */
458
+ const TEXT_LABELLED = /* @__PURE__ */ new Set([
459
+ "button",
460
+ "link",
461
+ "tab",
462
+ "menuitem",
463
+ "option",
464
+ "checkbox",
465
+ "radio",
466
+ "switch"
467
+ ]);
468
+ const MAX_CAPTION_SOURCE = 200;
469
+ const MAX_SHORT_CAPTION = 32;
470
+ function textOf(el) {
471
+ return el?.textContent ?? "";
472
+ }
473
+ function labelledBy(el) {
474
+ const ids = el.getAttribute("aria-labelledby");
475
+ if (!ids) return "";
476
+ const doc = el.ownerDocument;
477
+ return ids.split(/\s+/).map((id) => textOf(doc.getElementById(id))).join(" ");
478
+ }
479
+ function fieldLabel(el) {
480
+ const labels = el.labels;
481
+ if (labels && labels.length > 0) return textOf(labels[0]);
482
+ return el.getAttribute("placeholder") || el.getAttribute("name") || "";
483
+ }
484
+ function iconLabel(el) {
485
+ const img = el.querySelector("img[alt],svg[aria-label],svg title,[aria-label]");
486
+ if (!img) return "";
487
+ return img.getAttribute("alt") || img.getAttribute("aria-label") || textOf(img);
488
+ }
489
+ /** Approximates the accessible name without layout-dependent APIs (no innerText). */
490
+ function rawLabel(el, kind) {
491
+ const aria = el.getAttribute("aria-label") || labelledBy(el);
492
+ if (aria) return aria;
493
+ if (el.isContentEditable || el.getAttribute("role") === "textbox") return el.getAttribute("aria-placeholder") || "";
494
+ if (kind === "input" || kind === "textarea" || kind === "select") return fieldLabel(el);
495
+ if (el.localName === "input") {
496
+ const input = el;
497
+ if (kind === "button") return input.value || input.alt || "";
498
+ return fieldLabel(el);
499
+ }
500
+ if (kind === "form") return el.getAttribute("name") || el.id || "";
501
+ if (TEXT_LABELLED.has(kind) && !pointerTargets.has(el)) {
502
+ const text = textOf(el);
503
+ if (text.trim() && text.length <= MAX_CAPTION_SOURCE) return text;
504
+ return iconLabel(el) || el.getAttribute("title") || "";
505
+ }
506
+ const title = el.getAttribute("title");
507
+ if (title) return title;
508
+ if (!el.childElementCount && (pointerTargets.has(el) || el.hasAttribute("data-cl"))) {
509
+ const caption = textOf(el).trim();
510
+ if (caption.length <= MAX_SHORT_CAPTION) return caption;
511
+ }
512
+ return "";
513
+ }
514
+ const UNSTABLE_ID = /\d{3,}|^:|:r[0-9a-z]+:|^radix-|^headlessui-|^react-aria|^mui-|^ember\d|^[a-f0-9-]{16,}$/i;
515
+ const TEST_ATTRS = [
516
+ "data-testid",
517
+ "data-test",
518
+ "data-cy",
519
+ "data-qa"
520
+ ];
521
+ const MAX_SELECTOR_VALUE = 40;
522
+ /** A test id or name worth putting in a selector: not generated, cut to a bounded length. */
523
+ function stableValue(value) {
524
+ return value && !UNSTABLE_ID.test(value) ? truncate(value, MAX_SELECTOR_VALUE) : null;
525
+ }
526
+ /** Short selector built only from attributes that survive restyling and re-renders. */
527
+ function stableSelector(el) {
528
+ const parts = [];
529
+ let cur = el;
530
+ for (let depth = 0; cur && depth < 4 && cur.localName !== "body"; depth++) {
531
+ let part = cur.localName;
532
+ if (cur.id && cur.id.length < MAX_SELECTOR_VALUE && !UNSTABLE_ID.test(cur.id)) {
533
+ parts.unshift(`${part}#${cur.id}`);
534
+ break;
535
+ }
536
+ const testAttr = TEST_ATTRS.find((a) => stableValue(cur.getAttribute(a)));
537
+ if (testAttr) {
538
+ parts.unshift(`${part}[${testAttr}="${stableValue(cur.getAttribute(testAttr))}"]`);
539
+ break;
540
+ }
541
+ const name = stableValue(cur.getAttribute("name"));
542
+ if (name) part += `[name="${name}"]`;
543
+ else if (cur.localName === "input") part += `[type=${cur.type}]`;
544
+ parts.unshift(part);
545
+ cur = cur.parentElement;
546
+ }
547
+ return parts.join(">");
548
+ }
549
+ function hrefPath(el) {
550
+ const href = el.getAttribute("href");
551
+ if (!href || href.startsWith("#") || href.startsWith("javascript:")) return void 0;
552
+ try {
553
+ const url = new URL(href, el.ownerDocument.baseURI);
554
+ if (url.protocol !== "http:" && url.protocol !== "https:") return url.protocol;
555
+ const path = routeTemplate(url.pathname);
556
+ return url.origin === el.ownerDocument.location?.origin ? path : `${url.host}${path}`;
557
+ } catch {
558
+ return;
559
+ }
560
+ }
561
+ /**
562
+ * App chrome (navigation, header, sidebar, footer) renders the same controls on every route, so
563
+ * their fallback identity must not include the route, or one menu button becomes N elements.
564
+ */
565
+ const CHROME = "nav,header,aside,footer,[role=navigation],[role=banner],[role=complementary],[role=contentinfo]";
566
+ /** The element's current caption, cleaned and redacted; empty when masked. */
567
+ function labelOf(el, kind, maskAllText) {
568
+ if (maskAllText || isMasked(el)) return "";
569
+ return clean(rawLabel(el, kind), LIMITS.maxLabelLength);
570
+ }
571
+ /** Builds the element definition (and its stable id) for any element. */
572
+ function describe(el, opts) {
573
+ const kind = kindOf(el);
574
+ const annotation = parseAnnotation(el.getAttribute(ANNOTATION_ATTR));
575
+ const track = el.getAttribute(opts.trackAttr) || void 0;
576
+ const label = labelOf(el, kind, opts.maskAllText);
577
+ const selector = annotation || track ? void 0 : stableSelector(el);
578
+ const route = selector && el.closest(CHROME) ? "*" : opts.route;
579
+ const def = {
580
+ id: elementId({
581
+ kind,
582
+ track,
583
+ source: annotation?.source,
584
+ component: annotation?.component,
585
+ signature: annotation?.signature,
586
+ route,
587
+ label,
588
+ selector
589
+ }),
590
+ k: kind,
591
+ tag: el.localName
592
+ };
593
+ if (label) def.l = label;
594
+ if (track) def.tr = truncate(track, LIMITS.maxNameLength);
595
+ if (annotation) {
596
+ def.c = annotation.component;
597
+ def.s = annotation.source;
598
+ }
599
+ if (selector) def.sel = selector;
600
+ const h = kind === "link" ? hrefPath(el) : void 0;
601
+ if (h) def.h = h;
602
+ return def;
603
+ }
604
+ function hasAncestor(el, selector) {
605
+ for (let cur = el; cur; cur = cur.getRootNode().host) if (cur.closest(selector)) return true;
606
+ return false;
607
+ }
608
+ const isIgnored = (el) => hasAncestor(el, `[${IGNORE_ATTR}]`);
609
+ const isMasked = (el) => hasAncestor(el, `[${MASK_ATTR}]`);
610
+ /**
611
+ * Finds the element a user meant to interact with: the nearest interactive element on the event
612
+ * path, falling back to a `cursor: pointer` ancestor (catches `div onClick` without annotations).
613
+ * Null for clicks on a label with a control: the browser follows them with a click on the
614
+ * control, and that one is the interaction.
615
+ */
616
+ function resolveTarget(path, interactive) {
617
+ let firstElement = null;
618
+ for (const node of path) {
619
+ if (!(node instanceof Element)) continue;
620
+ if (node.localName === "body" || node.localName === "html") break;
621
+ if (!firstElement && isIgnored(node)) return null;
622
+ if (node.localName === "label" && node.control) return null;
623
+ firstElement ??= node;
624
+ if (node.matches(interactive)) return node;
625
+ }
626
+ if (!firstElement) return null;
627
+ let cur = firstElement;
628
+ for (let depth = 0; cur && depth < 4 && cur.localName !== "body"; depth++) {
629
+ if (getComputedStyle(cur).cursor === "pointer") {
630
+ pointerTargets.add(cur);
631
+ return cur;
632
+ }
633
+ cur = cur.parentElement;
634
+ }
635
+ return null;
636
+ }
637
+ /** Nearest element worth naming for passive interactions (copy): annotated, tracked or any. */
638
+ function contextElement(node, trackAttr) {
639
+ const el = node instanceof Element ? node : node?.parentElement ?? null;
640
+ if (!el || isIgnored(el)) return null;
641
+ return el.closest(`[data-cl],[${trackAttr}]`) ?? el;
642
+ }
643
+ //#endregion
644
+ //#region src/capture/clicks.ts
645
+ /** A click is a rage click when ≥3 land within 1s of each other inside a 30px radius. */
646
+ const RAGE_WINDOW_MS = 1e3;
647
+ const RAGE_RADIUS_PX = 30;
648
+ const RAGE_MIN_CLICKS = 3;
649
+ /** A click with no visible reaction within this window is a dead click. */
650
+ const DEAD_WINDOW_MS = 1e3;
651
+ var RageDetector = class {
652
+ onRage;
653
+ burst = null;
654
+ finish = safe(() => this.end());
655
+ constructor(onRage) {
656
+ this.onRage = onRage;
657
+ }
658
+ add(time, x, y, ref) {
659
+ const b = this.burst;
660
+ if (b && time - b.last <= RAGE_WINDOW_MS && Math.hypot(x - b.x, y - b.y) <= RAGE_RADIUS_PX) {
661
+ clearTimeout(b.timer);
662
+ b.n++;
663
+ b.last = time;
664
+ b.timer = setTimeout(this.finish, RAGE_WINDOW_MS);
665
+ return;
666
+ }
667
+ this.end();
668
+ this.burst = {
669
+ ref,
670
+ x,
671
+ y,
672
+ n: 1,
673
+ last: time,
674
+ timer: setTimeout(this.finish, RAGE_WINDOW_MS)
675
+ };
676
+ }
677
+ end() {
678
+ const b = this.burst;
679
+ if (!b) return;
680
+ clearTimeout(b.timer);
681
+ this.burst = null;
682
+ if (b.n >= RAGE_MIN_CLICKS) this.onRage(b.ref, b.n);
683
+ }
684
+ };
685
+ /** Controls whose effect is often invisible to the DOM (focus, native state) can't be "dead". */
686
+ const NEVER_DEAD = /* @__PURE__ */ new Set([
687
+ "input",
688
+ "textarea",
689
+ "select",
690
+ "checkbox",
691
+ "radio",
692
+ "option",
693
+ "form"
694
+ ]);
695
+ function canBeDead(el, e) {
696
+ if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return false;
697
+ if (NEVER_DEAD.has(kindOf(el)) || el.isContentEditable) return false;
698
+ if (el.localName === "a" && (el.hasAttribute("download") || el.getAttribute("target") === "_blank")) return false;
699
+ return !el.disabled;
700
+ }
701
+ const clicks = (ctx) => {
702
+ const rage = new RageDetector((ref, n) => ctx.emit({
703
+ t: "rc",
704
+ ...ref,
705
+ n
706
+ }));
707
+ /**
708
+ * Open dead-click windows by element id. A burst on one element yields one dead click, not five.
709
+ * Pressing anywhere else closes the other windows early: whatever happens next (focus moving at
710
+ * pointerdown, the next click's effects) reacts to the new interaction, not the old one.
711
+ */
712
+ const watching = /* @__PURE__ */ new Map();
713
+ const offDown = listen(document, "pointerdown", (e) => {
714
+ const target = e.target instanceof Node ? e.target : null;
715
+ for (const w of watching.values()) if (!target || !w.element.contains(target)) w.finish();
716
+ });
717
+ const off = listen(document, "click", (e) => {
718
+ if (!e.isTrusted) return;
719
+ const target = resolveTarget(e.composedPath(), ctx.interactive);
720
+ if (!target) return;
721
+ const ref = ctx.ref(target);
722
+ const time = Date.now();
723
+ ctx.emit({
724
+ t: "ck",
725
+ ...ref
726
+ });
727
+ ctx.markClick(ref);
728
+ rage.add(time, e.clientX, e.clientY, ref);
729
+ if (canBeDead(target, e) && !watching.has(ref.el)) {
730
+ const finish = ctx.activity.watch(DEAD_WINDOW_MS, (active) => {
731
+ watching.delete(ref.el);
732
+ if (!active) ctx.emit({
733
+ t: "dc",
734
+ ...ref
735
+ });
736
+ });
737
+ watching.set(ref.el, {
738
+ element: target,
739
+ finish
740
+ });
741
+ }
742
+ });
743
+ return () => {
744
+ off();
745
+ offDown();
746
+ rage.end();
747
+ };
748
+ };
749
+ //#endregion
750
+ //#region src/capture/copy.ts
751
+ /** Copying is a strong "this was useful" signal. Only the element is recorded, never the text. */
752
+ const copy = (ctx) => listen(document, "copy", () => {
753
+ const el = contextElement(document.getSelection()?.anchorNode ?? null, ctx.config.trackAttribute);
754
+ if (!el) return;
755
+ ctx.emit({
756
+ t: "cp",
757
+ ...ctx.ref(el)
758
+ });
759
+ });
760
+ //#endregion
761
+ //#region src/capture/errors.ts
762
+ /** Errors within this window after a click are attributed to the clicked element. */
763
+ const ERROR_CLICK_WINDOW_MS = 1e3;
764
+ const MAX_ERRORS_PER_PAGE = 10;
765
+ /** Browser noise that says nothing about the app. */
766
+ const IGNORED = [
767
+ /^Script error\.?$/,
768
+ /ResizeObserver loop/,
769
+ /^Non-Error promise rejection captured/
770
+ ];
771
+ function sourceOf(filename, line) {
772
+ if (!filename) return void 0;
773
+ try {
774
+ const url = new URL(filename, location.href);
775
+ const where = url.origin === location.origin ? url.pathname : `${url.host}${url.pathname}`;
776
+ return line ? `${where}:${line}` : where;
777
+ } catch {
778
+ return;
779
+ }
780
+ }
781
+ function reasonMessage(reason) {
782
+ if (reason instanceof Error) return `${reason.name}: ${reason.message}`;
783
+ if (typeof reason === "string") return reason;
784
+ return "Unhandled promise rejection";
785
+ }
786
+ const errors = (ctx) => {
787
+ let seen = /* @__PURE__ */ new Set();
788
+ ctx.onPage({ start() {
789
+ seen = /* @__PURE__ */ new Set();
790
+ } });
791
+ function report(raw, src) {
792
+ const m = clean(raw, LIMITS.maxMessageLength);
793
+ if (!m || IGNORED.some((re) => re.test(m))) return;
794
+ if (!seen.has(m) && seen.size < MAX_ERRORS_PER_PAGE) {
795
+ seen.add(m);
796
+ ctx.emit(src ? {
797
+ t: "er",
798
+ m,
799
+ src
800
+ } : {
801
+ t: "er",
802
+ m
803
+ });
804
+ }
805
+ const click = ctx.recentClick(ERROR_CLICK_WINDOW_MS);
806
+ if (click && !click.errored) {
807
+ click.errored = true;
808
+ ctx.emit({
809
+ t: "ec",
810
+ ...click.ref,
811
+ m
812
+ });
813
+ }
814
+ }
815
+ const offError = listen(window, "error", (e) => {
816
+ if (!(e instanceof ErrorEvent) || !e.message) return;
817
+ report(e.error instanceof Error ? `${e.error.name}: ${e.error.message}` : e.message, sourceOf(e.filename, e.lineno));
818
+ });
819
+ const offRejection = listen(window, "unhandledrejection", (e) => report(reasonMessage(e.reason)));
820
+ return () => {
821
+ offError();
822
+ offRejection();
823
+ };
824
+ };
825
+ //#endregion
826
+ //#region src/capture/forms.ts
827
+ const FIELD = "input:not([type=hidden]),textarea,select,[contenteditable=\"\"],[contenteditable=true]";
828
+ /** Frameworks mark fields invalid asynchronously after a submit attempt. */
829
+ const ARIA_INVALID_DELAY_MS = 400;
830
+ function fieldOf(target) {
831
+ if (!(target instanceof Element)) return null;
832
+ const field = target.closest(FIELD);
833
+ return field && !isIgnored(field) ? field : null;
834
+ }
835
+ /**
836
+ * Field interaction without values: which fields users type into, which fail validation, which
837
+ * forms get submitted and which get abandoned.
838
+ */
839
+ const forms = (ctx) => {
840
+ let touched = /* @__PURE__ */ new Set();
841
+ let invalid = /* @__PURE__ */ new Set();
842
+ let formStates = /* @__PURE__ */ new Map();
843
+ function stateOf(form) {
844
+ let state = formStates.get(form);
845
+ if (!state) {
846
+ state = {
847
+ ref: ctx.ref(form),
848
+ fields: /* @__PURE__ */ new Set(),
849
+ last: "",
850
+ submitted: false
851
+ };
852
+ formStates.set(form, state);
853
+ }
854
+ return state;
855
+ }
856
+ function fieldError(field) {
857
+ if (isIgnored(field)) return;
858
+ const ref = ctx.ref(field);
859
+ if (invalid.has(ref.el)) return;
860
+ invalid.add(ref.el);
861
+ ctx.emit({
862
+ t: "fe",
863
+ ...ref
864
+ });
865
+ }
866
+ function checkAriaInvalid(scope) {
867
+ setTimeout(safe(() => {
868
+ for (const field of scope.querySelectorAll("[aria-invalid=\"true\"]")) fieldError(field);
869
+ }), ARIA_INVALID_DELAY_MS);
870
+ }
871
+ ctx.onPage({
872
+ start() {
873
+ touched = /* @__PURE__ */ new Set();
874
+ invalid = /* @__PURE__ */ new Set();
875
+ formStates = /* @__PURE__ */ new Map();
876
+ },
877
+ end() {
878
+ for (const state of formStates.values()) {
879
+ if (state.submitted || state.fields.size === 0) continue;
880
+ ctx.emit({
881
+ t: "fb",
882
+ ...state.ref,
883
+ n: state.fields.size,
884
+ lf: state.last
885
+ });
886
+ }
887
+ }
888
+ });
889
+ const offs = [
890
+ listen(document, "input", (e) => {
891
+ if (!e.isTrusted) return;
892
+ const field = fieldOf(e.target);
893
+ if (!field) return;
894
+ const ref = ctx.ref(field);
895
+ if (!touched.has(ref.el)) {
896
+ touched.add(ref.el);
897
+ ctx.emit({
898
+ t: "fi",
899
+ ...ref
900
+ });
901
+ }
902
+ const form = field.form;
903
+ if (form) {
904
+ const state = stateOf(form);
905
+ state.fields.add(ref.el);
906
+ state.last = ref.el;
907
+ }
908
+ }),
909
+ listen(document, "invalid", (e) => {
910
+ const field = fieldOf(e.target);
911
+ if (field) fieldError(field);
912
+ }),
913
+ listen(document, "focusout", (e) => {
914
+ const field = fieldOf(e.target);
915
+ if (field?.getAttribute("aria-invalid") === "true") fieldError(field);
916
+ }),
917
+ listen(document, "submit", (e) => {
918
+ const form = e.target;
919
+ if (!(form instanceof HTMLFormElement) || isIgnored(form)) return;
920
+ const state = stateOf(form);
921
+ state.submitted = true;
922
+ ctx.emit({
923
+ t: "fs",
924
+ ...state.ref
925
+ });
926
+ checkAriaInvalid(form);
927
+ })
928
+ ];
929
+ return () => {
930
+ for (const off of offs) off();
931
+ };
932
+ };
933
+ //#endregion
934
+ //#region src/capture/impressions.ts
935
+ /** Fraction of an element that must be on screen to count as seen. */
936
+ const VISIBLE_RATIO = .5;
937
+ /** Added DOM nodes are scanned in idle time, batched. */
938
+ const SCAN_DELAY_MS = 250;
939
+ /**
940
+ * Records which interactive elements users actually saw, once per page view. This is what turns
941
+ * click counts into usage rates and makes "nobody uses this" distinguishable from "nobody sees this".
942
+ *
943
+ * Reported when the page ends and whenever the tab is hidden (a hidden mobile tab may be discarded
944
+ * without ending), each element at most once per page view.
945
+ */
946
+ const impressions = (ctx) => {
947
+ if (typeof IntersectionObserver === "undefined" || typeof MutationObserver === "undefined") return () => void 0;
948
+ /** Seen and not reported yet, with their ids (refreshed when the route arrives late). */
949
+ let seen = /* @__PURE__ */ new Map();
950
+ let reported = /* @__PURE__ */ new Set();
951
+ let observed = /* @__PURE__ */ new WeakSet();
952
+ let pending = [];
953
+ let scanTimer = null;
954
+ function onEntries(entries) {
955
+ for (const entry of entries) {
956
+ if (!entry.isIntersecting || entry.intersectionRatio < VISIBLE_RATIO) continue;
957
+ io.unobserve(entry.target);
958
+ if (isIgnored(entry.target)) continue;
959
+ if (seen.size + reported.size >= LIMITS.maxImpressionsPerEvent) continue;
960
+ seen.set(entry.target, ctx.ref(entry.target).el);
961
+ }
962
+ }
963
+ const io = new IntersectionObserver(safe(onEntries), { threshold: VISIBLE_RATIO });
964
+ function observe(el) {
965
+ if (observed.has(el) || isIgnored(el)) return;
966
+ observed.add(el);
967
+ io.observe(el);
968
+ }
969
+ function scan(root) {
970
+ if (root instanceof Element && root.matches(ctx.interactive)) observe(root);
971
+ for (const el of root.querySelectorAll(ctx.interactive)) observe(el);
972
+ }
973
+ function flushPending() {
974
+ scanTimer = null;
975
+ const roots = pending;
976
+ pending = [];
977
+ for (const root of roots) if (root.isConnected) scan(root);
978
+ }
979
+ function report() {
980
+ onEntries(io.takeRecords());
981
+ const els = [];
982
+ for (const id of seen.values()) {
983
+ if (reported.has(id)) continue;
984
+ reported.add(id);
985
+ els.push(id);
986
+ }
987
+ seen = /* @__PURE__ */ new Map();
988
+ if (els.length > 0) ctx.emit({
989
+ t: "im",
990
+ els
991
+ });
992
+ }
993
+ const mo = new MutationObserver(safe((records) => {
994
+ for (const record of records) for (const node of record.addedNodes) if (node instanceof Element) pending.push(node);
995
+ if (pending.length > 0 && scanTimer === null) scanTimer = setTimeout(safe(flushPending), SCAN_DELAY_MS);
996
+ }));
997
+ ctx.onPage({
998
+ start() {
999
+ io.disconnect();
1000
+ seen = /* @__PURE__ */ new Map();
1001
+ reported = /* @__PURE__ */ new Set();
1002
+ observed = /* @__PURE__ */ new WeakSet();
1003
+ scan(document);
1004
+ },
1005
+ hidden: report,
1006
+ end: report,
1007
+ route() {
1008
+ for (const el of seen.keys()) seen.set(el, ctx.ref(el).el);
1009
+ }
1010
+ });
1011
+ mo.observe(document.documentElement, {
1012
+ childList: true,
1013
+ subtree: true
1014
+ });
1015
+ return () => {
1016
+ mo.disconnect();
1017
+ io.disconnect();
1018
+ if (scanTimer !== null) clearTimeout(scanTimer);
1019
+ };
1020
+ };
1021
+ //#endregion
1022
+ //#region src/capture/network.ts
1023
+ /** Failed requests that start within this window after a click are attributed to it. */
1024
+ const FAILED_ACTION_WINDOW_MS = 2e3;
1025
+ const MAX_FAILURES_PER_CLICK = 3;
1026
+ function requestPath(url) {
1027
+ try {
1028
+ const u = new URL(url, location.href);
1029
+ const path = routeTemplate(u.pathname);
1030
+ return u.origin === location.origin ? path : `${u.host}${path}`;
1031
+ } catch {
1032
+ return "unknown";
1033
+ }
1034
+ }
1035
+ function isOwnRequest(url) {
1036
+ return url.includes(`${INGEST_PATH}?k=`);
1037
+ }
1038
+ /**
1039
+ * Wraps fetch and XMLHttpRequest. Requests signal activity (a click that starts a request is not
1040
+ * dead); failures shortly after a click become `failed_action` events on the clicked element.
1041
+ */
1042
+ const network = (ctx) => {
1043
+ /** `click` was taken when the request started: a click after that must not steal the failure. */
1044
+ function failed(click, method, url, status) {
1045
+ if (click.failures >= MAX_FAILURES_PER_CLICK) return;
1046
+ click.failures++;
1047
+ const m = truncate(`${method.toUpperCase()} ${requestPath(url)}`, LIMITS.maxMessageLength);
1048
+ ctx.emit({
1049
+ t: "fa",
1050
+ ...click.ref,
1051
+ st: status,
1052
+ m
1053
+ });
1054
+ }
1055
+ const observeFetch = safe((request, input, init) => {
1056
+ const source = input instanceof Request ? input : void 0;
1057
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : source?.url;
1058
+ if (url && isOwnRequest(url)) return;
1059
+ ctx.activity.signal();
1060
+ const click = ctx.recentClick(FAILED_ACTION_WINDOW_MS);
1061
+ if (!click || !url) return;
1062
+ const method = init?.method ?? source?.method ?? "GET";
1063
+ return request.then((res) => {
1064
+ safe(() => {
1065
+ const status = res.status;
1066
+ if (status >= 400) failed(click, method, url, status);
1067
+ })();
1068
+ return res;
1069
+ }, (err) => {
1070
+ safe(() => {
1071
+ if (!(init?.signal ?? source?.signal)?.aborted && !(err instanceof DOMException && err.name === "AbortError")) failed(click, method, url, 0);
1072
+ })();
1073
+ throw err;
1074
+ });
1075
+ });
1076
+ const offFetch = patch(window, "fetch", (original) => function(...args) {
1077
+ let request;
1078
+ try {
1079
+ request = original.apply(this, args);
1080
+ } catch (err) {
1081
+ request = Promise.reject(err);
1082
+ }
1083
+ return observeFetch(request, ...args) ?? request;
1084
+ });
1085
+ const meta = /* @__PURE__ */ new WeakMap();
1086
+ const remember = safe((xhr, method, url) => {
1087
+ meta.set(xhr, {
1088
+ method,
1089
+ url: String(url)
1090
+ });
1091
+ });
1092
+ const observeXhr = safe((xhr) => {
1093
+ const m = meta.get(xhr);
1094
+ if (m && !isOwnRequest(m.url)) {
1095
+ ctx.activity.signal();
1096
+ const click = ctx.recentClick(FAILED_ACTION_WINDOW_MS);
1097
+ if (click) {
1098
+ const report = () => {
1099
+ if (xhr.status === 0 || xhr.status >= 400) failed(click, m.method, m.url, xhr.status);
1100
+ };
1101
+ if (xhr.readyState === XMLHttpRequest.DONE) return report();
1102
+ let aborted = false;
1103
+ const offAbort = listen(xhr, "abort", () => {
1104
+ aborted = true;
1105
+ }, { once: true });
1106
+ listen(xhr, "loadend", () => {
1107
+ offAbort();
1108
+ if (!aborted && meta.get(xhr) === m) report();
1109
+ }, { once: true });
1110
+ }
1111
+ }
1112
+ });
1113
+ if (typeof XMLHttpRequest === "undefined") return offFetch;
1114
+ const proto = XMLHttpRequest.prototype;
1115
+ const offOpen = patch(proto, "open", (original) => function(...args) {
1116
+ const result = Reflect.apply(original, this, args);
1117
+ remember(this, args[0], args[1]);
1118
+ return result;
1119
+ });
1120
+ const offSend = patch(proto, "send", (original) => function(...args) {
1121
+ const result = original.apply(this, args);
1122
+ observeXhr(this);
1123
+ return result;
1124
+ });
1125
+ return () => {
1126
+ offFetch();
1127
+ offOpen();
1128
+ offSend();
1129
+ };
1130
+ };
1131
+ //#endregion
1132
+ //#region src/capture/pages.ts
1133
+ /** Leaving a page via "back" this soon after arriving counts as a quick back. */
1134
+ const QUICK_BACK_MS = 5e3;
1135
+ function scrollDepth() {
1136
+ const doc = document.documentElement;
1137
+ const height = Math.max(doc.scrollHeight, document.body?.scrollHeight ?? 0);
1138
+ if (height <= 0) return 100;
1139
+ return Math.min(100, Math.round((window.scrollY + window.innerHeight) / height * 100));
1140
+ }
1141
+ /**
1142
+ * SPA navigation (History API), visible time, scroll depth and quick backs. Page start/end
1143
+ * themselves (including unload and the back/forward cache) are owned by the client, so every
1144
+ * module sees the same boundaries.
1145
+ *
1146
+ * Known gap: `page_leave` is final only when the page ends. A hidden mobile tab that the browser
1147
+ * discards never ends, so its visible time and scroll depth are lost (as are form abandons).
1148
+ * Reporting on `visibilitychange` instead needs repeated, cumulative values per page view that
1149
+ * the server de-duplicates (max per page view); today's rollups sum every `pl` they receive.
1150
+ */
1151
+ function pages(nav) {
1152
+ return (ctx) => {
1153
+ let visibleMs = 0;
1154
+ let visibleSince = 0;
1155
+ let maxScroll = 0;
1156
+ let scrollQueued = false;
1157
+ const pauseVisible = () => {
1158
+ if (visibleSince) visibleMs += Date.now() - visibleSince;
1159
+ visibleSince = 0;
1160
+ };
1161
+ const resumeVisible = () => {
1162
+ if (!visibleSince && document.visibilityState === "visible") visibleSince = Date.now();
1163
+ };
1164
+ const measureScroll = () => {
1165
+ if (scrollQueued) return;
1166
+ scrollQueued = true;
1167
+ requestAnimationFrame(safe(() => {
1168
+ scrollQueued = false;
1169
+ maxScroll = Math.max(maxScroll, scrollDepth());
1170
+ }));
1171
+ };
1172
+ ctx.onPage({
1173
+ start() {
1174
+ visibleMs = 0;
1175
+ visibleSince = 0;
1176
+ resumeVisible();
1177
+ maxScroll = 0;
1178
+ measureScroll();
1179
+ },
1180
+ end(page, reason) {
1181
+ pauseVisible();
1182
+ ctx.emit({
1183
+ t: "pl",
1184
+ d: visibleMs,
1185
+ sd: maxScroll
1186
+ });
1187
+ const stayed = Date.now() - page.start;
1188
+ if (reason === "pop" && stayed < QUICK_BACK_MS) ctx.emit({
1189
+ t: "qb",
1190
+ d: stayed
1191
+ });
1192
+ }
1193
+ });
1194
+ const wrap = (reason) => (original) => {
1195
+ const navigate = safe(() => nav.navigate(reason));
1196
+ return function(...args) {
1197
+ const result = original.apply(this, args);
1198
+ navigate();
1199
+ return result;
1200
+ };
1201
+ };
1202
+ const offs = [
1203
+ patch(history, "pushState", wrap("push")),
1204
+ patch(history, "replaceState", wrap("replace")),
1205
+ listen(window, "popstate", () => nav.navigate("pop")),
1206
+ listen(window, "scroll", measureScroll),
1207
+ listen(document, "visibilitychange", () => {
1208
+ if (document.visibilityState === "hidden") pauseVisible();
1209
+ else resumeVisible();
1210
+ })
1211
+ ];
1212
+ return () => {
1213
+ for (const off of offs) off();
1214
+ };
1215
+ };
1216
+ }
1217
+ //#endregion
1218
+ //#region src/capture/slow.ts
1219
+ function pathOf(node) {
1220
+ const path = [];
1221
+ for (let cur = node; cur; cur = cur.parentNode) path.push(cur);
1222
+ return path;
1223
+ }
1224
+ /** Interactions whose visual response took ≥ `slowInteractionMs` (Event Timing API, as used by INP). */
1225
+ const slowInteractions = (ctx) => {
1226
+ if (typeof PerformanceObserver === "undefined" || !PerformanceObserver.supportedEntryTypes?.includes("event")) return () => void 0;
1227
+ const reported = /* @__PURE__ */ new Set();
1228
+ const observer = new PerformanceObserver(safe((list) => {
1229
+ for (const entry of list.getEntries()) {
1230
+ const id = entry.interactionId;
1231
+ if (!id || reported.has(id) || entry.duration < ctx.config.slowInteractionMs) continue;
1232
+ const target = entry.target;
1233
+ if (!target) continue;
1234
+ const el = resolveTarget(pathOf(target), ctx.interactive);
1235
+ if (!el) continue;
1236
+ reported.add(id);
1237
+ ctx.emit({
1238
+ t: "si",
1239
+ ...ctx.ref(el),
1240
+ d: Math.round(entry.duration)
1241
+ });
1242
+ }
1243
+ }));
1244
+ observer.observe({
1245
+ type: "event",
1246
+ durationThreshold: 104,
1247
+ buffered: false
1248
+ });
1249
+ return () => observer.disconnect();
1250
+ };
1251
+ //#endregion
1252
+ //#region src/capture/values.ts
1253
+ /** Input types whose value is never useful or never safe to record. */
1254
+ const NEVER_TYPES = /* @__PURE__ */ new Set([
1255
+ "password",
1256
+ "hidden",
1257
+ "file"
1258
+ ]);
1259
+ /** autocomplete tokens for secrets and payment data. */
1260
+ const NEVER_AUTOCOMPLETE = /\b(cc-[a-z-]+|one-time-code|current-password|new-password)\b/i;
1261
+ /** Names/labels that suggest a secret even when the markup doesn't say so. */
1262
+ const SENSITIVE_NAME = /pass(word|code)?|pwd|card|cvv|cvc|ccnum|security.?code|ssn|iban|\bpin\b|otp|secret|token|api.?key/i;
1263
+ const SEARCH_HINT = /search|query|filter|find/i;
1264
+ function isField(el) {
1265
+ return el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement || el instanceof HTMLSelectElement;
1266
+ }
1267
+ /**
1268
+ * Fields whose values must never leave the browser, whatever the configuration says. Visible
1269
+ * labels count too: a "show password" toggle turns a password field into a plain text field.
1270
+ */
1271
+ function isSensitive(field) {
1272
+ if (field instanceof HTMLInputElement && NEVER_TYPES.has(field.type)) return true;
1273
+ if (NEVER_AUTOCOMPLETE.test(field.getAttribute("autocomplete") ?? "")) return true;
1274
+ const hints = [
1275
+ field.name,
1276
+ field.id,
1277
+ field.getAttribute("aria-label"),
1278
+ field.getAttribute("placeholder"),
1279
+ labelledBy(field),
1280
+ ...Array.from(field.labels ?? [], (label) => label.textContent)
1281
+ ].join(" ");
1282
+ return SENSITIVE_NAME.test(hints);
1283
+ }
1284
+ function isSearch(field) {
1285
+ if (field instanceof HTMLInputElement && field.type === "search") return true;
1286
+ if (field.getAttribute("role") === "searchbox") return true;
1287
+ return SEARCH_HINT.test(`${field.name} ${field.getAttribute("aria-label") ?? ""} ${field.getAttribute("placeholder") ?? ""}`);
1288
+ }
1289
+ /** What the user chose or typed, as a person would describe it. */
1290
+ function fieldValue(field, maskAllText) {
1291
+ if (field instanceof HTMLSelectElement) return [...field.selectedOptions].map((o) => o.label || o.text || o.value).join(", ");
1292
+ if (field instanceof HTMLInputElement) {
1293
+ if (field.type === "checkbox") return field.checked ? "checked" : "unchecked";
1294
+ if (field.type === "radio") return field.checked ? labelOf(field, "radio", maskAllText) || field.value : "";
1295
+ }
1296
+ return field.value;
1297
+ }
1298
+ /**
1299
+ * Captured field values (opt-in): what people search for, which options they pick, what they
1300
+ * name things. Recorded when a value is committed (change/blur, Enter in search boxes), never on
1301
+ * every keystroke, and deduplicated per field and page view.
1302
+ */
1303
+ const fieldValues = (ctx) => {
1304
+ let last = /* @__PURE__ */ new Map();
1305
+ ctx.onPage({ start() {
1306
+ last = /* @__PURE__ */ new Map();
1307
+ } });
1308
+ function capture(target) {
1309
+ if (!(target instanceof Element) || !isField(target)) return;
1310
+ const optedIn = target.closest(`[${CAPTURE_ATTR}]`) !== null;
1311
+ if (!ctx.config.captureInputValues && !optedIn) return;
1312
+ if (isIgnored(target) || isMasked(target) || isSensitive(target)) return;
1313
+ const v = clean(fieldValue(target, ctx.config.maskAllText), LIMITS.maxValueLength);
1314
+ if (!v) return;
1315
+ const ref = ctx.ref(target);
1316
+ if (last.get(ref.el) === v) return;
1317
+ last.set(ref.el, v);
1318
+ ctx.emit({
1319
+ t: "fv",
1320
+ ...ref,
1321
+ v
1322
+ });
1323
+ }
1324
+ const offs = [listen(document, "change", (e) => {
1325
+ if (e.isTrusted) capture(e.target);
1326
+ }), listen(document, "keydown", (e) => {
1327
+ if (!e.isTrusted || e.key !== "Enter" || !(e.target instanceof Element)) return;
1328
+ if (isField(e.target) && isSearch(e.target)) capture(e.target);
1329
+ })];
1330
+ return () => {
1331
+ for (const off of offs) off();
1332
+ };
1333
+ };
1334
+ //#endregion
1335
+ //#region src/storage.ts
1336
+ function createStore(prefix) {
1337
+ const memory = /* @__PURE__ */ new Map();
1338
+ let backend = null;
1339
+ try {
1340
+ backend = window.localStorage;
1341
+ } catch {
1342
+ backend = null;
1343
+ }
1344
+ const k = (key) => `${prefix}_${key}`;
1345
+ return {
1346
+ get(key) {
1347
+ try {
1348
+ return backend ? backend.getItem(k(key)) : memory.get(k(key)) ?? null;
1349
+ } catch {
1350
+ return memory.get(k(key)) ?? null;
1351
+ }
1352
+ },
1353
+ set(key, value) {
1354
+ memory.set(k(key), value);
1355
+ try {
1356
+ backend?.setItem(k(key), value);
1357
+ } catch {
1358
+ backend = null;
1359
+ }
1360
+ },
1361
+ remove(key) {
1362
+ memory.delete(k(key));
1363
+ try {
1364
+ backend?.removeItem(k(key));
1365
+ } catch {
1366
+ backend = null;
1367
+ }
1368
+ }
1369
+ };
1370
+ }
1371
+ function readJson(store, key) {
1372
+ const raw = store.get(key);
1373
+ if (!raw) return null;
1374
+ try {
1375
+ return JSON.parse(raw);
1376
+ } catch {
1377
+ return null;
1378
+ }
1379
+ }
1380
+ //#endregion
1381
+ //#region src/delivery.ts
1382
+ const RETRY_BASE_MS = 2e3;
1383
+ /** The first batch of a page load goes out quickly, so the Live hint is learned early. */
1384
+ const FIRST_FLUSH_MS = 1e3;
1385
+ /** Flush interval while someone watches the project live, and how long that lasts per hint. */
1386
+ const LIVE_FLUSH_MS = 500;
1387
+ const LIVE_WINDOW_MS = 6e4;
1388
+ const MAX_RETRY_BYTES = 262144;
1389
+ const MAX_ATTEMPTS = 6;
1390
+ function isStoredBatch(value) {
1391
+ const s = value;
1392
+ return typeof s?.attempts === "number" && Array.isArray(s.batch?.e);
1393
+ }
1394
+ /**
1395
+ * Batches waiting for a retry. All tabs of a visitor share one list, so storage (not memory) is
1396
+ * the source of truth: adding re-reads and merges, taking removes before sending. Tabs neither
1397
+ * overwrite nor double-send each other's batches; batch ids let the server drop the rare repeat.
1398
+ */
1399
+ var RetryStore = class {
1400
+ #key;
1401
+ #store;
1402
+ constructor(store, projectKey) {
1403
+ this.#store = store;
1404
+ this.#key = `q_${projectKey}`;
1405
+ }
1406
+ get size() {
1407
+ return this.#read().length;
1408
+ }
1409
+ add(batch, attempts) {
1410
+ if (attempts >= MAX_ATTEMPTS) return;
1411
+ const list = this.#read().filter((s) => !batch.i || s.batch.i !== batch.i);
1412
+ list.push({
1413
+ batch,
1414
+ attempts
1415
+ });
1416
+ this.#write(list);
1417
+ }
1418
+ /** Removes and returns the oldest batch. */
1419
+ take() {
1420
+ const list = this.#read();
1421
+ const first = list.shift();
1422
+ if (first) this.#write(list);
1423
+ return first;
1424
+ }
1425
+ clear() {
1426
+ this.#store.remove(this.#key);
1427
+ }
1428
+ #read() {
1429
+ const list = readJson(this.#store, this.#key);
1430
+ return Array.isArray(list) ? list.filter(isStoredBatch) : [];
1431
+ }
1432
+ #write(list) {
1433
+ let json = JSON.stringify(list);
1434
+ while (json.length > MAX_RETRY_BYTES && list.length > 1) {
1435
+ list.shift();
1436
+ json = JSON.stringify(list);
1437
+ }
1438
+ if (list.length > 0) this.#store.set(this.#key, json);
1439
+ else this.clear();
1440
+ }
1441
+ };
1442
+ /**
1443
+ * Gets batches to the server: a flush timer (faster while someone watches live), synchronous
1444
+ * beacons on unload, and retries with backoff. Sends nothing while inactive (before consent,
1445
+ * after opt-out or shutdown).
1446
+ */
1447
+ var Delivery = class {
1448
+ #active = false;
1449
+ /** set on opt-out: batches failing after it must not be stored again */
1450
+ #discarded = false;
1451
+ #flushTimer = null;
1452
+ #retryTimer = null;
1453
+ #retryAttempt = 0;
1454
+ #flushedOnce = false;
1455
+ #liveUntil = 0;
1456
+ #flushNormal = safe(() => this.flush("normal"));
1457
+ #batcher;
1458
+ #transport;
1459
+ #retries;
1460
+ #identity;
1461
+ #config;
1462
+ constructor(batcher, transport, retries, identity, config) {
1463
+ this.#batcher = batcher;
1464
+ this.#transport = transport;
1465
+ this.#retries = retries;
1466
+ this.#identity = identity;
1467
+ this.#config = config;
1468
+ }
1469
+ start() {
1470
+ this.#active = true;
1471
+ this.#discarded = false;
1472
+ if (this.#retries.size > 0) this.#scheduleRetry(0);
1473
+ }
1474
+ /** Stops timers; queued events and stored retries stay for a later start or page load. */
1475
+ stop() {
1476
+ this.#active = false;
1477
+ this.#clearFlushTimer();
1478
+ if (this.#retryTimer !== null) clearTimeout(this.#retryTimer);
1479
+ this.#retryTimer = null;
1480
+ }
1481
+ /** Stops and drops everything not yet sent, including other page loads' retries (opt-out). */
1482
+ discard() {
1483
+ this.stop();
1484
+ this.#discarded = true;
1485
+ this.#batcher.clear();
1486
+ this.#retries.clear();
1487
+ }
1488
+ /** Call after queueing an event. */
1489
+ queued() {
1490
+ if (this.#batcher.size >= this.#config.flushAt) queueMicrotask(this.#flushNormal);
1491
+ else this.#flushTimer ??= setTimeout(this.#flushNormal, this.#flushDelay());
1492
+ }
1493
+ #flushDelay() {
1494
+ const { flushIntervalMs } = this.#config;
1495
+ if (Date.now() < this.#liveUntil) return Math.min(LIVE_FLUSH_MS, flushIntervalMs);
1496
+ if (!this.#flushedOnce) return Math.min(FIRST_FLUSH_MS, flushIntervalMs);
1497
+ return flushIntervalMs;
1498
+ }
1499
+ #clearFlushTimer() {
1500
+ if (this.#flushTimer !== null) clearTimeout(this.#flushTimer);
1501
+ this.#flushTimer = null;
1502
+ }
1503
+ flush(mode) {
1504
+ this.#clearFlushTimer();
1505
+ if (!this.#active || !this.#identity().sessionId) return;
1506
+ for (let batch = this.#take(); batch; batch = this.#take()) if (mode === "unload") {
1507
+ if (!this.#transport.beacon(batch)) this.#retries.add(batch, 0);
1508
+ } else {
1509
+ this.#flushedOnce = true;
1510
+ this.#send(batch, 0).then(safe((ok) => {
1511
+ if (!ok) this.#scheduleRetry();
1512
+ }), () => void 0);
1513
+ }
1514
+ }
1515
+ #take() {
1516
+ return this.#batcher.take(this.#identity());
1517
+ }
1518
+ /** Sends one batch; false (and the batch stored for a retry) when it should be tried again. */
1519
+ async #send(batch, attempts) {
1520
+ const { result, live } = await this.#transport.send(batch);
1521
+ if (live) this.#liveUntil = Date.now() + LIVE_WINDOW_MS;
1522
+ if (result !== "retry") return true;
1523
+ if (!this.#discarded) this.#retries.add(batch, attempts + 1);
1524
+ return false;
1525
+ }
1526
+ #scheduleRetry(delay = RETRY_BASE_MS * 2 ** Math.min(this.#retryAttempt, 5)) {
1527
+ if (this.#retryTimer !== null || !this.#active) return;
1528
+ this.#retryTimer = setTimeout(safe(() => {
1529
+ this.#retryTimer = null;
1530
+ this.#retry().catch(() => void 0);
1531
+ }), delay);
1532
+ }
1533
+ /** Sends stored batches one by one (re-reading storage each time); stops at the first failure. */
1534
+ async #retry() {
1535
+ for (let n = this.#retries.size; n > 0 && this.#active; n--) {
1536
+ const stored = this.#retries.take();
1537
+ if (!stored) break;
1538
+ if (!await this.#send(stored.batch, stored.attempts)) {
1539
+ this.#retryAttempt++;
1540
+ this.#scheduleRetry();
1541
+ return;
1542
+ }
1543
+ }
1544
+ this.#retryAttempt = 0;
1545
+ }
1546
+ };
1547
+ //#endregion
1548
+ //#region src/session.ts
1549
+ const KEY = "s";
1550
+ const WRITE_THROTTLE_MS = 5e3;
1551
+ /**
1552
+ * Sessions end after a period of inactivity. The record lives in localStorage so all tabs of the
1553
+ * same visitor share one session.
1554
+ */
1555
+ var Sessions = class {
1556
+ #record = null;
1557
+ #lastWrite = 0;
1558
+ #store;
1559
+ #timeoutMs;
1560
+ constructor(store, timeoutMs) {
1561
+ this.#store = store;
1562
+ this.#timeoutMs = timeoutMs;
1563
+ }
1564
+ /** Returns the current session id, rotating it when the previous session expired. */
1565
+ current(now) {
1566
+ const candidate = this.#freshest();
1567
+ if (candidate && now - candidate.last < this.#timeoutMs) {
1568
+ this.#record = candidate;
1569
+ this.#touch(now);
1570
+ return {
1571
+ id: candidate.id,
1572
+ isNew: false
1573
+ };
1574
+ }
1575
+ return {
1576
+ id: this.#start(now),
1577
+ isNew: true
1578
+ };
1579
+ }
1580
+ /**
1581
+ * Storage writes are throttled, so the in-memory record can be fresher than the stored one;
1582
+ * a different stored id means another tab rotated the session.
1583
+ */
1584
+ #freshest() {
1585
+ const raw = readJson(this.#store, KEY);
1586
+ const stored = raw && isUuid(raw.id) && typeof raw.last === "number" ? raw : null;
1587
+ const mem = this.#record;
1588
+ if (!stored || !mem) return stored ?? mem;
1589
+ if (stored.id === mem.id) return {
1590
+ id: mem.id,
1591
+ last: Math.max(stored.last, mem.last)
1592
+ };
1593
+ return stored.last >= mem.last ? stored : mem;
1594
+ }
1595
+ /** Forgets the session here and in storage (opt-out, reset): the next event starts a new one. */
1596
+ clear() {
1597
+ this.#record = null;
1598
+ this.#store.remove(KEY);
1599
+ }
1600
+ #start(now) {
1601
+ this.#record = {
1602
+ id: uuidv7(now),
1603
+ last: now
1604
+ };
1605
+ this.#write();
1606
+ return this.#record.id;
1607
+ }
1608
+ #touch(now) {
1609
+ if (!this.#record) return;
1610
+ this.#record.last = now;
1611
+ if (now - this.#lastWrite >= WRITE_THROTTLE_MS) this.#write();
1612
+ }
1613
+ #write() {
1614
+ if (!this.#record) return;
1615
+ this.#lastWrite = this.#record.last;
1616
+ this.#store.set(KEY, JSON.stringify(this.#record));
1617
+ }
1618
+ };
1619
+ //#endregion
1620
+ //#region src/transport.ts
1621
+ /** Browsers cap keepalive/beacon bodies at 64 KiB in total. */
1622
+ const KEEPALIVE_LIMIT = 6e4;
1623
+ const GZIP_THRESHOLD = 1024;
1624
+ async function gzip(text) {
1625
+ if (typeof CompressionStream === "undefined") return null;
1626
+ try {
1627
+ const stream = new Blob([text]).stream().pipeThrough(new CompressionStream("gzip"));
1628
+ return await new Response(stream).blob();
1629
+ } catch {
1630
+ return null;
1631
+ }
1632
+ }
1633
+ function classify(status) {
1634
+ if (status >= 200 && status < 300) return "ok";
1635
+ if (status === 408 || status === 429 || status >= 500) return "retry";
1636
+ return "drop";
1637
+ }
1638
+ /** `fetchImpl` must be the page's original fetch, captured before network instrumentation. */
1639
+ function createTransport(endpoint, fetchImpl, debug = false) {
1640
+ return {
1641
+ async send(batch) {
1642
+ const json = JSON.stringify({
1643
+ ...batch,
1644
+ at: Date.now()
1645
+ });
1646
+ const compressed = json.length > GZIP_THRESHOLD ? await gzip(json) : null;
1647
+ const body = compressed ?? json;
1648
+ const size = compressed ? compressed.size : json.length;
1649
+ try {
1650
+ const res = await fetchImpl(compressed ? `${endpoint}&z=1` : endpoint, {
1651
+ method: "POST",
1652
+ body,
1653
+ headers: { "content-type": "text/plain;charset=UTF-8" },
1654
+ credentials: "omit",
1655
+ keepalive: size < KEEPALIVE_LIMIT
1656
+ });
1657
+ const result = classify(res.status);
1658
+ if (debug && result === "drop" && res.status >= 400 && res.status < 500) safe(() => console.warn("[clicklore] dropped batch, HTTP", res.status))();
1659
+ return {
1660
+ result,
1661
+ live: res.headers.get(LIVE_HEADER) === "1"
1662
+ };
1663
+ } catch {
1664
+ return {
1665
+ result: "retry",
1666
+ live: false
1667
+ };
1668
+ }
1669
+ },
1670
+ beacon(batch) {
1671
+ const json = JSON.stringify({
1672
+ ...batch,
1673
+ at: Date.now()
1674
+ });
1675
+ if (json.length >= KEEPALIVE_LIMIT) return false;
1676
+ const blob = new Blob([json], { type: "text/plain;charset=UTF-8" });
1677
+ try {
1678
+ if (typeof navigator.sendBeacon === "function") return navigator.sendBeacon(endpoint, blob);
1679
+ fetchImpl(endpoint, {
1680
+ method: "POST",
1681
+ body: blob,
1682
+ credentials: "omit",
1683
+ keepalive: true
1684
+ }).catch(() => void 0);
1685
+ return true;
1686
+ } catch {
1687
+ return false;
1688
+ }
1689
+ }
1690
+ };
1691
+ }
1692
+ //#endregion
1693
+ //#region src/client.ts
1694
+ /** Visitor keys not already cleared by sessions or delivery. */
1695
+ const VISITOR_KEYS = [
1696
+ "a",
1697
+ "u",
1698
+ "g",
1699
+ "q"
1700
+ ];
1701
+ const isFallback = (def) => def.tr === void 0 && def.s === void 0;
1702
+ /** Custom event props are redacted (emails, long numbers); user traits are kept as given. */
1703
+ function sanitizeProps(props, redact) {
1704
+ const out = {};
1705
+ if (!props) return out;
1706
+ let count = 0;
1707
+ for (const [key, value] of Object.entries(props)) {
1708
+ if (count >= LIMITS.maxPropKeys) break;
1709
+ const k = truncate(key, LIMITS.maxNameLength);
1710
+ if (value === null || typeof value === "boolean") out[k] = value;
1711
+ else if (typeof value === "number") out[k] = Number.isFinite(value) ? value : null;
1712
+ else if (typeof value === "string") out[k] = truncate(redact ? redactPersonal(value) : value, LIMITS.maxPropValueLength);
1713
+ else if (value instanceof Date) out[k] = value.toISOString();
1714
+ else continue;
1715
+ count++;
1716
+ }
1717
+ return out;
1718
+ }
1719
+ /** Groups as `group()` stores them; anything else found in storage is ignored. */
1720
+ function storedGroups(value) {
1721
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
1722
+ const ids = Object.values(value);
1723
+ if (ids.length === 0 || ids.some((id) => typeof id !== "string")) return void 0;
1724
+ return value;
1725
+ }
1726
+ function doNotTrack() {
1727
+ const nav = navigator;
1728
+ return nav.doNotTrack === "1" || nav.globalPrivacyControl === true;
1729
+ }
1730
+ var Client = class {
1731
+ config;
1732
+ interactive;
1733
+ activity;
1734
+ #store;
1735
+ #batcher = new Batcher();
1736
+ #sessions;
1737
+ #delivery;
1738
+ #hooks = [];
1739
+ #described = /* @__PURE__ */ new WeakMap();
1740
+ #teardowns = [];
1741
+ #running = false;
1742
+ /** cancels a start deferred until a prerendered page is shown */
1743
+ #deferred = null;
1744
+ #lastClick = null;
1745
+ #anonId;
1746
+ #userId;
1747
+ #groups;
1748
+ #sessionId = "";
1749
+ #page = null;
1750
+ #pageSeq = 0;
1751
+ /** set while the page reports itself (end, hidden): see `emit` */
1752
+ #reporting = false;
1753
+ #routeOverride = null;
1754
+ /** `transport` replaces the network (tests); by default batches go to the configured host. */
1755
+ constructor(config, transport) {
1756
+ this.config = resolveConfig(config);
1757
+ this.interactive = interactiveSelector(this.config.trackAttribute);
1758
+ this.#store = createStore(this.config.storagePrefix);
1759
+ this.#sessions = new Sessions(this.#store, this.config.sessionTimeoutMs);
1760
+ this.#delivery = new Delivery(this.#batcher, transport ?? createTransport(this.config.endpoint, window.fetch.bind(window), this.config.debug), new RetryStore(this.#store, this.config.projectKey), () => ({
1761
+ anonId: this.#anonId,
1762
+ sessionId: this.#sessionId,
1763
+ userId: this.#userId,
1764
+ groups: this.#groups
1765
+ }), this.config);
1766
+ this.activity = createActivity(document);
1767
+ const storedAnon = this.#store.get("a");
1768
+ this.#anonId = isUuid(storedAnon) ? storedAnon : uuidv4();
1769
+ this.#userId = truncate(this.#store.get("u") ?? "", LIMITS.maxIdLength) || void 0;
1770
+ this.#groups = storedGroups(readJson(this.#store, "g"));
1771
+ }
1772
+ start() {
1773
+ if (this.#running || this.#deferred || !this.#allowed()) return;
1774
+ if (document.prerendering) {
1775
+ this.#deferred = listen(document, "prerenderingchange", () => {
1776
+ this.#deferred = null;
1777
+ this.start();
1778
+ }, { once: true });
1779
+ return;
1780
+ }
1781
+ this.#running = true;
1782
+ this.#persistIds();
1783
+ this.#store.remove("q");
1784
+ this.#delivery.start();
1785
+ const c = this.config.capture;
1786
+ if (c.pages) this.#teardowns.push(pages({ navigate: (r) => this.#navigate(r) })(this));
1787
+ if (c.clicks) this.#teardowns.push(clicks(this));
1788
+ if (c.impressions) this.#teardowns.push(impressions(this));
1789
+ if (c.forms) this.#teardowns.push(forms(this));
1790
+ this.#teardowns.push(fieldValues(this));
1791
+ if (c.errors) this.#teardowns.push(errors(this));
1792
+ if (c.network) this.#teardowns.push(network(this));
1793
+ if (c.slowInteractions) this.#teardowns.push(slowInteractions(this));
1794
+ if (c.copy) this.#teardowns.push(copy(this));
1795
+ this.#teardowns.push(listen(window, "storage", (e) => {
1796
+ if (e.key === `${this.config.storagePrefix}_c` && e.newValue === "out" && e.storageArea === localStorage) this.#forgetVisitor();
1797
+ }), listen(document, "visibilitychange", () => {
1798
+ if (document.visibilityState !== "hidden") return;
1799
+ this.#report((h, page) => h.hidden?.(page));
1800
+ this.flush("unload");
1801
+ }), listen(window, "pagehide", () => {
1802
+ this.#navigate("unload");
1803
+ this.flush("unload");
1804
+ }), listen(window, "pageshow", (e) => {
1805
+ if (e.persisted) this.#navigate("restore");
1806
+ }));
1807
+ this.#beginPage();
1808
+ }
1809
+ stop(report = true) {
1810
+ try {
1811
+ if (report && this.#running) this.#endPage("unload");
1812
+ if (!report) this.#halt();
1813
+ this.#teardown();
1814
+ if (report) this.flush("normal");
1815
+ } finally {
1816
+ this.#halt();
1817
+ }
1818
+ }
1819
+ #halt() {
1820
+ this.#running = false;
1821
+ this.#delivery.stop();
1822
+ this.#deferred?.();
1823
+ this.#deferred = null;
1824
+ }
1825
+ #teardown() {
1826
+ for (const t of this.#teardowns.splice(0)) safe(t)();
1827
+ this.#hooks.length = 0;
1828
+ this.activity.dispose();
1829
+ this.#page = null;
1830
+ }
1831
+ #allowed() {
1832
+ const consent = this.#store.get("c");
1833
+ if (consent === "out") return false;
1834
+ if (this.config.requireConsent && consent !== "in") return false;
1835
+ return !(this.config.respectDoNotTrack && doNotTrack());
1836
+ }
1837
+ optIn() {
1838
+ this.#store.set("c", "in");
1839
+ this.start();
1840
+ }
1841
+ /** Stops capture and forgets the visitor locally: nothing still queued or stored is sent. */
1842
+ optOut() {
1843
+ this.#store.set("c", "out");
1844
+ this.#forgetVisitor();
1845
+ }
1846
+ #forgetVisitor() {
1847
+ this.stop(false);
1848
+ this.#delivery.discard();
1849
+ for (const key of VISITOR_KEYS) this.#store.remove(key);
1850
+ this.#sessions.clear();
1851
+ this.#sessionId = "";
1852
+ this.#anonId = uuidv4();
1853
+ }
1854
+ identify(userId, traits) {
1855
+ const id = truncate(String(userId), LIMITS.maxIdLength);
1856
+ if (!id) return;
1857
+ if (id !== this.#userId) {
1858
+ this.flush("normal");
1859
+ this.#batcher.setTraits(void 0);
1860
+ this.#userId = id;
1861
+ this.#persistIds();
1862
+ }
1863
+ if (traits) this.#batcher.setTraits(sanitizeProps(traits, false));
1864
+ this.emit({ t: "id" });
1865
+ }
1866
+ group(type, id) {
1867
+ this.flush("normal");
1868
+ this.#groups = {
1869
+ ...this.#groups,
1870
+ [truncate(type, LIMITS.maxNameLength)]: truncate(String(id), LIMITS.maxIdLength)
1871
+ };
1872
+ this.#persistIds();
1873
+ }
1874
+ /** Forgets the user (logout): new anonymous id and a new session, starting on this page. */
1875
+ reset() {
1876
+ this.flush("normal");
1877
+ this.#batcher.setTraits(void 0);
1878
+ this.#userId = void 0;
1879
+ this.#groups = void 0;
1880
+ this.#anonId = uuidv4();
1881
+ this.#persistIds();
1882
+ this.#sessions.clear();
1883
+ this.#sessionId = "";
1884
+ if (this.#page) this.emit(this.#pageview(this.#page));
1885
+ }
1886
+ get anonymousId() {
1887
+ return this.#anonId;
1888
+ }
1889
+ /** The session of the last event; null before capture starts (this never starts a session). */
1890
+ get currentSessionId() {
1891
+ return this.#sessionId || null;
1892
+ }
1893
+ /** Ids stay in memory until capture is allowed; from then on storage mirrors them. */
1894
+ #persistIds() {
1895
+ if (!this.#running) return;
1896
+ this.#store.set("a", this.#anonId);
1897
+ if (this.#userId) this.#store.set("u", this.#userId);
1898
+ else this.#store.remove("u");
1899
+ if (this.#groups) this.#store.set("g", JSON.stringify(this.#groups));
1900
+ else this.#store.remove("g");
1901
+ }
1902
+ track(name, props) {
1903
+ const n = truncate(name.trim(), LIMITS.maxNameLength);
1904
+ if (!n) return;
1905
+ const pr = sanitizeProps(props, true);
1906
+ this.emit(Object.keys(pr).length > 0 ? {
1907
+ t: "cu",
1908
+ n,
1909
+ pr
1910
+ } : {
1911
+ t: "cu",
1912
+ n
1913
+ });
1914
+ }
1915
+ emit(input) {
1916
+ if (!this.#running) return;
1917
+ const now = Date.now();
1918
+ const session = this.#reporting && this.#sessionId ? null : this.#sessions.current(now);
1919
+ if (session && session.id !== this.#sessionId) {
1920
+ if (this.#sessionId) this.flush("normal");
1921
+ this.#sessionId = session.id;
1922
+ if (session.isNew) {
1923
+ this.#push(this.#stamp(this.#sessionStart(), now));
1924
+ if (input.t !== "pv" && this.#page) this.#push(this.#stamp(this.#pageview(this.#page), now));
1925
+ }
1926
+ }
1927
+ this.#push(this.#stamp(input, now));
1928
+ }
1929
+ #stamp(input, ts) {
1930
+ return {
1931
+ ...input,
1932
+ ts,
1933
+ p: this.#currentRoute()
1934
+ };
1935
+ }
1936
+ #push(event) {
1937
+ if (this.config.debug) console.debug("[clicklore]", event.t, event);
1938
+ this.#batcher.push(event, this.#page?.seq ?? this.#pageSeq);
1939
+ this.#delivery.queued();
1940
+ }
1941
+ #pageview(page) {
1942
+ const title = clean(document.title, LIMITS.maxNameLength);
1943
+ return {
1944
+ t: "pv",
1945
+ pa: page.sanitizedPath,
1946
+ ti: title || void 0
1947
+ };
1948
+ }
1949
+ #sessionStart() {
1950
+ const params = new URLSearchParams(location.search);
1951
+ const utm = {};
1952
+ for (const [k, v] of params) if (k.startsWith("utm_") && v) utm[truncate(k.slice(4), LIMITS.maxNameLength)] = truncate(v, 200);
1953
+ const event = {
1954
+ t: "ss",
1955
+ sw: window.screen?.width ?? 0,
1956
+ sh: window.screen?.height ?? 0,
1957
+ lang: navigator.language,
1958
+ tz: Intl.DateTimeFormat().resolvedOptions().timeZone
1959
+ };
1960
+ if (Object.keys(utm).length > 0) event.utm = utm;
1961
+ const referrer = this.#externalReferrer();
1962
+ if (referrer) event.r = referrer;
1963
+ return event;
1964
+ }
1965
+ #externalReferrer() {
1966
+ if (!document.referrer) return void 0;
1967
+ try {
1968
+ const url = new URL(document.referrer);
1969
+ if (url.origin === location.origin) return void 0;
1970
+ return `${url.host}${url.pathname === "/" ? "" : routeTemplate(url.pathname)}`;
1971
+ } catch {
1972
+ return;
1973
+ }
1974
+ }
1975
+ ref(el) {
1976
+ const { trackAttribute, maskAllText } = this.config;
1977
+ const route = this.#currentRoute();
1978
+ const kind = kindOf(el);
1979
+ const label = labelOf(el, kind, maskAllText);
1980
+ const inputs = `${kind}|${el.getAttribute(ANNOTATION_ATTR)}|${el.getAttribute(trackAttribute)}`;
1981
+ let d = this.#described.get(el);
1982
+ if (!d || d.inputs !== inputs || isFallback(d.def) && (d.route !== route || label !== (d.def.l ?? ""))) {
1983
+ d = {
1984
+ def: describe(el, {
1985
+ route,
1986
+ trackAttr: trackAttribute,
1987
+ maskAllText
1988
+ }),
1989
+ inputs,
1990
+ route
1991
+ };
1992
+ this.#described.set(el, d);
1993
+ }
1994
+ this.#batcher.define(d.def);
1995
+ return !isFallback(d.def) && label && label !== d.def.l ? {
1996
+ el: d.def.id,
1997
+ lb: label
1998
+ } : { el: d.def.id };
1999
+ }
2000
+ markClick(ref) {
2001
+ this.#lastClick = {
2002
+ time: Date.now(),
2003
+ ref,
2004
+ errored: false,
2005
+ failures: 0
2006
+ };
2007
+ }
2008
+ recentClick(windowMs) {
2009
+ const click = this.#lastClick;
2010
+ return click && Date.now() - click.time <= windowMs ? click : null;
2011
+ }
2012
+ onPage(hooks) {
2013
+ this.#hooks.push(hooks);
2014
+ }
2015
+ /**
2016
+ * Route of the page events belong to. During navigation the URL has already changed while the
2017
+ * old page is still ending, so this is the page's route, not the one derived from `location`.
2018
+ */
2019
+ #currentRoute() {
2020
+ return this.#page?.route ?? this.#route();
2021
+ }
2022
+ #sanitizePath(path) {
2023
+ const sanitized = safe(() => this.config.sanitizeUrl?.(path))();
2024
+ return truncate(typeof sanitized === "string" ? sanitized : routeTemplate(path), LIMITS.maxRouteLength);
2025
+ }
2026
+ #route(path = location.pathname, sanitizedPath) {
2027
+ if (this.#routeOverride?.path === path) return this.#routeOverride.route;
2028
+ const route = safe(() => this.config.route?.(path))();
2029
+ return typeof route === "string" ? truncate(route, LIMITS.maxRouteLength) : sanitizedPath ?? this.#sanitizePath(path);
2030
+ }
2031
+ /** Called by framework adapters with the router's template for the current path. */
2032
+ setRoute(template) {
2033
+ const route = truncate(template, LIMITS.maxRouteLength);
2034
+ this.#routeOverride = {
2035
+ path: location.pathname,
2036
+ route
2037
+ };
2038
+ const page = this.#page;
2039
+ if (page && page.path === location.pathname && page.route !== route) {
2040
+ page.route = route;
2041
+ this.#batcher.rewriteRoute(page.seq, route);
2042
+ for (const h of this.#hooks) safe(() => h.route?.(page))();
2043
+ }
2044
+ }
2045
+ #navigate(reason) {
2046
+ this.activity.signal();
2047
+ if (reason === "restore") {
2048
+ if (!this.#page) this.#beginPage();
2049
+ return;
2050
+ }
2051
+ if (reason !== "unload" && this.#page?.path === location.pathname) return;
2052
+ this.#endPage(reason);
2053
+ if (reason !== "unload") this.#beginPage();
2054
+ }
2055
+ #beginPage() {
2056
+ const path = location.pathname;
2057
+ const sanitizedPath = this.#sanitizePath(path);
2058
+ const page = {
2059
+ seq: ++this.#pageSeq,
2060
+ route: this.#route(path, sanitizedPath),
2061
+ path,
2062
+ sanitizedPath,
2063
+ start: Date.now()
2064
+ };
2065
+ this.#page = page;
2066
+ this.emit(this.#pageview(page));
2067
+ for (const h of this.#hooks) safe(() => h.start?.(page))();
2068
+ }
2069
+ #endPage(reason) {
2070
+ this.#report((h, page) => h.end?.(page, reason));
2071
+ this.#page = null;
2072
+ }
2073
+ /** Runs hooks in which the current page reports on itself (end, hidden). */
2074
+ #report(run) {
2075
+ const page = this.#page;
2076
+ if (!page) return;
2077
+ const reporting = this.#reporting;
2078
+ this.#reporting = true;
2079
+ try {
2080
+ for (const h of this.#hooks) safe(run)(h, page);
2081
+ } finally {
2082
+ this.#reporting = reporting;
2083
+ }
2084
+ }
2085
+ flush(mode) {
2086
+ this.#delivery.flush(mode);
2087
+ }
2088
+ };
2089
+ //#endregion
2090
+ //#region src/index.ts
2091
+ /**
2092
+ * Page-wide slot claimed by the running copy of the SDK. A page can load two copies (script tag
2093
+ * plus npm, or two tags); both capturing would count everything twice.
2094
+ */
2095
+ const SLOT = Symbol.for("clicklore");
2096
+ let client;
2097
+ let warned = false;
2098
+ /** Calls made before `init()` (e.g. identify in a provider that renders first) are replayed. */
2099
+ const pending = [];
2100
+ function withClient(fn) {
2101
+ if (typeof window === "undefined") return;
2102
+ if (client) safe(fn)(client);
2103
+ else if (client === void 0 && pending.length < 100) pending.push(fn);
2104
+ }
2105
+ /**
2106
+ * Starts capturing. Safe to call during SSR (no-op) and more than once (later calls are ignored).
2107
+ * When another copy of the SDK already runs on the page, this one warns and stays inactive.
2108
+ */
2109
+ const init = safe((config) => {
2110
+ if (typeof window === "undefined" || typeof document === "undefined" || client) return;
2111
+ const slot = globalThis;
2112
+ try {
2113
+ if (slot[SLOT]) {
2114
+ if (!warned) console.warn("[clicklore] another copy of the SDK is already running; ignoring init()");
2115
+ warned = true;
2116
+ return;
2117
+ }
2118
+ const next = new Client(config);
2119
+ client = next;
2120
+ slot[SLOT] = next;
2121
+ next.start();
2122
+ for (const fn of pending.splice(0)) safe(fn)(next);
2123
+ } catch (error) {
2124
+ const failed = client;
2125
+ client = null;
2126
+ pending.length = 0;
2127
+ safe(() => failed?.stop(false))();
2128
+ if (slot[SLOT] === failed) delete slot[SLOT];
2129
+ console.error("[clicklore] could not start SDK", error);
2130
+ }
2131
+ });
2132
+ /** Records a custom event. */
2133
+ function track(name, props) {
2134
+ withClient((c) => c.track(name, props));
2135
+ }
2136
+ /** Associates this visitor with your user id; traits (email, plan…) show up on their profile. */
2137
+ function identify(userId, traits) {
2138
+ withClient((c) => c.identify(userId, traits));
2139
+ }
2140
+ /** Associates this visitor with a group, e.g. `group('org', 'acme')`. */
2141
+ function group(type, id) {
2142
+ withClient((c) => c.group(type, id));
2143
+ }
2144
+ /** Forgets the identified user (call on logout). */
2145
+ function reset() {
2146
+ withClient((c) => c.reset());
2147
+ }
2148
+ /** Tells Clicklore the route template for the current URL, e.g. `/projects/[id]`. */
2149
+ function setRoute(template) {
2150
+ withClient((c) => c.setRoute(template));
2151
+ }
2152
+ function optIn() {
2153
+ withClient((c) => c.optIn());
2154
+ }
2155
+ function optOut() {
2156
+ withClient((c) => c.optOut());
2157
+ }
2158
+ /** Sends queued events now. */
2159
+ const flush = safe(() => {
2160
+ client?.flush("normal");
2161
+ });
2162
+ /** Stops capturing and removes all listeners and patches. */
2163
+ const shutdown = safe(() => {
2164
+ if (!client) return;
2165
+ client.stop();
2166
+ const slot = globalThis;
2167
+ if (slot[SLOT] === client) delete slot[SLOT];
2168
+ client = void 0;
2169
+ });
2170
+ function getAnonymousId() {
2171
+ return client?.anonymousId ?? null;
2172
+ }
2173
+ function getSessionId() {
2174
+ return client?.currentSessionId ?? null;
2175
+ }
2176
+ /**
2177
+ * The public API as one object: what framework adapters hand out (e.g. `useClicklore()`), so
2178
+ * every adapter exposes the same functions.
2179
+ */
2180
+ const clicklore = {
2181
+ track,
2182
+ identify,
2183
+ group,
2184
+ reset,
2185
+ setRoute,
2186
+ optIn,
2187
+ optOut,
2188
+ flush,
2189
+ shutdown,
2190
+ getAnonymousId,
2191
+ getSessionId
2192
+ };
2193
+ //#endregion
2194
+ export { SDK_VERSION, clicklore, flush, getAnonymousId, getSessionId, group, identify, init, optIn, optOut, reset, setRoute, shutdown, track };