@decocms/blocks 8.17.0 → 8.18.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.
Files changed (97) hide show
  1. package/dist/v8/analytics/client.d.ts +48 -0
  2. package/dist/v8/analytics/client.d.ts.map +1 -0
  3. package/dist/v8/analytics/client.js +71 -0
  4. package/dist/v8/analytics/client.js.map +1 -0
  5. package/dist/v8/analytics/runtime/modules/click.d.ts +2 -0
  6. package/dist/v8/analytics/runtime/modules/click.d.ts.map +1 -0
  7. package/dist/v8/analytics/runtime/modules/click.js +48 -0
  8. package/dist/v8/analytics/runtime/modules/click.js.map +1 -0
  9. package/dist/v8/analytics/runtime/modules/commerce.d.ts +2 -0
  10. package/dist/v8/analytics/runtime/modules/commerce.d.ts.map +1 -0
  11. package/dist/v8/analytics/runtime/modules/commerce.js +41 -0
  12. package/dist/v8/analytics/runtime/modules/commerce.js.map +1 -0
  13. package/dist/v8/analytics/runtime/modules/consent.d.ts +33 -0
  14. package/dist/v8/analytics/runtime/modules/consent.d.ts.map +1 -0
  15. package/dist/v8/analytics/runtime/modules/consent.js +154 -0
  16. package/dist/v8/analytics/runtime/modules/consent.js.map +1 -0
  17. package/dist/v8/analytics/runtime/modules/deco.d.ts +2 -0
  18. package/dist/v8/analytics/runtime/modules/deco.d.ts.map +1 -0
  19. package/dist/v8/analytics/runtime/modules/deco.js +209 -0
  20. package/dist/v8/analytics/runtime/modules/deco.js.map +1 -0
  21. package/dist/v8/analytics/runtime/modules/engagement.d.ts +2 -0
  22. package/dist/v8/analytics/runtime/modules/engagement.d.ts.map +1 -0
  23. package/dist/v8/analytics/runtime/modules/engagement.js +128 -0
  24. package/dist/v8/analytics/runtime/modules/engagement.js.map +1 -0
  25. package/dist/v8/analytics/runtime/modules/errors.d.ts +2 -0
  26. package/dist/v8/analytics/runtime/modules/errors.d.ts.map +1 -0
  27. package/dist/v8/analytics/runtime/modules/errors.js +167 -0
  28. package/dist/v8/analytics/runtime/modules/errors.js.map +1 -0
  29. package/dist/v8/analytics/runtime/modules/heatmap.d.ts +2 -0
  30. package/dist/v8/analytics/runtime/modules/heatmap.d.ts.map +1 -0
  31. package/dist/v8/analytics/runtime/modules/heatmap.js +316 -0
  32. package/dist/v8/analytics/runtime/modules/heatmap.js.map +1 -0
  33. package/dist/v8/analytics/runtime/modules/vitals.d.ts +2 -0
  34. package/dist/v8/analytics/runtime/modules/vitals.d.ts.map +1 -0
  35. package/dist/v8/analytics/runtime/modules/vitals.js +119 -0
  36. package/dist/v8/analytics/runtime/modules/vitals.js.map +1 -0
  37. package/dist/v8/analytics/runtime/src/guards.d.ts +10 -0
  38. package/dist/v8/analytics/runtime/src/guards.d.ts.map +1 -0
  39. package/dist/v8/analytics/runtime/src/guards.js +70 -0
  40. package/dist/v8/analytics/runtime/src/guards.js.map +1 -0
  41. package/dist/v8/analytics/runtime/src/index.d.ts +2 -0
  42. package/dist/v8/analytics/runtime/src/index.d.ts.map +1 -0
  43. package/dist/v8/analytics/runtime/src/index.js +562 -0
  44. package/dist/v8/analytics/runtime/src/index.js.map +1 -0
  45. package/dist/v8/analytics/runtime/src/queue.d.ts +15 -0
  46. package/dist/v8/analytics/runtime/src/queue.d.ts.map +1 -0
  47. package/dist/v8/analytics/runtime/src/queue.js +36 -0
  48. package/dist/v8/analytics/runtime/src/queue.js.map +1 -0
  49. package/dist/v8/analytics/runtime/src/trim.d.ts +13 -0
  50. package/dist/v8/analytics/runtime/src/trim.d.ts.map +1 -0
  51. package/dist/v8/analytics/runtime/src/trim.js +38 -0
  52. package/dist/v8/analytics/runtime/src/trim.js.map +1 -0
  53. package/dist/v8/analytics/runtime/view/heat-core.d.ts +69 -0
  54. package/dist/v8/analytics/runtime/view/heat-core.d.ts.map +1 -0
  55. package/dist/v8/analytics/runtime/view/heat-core.js +314 -0
  56. package/dist/v8/analytics/runtime/view/heat-core.js.map +1 -0
  57. package/dist/v8/analytics/runtime/view/view.d.ts +51 -0
  58. package/dist/v8/analytics/runtime/view/view.d.ts.map +1 -0
  59. package/dist/v8/analytics/runtime/view/view.js +525 -0
  60. package/dist/v8/analytics/runtime/view/view.js.map +1 -0
  61. package/dist/v8/analytics/shared/anchor.d.ts +71 -0
  62. package/dist/v8/analytics/shared/anchor.d.ts.map +1 -0
  63. package/dist/v8/analytics/shared/anchor.js +155 -0
  64. package/dist/v8/analytics/shared/anchor.js.map +1 -0
  65. package/dist/v8/analytics/shared/contract.d.ts +294 -0
  66. package/dist/v8/analytics/shared/contract.d.ts.map +1 -0
  67. package/dist/v8/analytics/shared/contract.js +652 -0
  68. package/dist/v8/analytics/shared/contract.js.map +1 -0
  69. package/dist/v8/fetch.d.ts.map +1 -1
  70. package/dist/v8/fetch.js +27 -2
  71. package/dist/v8/fetch.js.map +1 -1
  72. package/dist/v8/telemetry.d.ts +2 -0
  73. package/dist/v8/telemetry.d.ts.map +1 -1
  74. package/dist/v8/telemetry.js +21 -6
  75. package/dist/v8/telemetry.js.map +1 -1
  76. package/package.json +6 -1
  77. package/src/v8/analytics/client.ts +110 -0
  78. package/src/v8/analytics/runtime/globals.d.ts +36 -0
  79. package/src/v8/analytics/runtime/modules/click.ts +54 -0
  80. package/src/v8/analytics/runtime/modules/commerce.ts +73 -0
  81. package/src/v8/analytics/runtime/modules/consent.ts +150 -0
  82. package/src/v8/analytics/runtime/modules/deco.ts +207 -0
  83. package/src/v8/analytics/runtime/modules/engagement.ts +140 -0
  84. package/src/v8/analytics/runtime/modules/errors.ts +217 -0
  85. package/src/v8/analytics/runtime/modules/heatmap.ts +360 -0
  86. package/src/v8/analytics/runtime/modules/vitals.ts +128 -0
  87. package/src/v8/analytics/runtime/src/guards.ts +70 -0
  88. package/src/v8/analytics/runtime/src/index.ts +606 -0
  89. package/src/v8/analytics/runtime/src/queue.ts +40 -0
  90. package/src/v8/analytics/runtime/src/trim.ts +39 -0
  91. package/src/v8/analytics/runtime/view/heat-core.ts +335 -0
  92. package/src/v8/analytics/runtime/view/view.ts +596 -0
  93. package/src/v8/analytics/shared/anchor.ts +171 -0
  94. package/src/v8/analytics/shared/contract.ts +691 -0
  95. package/src/v8/analytics/tsconfig.json +14 -0
  96. package/src/v8/fetch.ts +27 -2
  97. package/src/v8/telemetry.ts +25 -5
@@ -0,0 +1,217 @@
1
+ /** Automatic error capture.
2
+ *
3
+ * `captureException` in core only ever sees what a site already wrapped in try/catch,
4
+ * which is the minority of what breaks. This module attaches the two listeners that
5
+ * see the rest, and does the two things that separate an error product from an error
6
+ * log: it gives every error a stable fingerprint so repeats group, and it collapses a
7
+ * repeating error into one event with a count instead of one event per occurrence.
8
+ *
9
+ * That second part is not an optimisation. A render loop throwing on every frame is
10
+ * the normal shape of a bad deploy; without collapsing, one visitor's broken tab sends
11
+ * thousands of events, the queue drops the rest of their session, and the bill and the
12
+ * data are both wrong.
13
+ */
14
+ import { LIMITS } from "../../shared/contract.ts";
15
+
16
+ type Props = Record<string, string | number | boolean>;
17
+
18
+ window.__dqRegister?.((enqueue, api: Record<string, unknown>, onFinal) => {
19
+ // Volatile parts of a message are what stop repeats grouping: ids, timestamps, URLs
20
+ // and offsets differ per occurrence while the fault is identical. Strip them before
21
+ // hashing, keep the original message on the event as a sample.
22
+ const stable = (msg: string) =>
23
+ msg
24
+ .replace(/https?:\/\/[^\s)'"]+/g, "<url>")
25
+ .replace(/\b[0-9a-f]{8,}\b/gi, "<hex>")
26
+ .replace(/\b\d[\d.,]*\b/g, "<n>")
27
+ .replace(/['"][^'"]{0,80}['"]/g, "<str>")
28
+ .slice(0, 200);
29
+
30
+ // A file path is the same fault whether it arrives absolute, with a cache-busting
31
+ // query, or with a hash fragment.
32
+ const cleanFile = (f: string) => {
33
+ if (!f) return "";
34
+ try {
35
+ const u = new URL(f, location.href);
36
+ return (u.origin === location.origin ? "" : u.origin) + u.pathname;
37
+ } catch {
38
+ return f.split("?")[0].split("#")[0];
39
+ }
40
+ };
41
+
42
+ // A URL in a message or a stack keeps its origin and path and loses its query and fragment:
43
+ // `fetch failed for /api/cart?email=...&token=...` is the fault, the values are a visitor's.
44
+ // A frame's trailing `:line:col` survives, since it is what points at the fault.
45
+ const noQuery = (s: string) =>
46
+ s.replace(
47
+ /([a-z][\w+.-]*:\/\/[^\s?#()'"]*)[?#][^\s()'"]*?(?=:\d+:\d+(?![^\s)])|[\s()'"]|$)/gi,
48
+ "$1",
49
+ );
50
+
51
+ // FNV-1a with a murmur3 finaliser. The finaliser matters: without it the low bits are
52
+ // just an XOR of the input's low bits, and near-identical inputs land in adjacent
53
+ // buckets rather than spread.
54
+ const fingerprint = (parts: string[]) => {
55
+ let h = 2166136261;
56
+ const s = parts.join("|");
57
+ for (let i = 0; i < s.length; i++) {
58
+ h ^= s.charCodeAt(i);
59
+ h = Math.imul(h, 16777619);
60
+ }
61
+ h = Math.imul(h ^ (h >>> 16), 2246822507);
62
+ h = Math.imul(h ^ (h >>> 13), 3266489909);
63
+ return ((h ^ (h >>> 16)) >>> 0).toString(36).padStart(7, "0");
64
+ };
65
+
66
+ // Seen this page load: fingerprint -> how many times since the last send. A repeating
67
+ // error increments rather than enqueues.
68
+ const seen = new Map<string, { n: number; sent: boolean }>();
69
+ // A hard ceiling on DISTINCT errors per page load. A loop that generates a new
70
+ // fingerprint each time (a message with an unstrippable varying part) would otherwise
71
+ // defeat the collapsing entirely, which is the failure mode this guard exists for.
72
+ const MAX_DISTINCT = 20;
73
+
74
+ // OURS = this origin, or a host the site declared as its own in `errorHosts` (served as `er`;
75
+ // a separate asset CDN, say). Everything else on a storefront is a vendor: a GTM tag, a pixel,
76
+ // a chat widget. Measured on FILA, New Balance and Umbro, 96-100% of `$error` was a
77
+ // cross-origin ResourceError -- a dead tag, a 403'd account, an ad blocker -- none of it
78
+ // actionable here, and between them 18-26% of every event those sites sent.
79
+ const ours = (u: string) => {
80
+ try {
81
+ const x = new URL(u, location.href);
82
+ return (
83
+ x.origin === location.origin || ((api.er as string[] | undefined) ?? []).includes(x.host)
84
+ );
85
+ } catch {
86
+ return false;
87
+ }
88
+ };
89
+
90
+ function report(
91
+ type: string,
92
+ message: string,
93
+ file: string,
94
+ line: number,
95
+ stack: string,
96
+ props?: Props,
97
+ ) {
98
+ // Read by the heatmap module: a click followed by an error within a second is an
99
+ // "error click". On the performance timeline, which is what the click is timed on.
100
+ // Only OUR faults flag it. Vendor tags boot on the storefront's first interaction, so their
101
+ // failures land right after the first click -- every header "error click" reproduced on
102
+ // FILA, New Balance and Umbro was one. The source is the file, else the first stack frame
103
+ // (a URL followed by :line:col, which a URL quoted in the message is not). "Script error."
104
+ // and a fault with no source cannot be attributed, so they do not flag.
105
+ const src = file || (/([a-z][\w+.-]*:\/\/[^\s()]+):\d+:\d+/i.exec(String(stack))?.[1] ?? "");
106
+ // Not the site's code at all: a script the BROWSER injected -- an in-app browser's bridge
107
+ // (`iabjs://`, Instagram/Facebook), an extension (`chrome-extension://`, `moz-extension://`,
108
+ // `safari-web-extension://`). Nothing the site ships can fix it, and it was the largest single
109
+ // fault on two storefronts after #27 (newbalance: 130 an hour, "Error invoking postMessage:
110
+ // Java object is gone").
111
+ if (/^[a-z][\w+.-]*:\/\//i.test(src) && !/^https?:/i.test(src)) return;
112
+ if (src && message !== "Script error." && ours(src))
113
+ (window as any).__dqLastErrorTs = performance.now();
114
+ const fp = fingerprint([type, stable(message), cleanFile(file), String(line)]);
115
+ const prev = seen.get(fp);
116
+ if (prev) {
117
+ prev.n++;
118
+ return;
119
+ } // already reported this page load
120
+ if (seen.size >= MAX_DISTINCT) return; // storm guard
121
+ seen.set(fp, { n: 1, sent: true });
122
+
123
+ enqueue("$error", props, {
124
+ error_type: (type || "Error").slice(0, 40),
125
+ error_fingerprint: fp,
126
+ error_message: noQuery(String(message ?? "")).slice(0, LIMITS.valueLen),
127
+ error_file: cleanFile(file).slice(0, LIMITS.pathLen),
128
+ error_line: Number(line) || 0,
129
+ error_count: 1,
130
+ error_stack: noQuery(String(stack ?? "")).slice(0, LIMITS.errorEventBytes),
131
+ });
132
+ }
133
+
134
+ // Repeats accumulated after the first report are sent once, at the end, as a single
135
+ // event carrying the count. One event per thousand occurrences, and the thousand is
136
+ // still visible.
137
+ function flushRepeats() {
138
+ let any = false;
139
+ for (const [fp, rec] of seen) {
140
+ if (rec.n <= 1) continue;
141
+ enqueue("$error", undefined, {
142
+ error_fingerprint: fp,
143
+ error_type: "repeat",
144
+ error_count: rec.n - 1,
145
+ error_message: "",
146
+ });
147
+ rec.n = 1;
148
+ any = true;
149
+ }
150
+ void any;
151
+ }
152
+ // Ordering, not a second request: core runs this BEFORE its final flush, so the
153
+ // repeats are in the queue when that flush happens. Enqueueing after it used to
154
+ // report eight occurrences as one; flushing again to compensate cost a request.
155
+ onFinal(flushRepeats);
156
+
157
+ addEventListener(
158
+ "error",
159
+ (e: any) => {
160
+ // A failed <img>/<script>/<link> also fires "error" on window, with no `error`
161
+ // object and the element as target. It is a real fault worth recording, but it is
162
+ // not an exception and must not be reported as one.
163
+ if (!e?.error && e?.target && e.target !== window) {
164
+ const el = e.target;
165
+ // `.href` on an SVG element is an SVGAnimatedString, NOT a string — so a failing
166
+ // `<use href="/sprite.svg#icon">` used to be reported as
167
+ // `/[object%20SVGAnimatedString]`, which names no resource and masks which sprite
168
+ // actually failed (seen live on a storefront whose icons are one `<use>` sprite).
169
+ // `.src` has the same shape on SVGScriptElement.
170
+ const raw = el.src || el.href || "";
171
+ const src: string = typeof raw === "string" ? raw : (raw.baseVal ?? "");
172
+ // A vendor's asset failing is the vendor's problem (see `ours`): dropped, not reported.
173
+ // Ours -- our chunks, our sprite, a declared `errorHosts` CDN -- is a real fault.
174
+ if (!src || !ours(src)) return;
175
+ report(
176
+ "ResourceError",
177
+ `failed to load ${el.tagName?.toLowerCase?.() ?? "resource"}`,
178
+ src,
179
+ 0,
180
+ "",
181
+ );
182
+ return;
183
+ }
184
+ report(
185
+ e?.error?.name ?? "Error",
186
+ e?.message ?? String(e?.error ?? "error"),
187
+ e?.filename ?? "",
188
+ e?.lineno ?? 0,
189
+ e?.error?.stack ?? "",
190
+ );
191
+ },
192
+ true,
193
+ ); // capture phase: resource errors do not bubble
194
+
195
+ addEventListener("unhandledrejection", (e: any) => {
196
+ const r = e?.reason;
197
+ report(
198
+ r?.name ?? "UnhandledRejection",
199
+ r?.message ?? String(r ?? "rejected"),
200
+ r?.fileName ?? "",
201
+ r?.lineNumber ?? 0,
202
+ r?.stack ?? "",
203
+ );
204
+ });
205
+
206
+ // Same fingerprinting for the manual path, so an error caught by the site and the
207
+ // same error escaping uncaught land in one group rather than two.
208
+ api.captureException = (err: any, props?: Props) =>
209
+ report(
210
+ err?.name ?? "Error",
211
+ err?.message ?? String(err),
212
+ err?.fileName ?? "",
213
+ err?.lineNumber ?? 0,
214
+ err?.stack ?? "",
215
+ props,
216
+ );
217
+ });
@@ -0,0 +1,360 @@
1
+ /** Heatmaps: where people click, how far they scroll and where their attention goes, as ONE
2
+ * `$heatmap` event per page view.
3
+ *
4
+ * Each view (a document load, or an SPA route change to a new path) gets a random `view_id`, kept
5
+ * in memory only, so this works at tier 0 with no storage. Every emission is CUMULATIVE for its
6
+ * view -- on `visibilitychange: hidden`, on `pagehide` and on route change -- and the warehouse
7
+ * keeps the last one per view (`argMax(..., ts)`). That makes a lost early beacon harmless and a
8
+ * page that is hidden and shown five times one view, not five.
9
+ *
10
+ * It rides core's flushes, so it never spends a request of its own.
11
+ *
12
+ * Costs on the visitor's main thread, all bounded:
13
+ * - click (capture, passive): one getBoundingClientRect on the anchor, a parent walk with
14
+ * getComputedStyle for the fixed/sticky flag, sibling counts. Read in the CAPTURE phase,
15
+ * before the site's own handlers have mutated anything, so the layout read finds a clean
16
+ * layout instead of forcing one. No serialisation.
17
+ * - scroll (passive): at most one rAF per frame; `scrollHeight` at most once a second.
18
+ * - sections: one IntersectionObserver, callbacks off the input path.
19
+ * Every handler is wrapped: a failure here means "heatmap stopped", never "the page broke".
20
+ *
21
+ * Never sent: text, input values, href/src, classes, coordinates of untrusted events.
22
+ */
23
+ import { anchorOf, rootOf, pathOf, cyrb53, fsRootName } from "../../shared/anchor.ts";
24
+
25
+ window.__dqRegister?.((enqueue, cfg: Record<string, any>, onFinal, onRoute) => {
26
+ const w = window as any,
27
+ d = document,
28
+ now = () => performance.now();
29
+ // Never runs where a visitor types who they are or pays.
30
+ const DENY = /^\/(checkout|account|login)(\/|$)|^\/(api\/io|pvt)\//i;
31
+
32
+ let on = false,
33
+ vid = "",
34
+ path = "",
35
+ t0 = 0,
36
+ last = 0,
37
+ input = 0,
38
+ vis = false,
39
+ raf = 0,
40
+ dhAt = 0;
41
+ let vw = 0,
42
+ vh = 0,
43
+ top = 0,
44
+ dh = 0,
45
+ sd = 0,
46
+ am = 0;
47
+ let roots: Map<string, number>,
48
+ at: number[],
49
+ ss: Map<number, number>,
50
+ seen: Set<number>,
51
+ clicks: any[][];
52
+ let burst: any,
53
+ known: WeakSet<Element>,
54
+ idxOf: WeakMap<Element, number>,
55
+ sent = "",
56
+ sentAm = 0;
57
+ // Clicks awaiting a dead-click verdict. ANY reaction clears all of them: one DOM mutation, a
58
+ // scroll, a route change or focus moving into a text field answers every click before it.
59
+ const pending = new Set<any>();
60
+ const react = () => {
61
+ pending.clear();
62
+ mo.disconnect();
63
+ };
64
+ const mo = new MutationObserver(react);
65
+
66
+ const idx = (id: string) => {
67
+ if (!id) return -1;
68
+ let i = roots.get(id);
69
+ if (i === undefined) {
70
+ if (roots.size >= 32) return -1;
71
+ roots.set(id, (i = roots.size));
72
+ }
73
+ return i;
74
+ };
75
+ const guard =
76
+ (f: (...a: any[]) => void) =>
77
+ (...a: any[]) => {
78
+ try {
79
+ f(...a);
80
+ } catch {
81
+ /* heatmap stops, page lives */
82
+ }
83
+ };
84
+ // Every listener goes through here: guarded, passive unless told otherwise.
85
+ const listen = (
86
+ t: string,
87
+ f: (e: any) => void,
88
+ o: AddEventListenerOptions = { passive: true },
89
+ on: EventTarget = w,
90
+ ) => on.addEventListener(t, guard(f), o);
91
+
92
+ // ---- time: active ms credited to the viewport position it was spent on --------------------
93
+ // Active = tab visible AND some input in the last 30 s, so an idle background tab does not
94
+ // paint the hero red. Time between two ticks is credited to where the viewport WAS.
95
+ const tick = () => {
96
+ const n = now(),
97
+ act = Math.min(n, input + 3e4) - last;
98
+ if (vis && act > 0 && dh) {
99
+ am += act;
100
+ for (
101
+ let i = Math.floor((top * 40) / dh),
102
+ e = Math.min(39, Math.floor(((top + vh - 1) * 40) / dh));
103
+ i <= e;
104
+ i++
105
+ )
106
+ at[i] = (at[i] || 0) + act;
107
+ for (const i of seen) ss.set(i, ss.get(i)! + act);
108
+ }
109
+ last = n;
110
+ vis = d.visibilityState == "visible";
111
+ vw = innerWidth;
112
+ vh = innerHeight;
113
+ top = scrollY;
114
+ if (n - dhAt > 1e3) {
115
+ const h = d.documentElement.scrollHeight;
116
+ dhAt = n;
117
+ if (h > dh) {
118
+ dh = h;
119
+ observe(d.body);
120
+ }
121
+ }
122
+ sd = Math.max(sd, dh ? Math.min(100, Math.round(((top + vh) * 100) / dh)) : 100);
123
+ };
124
+ const poke = () => {
125
+ const n = now();
126
+ if (on && n - input > 3e4) tick();
127
+ input = n;
128
+ };
129
+
130
+ // ---- sections: Deco sections and FastStore component roots, the same roots clicks use -----
131
+ const io = new IntersectionObserver(
132
+ guard((es: IntersectionObserverEntry[]) => {
133
+ if (!on) return;
134
+ tick();
135
+ for (const e of es) {
136
+ const i = idxOf.get(e.target)!;
137
+ if (i < 0) continue;
138
+ if (e.intersectionRatio >= 0.5 || e.intersectionRect.height >= 300) {
139
+ seen.add(i);
140
+ ss.set(i, ss.get(i) || 0);
141
+ } else seen.delete(i);
142
+ }
143
+ }),
144
+ { threshold: [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1] },
145
+ );
146
+ // Top-down to the first root on each branch: visits the page scaffolding, not the inside of
147
+ // every component. Re-run when the document grows, which is when lazy sections appear.
148
+ const observe = (p: Element, k = 0) => {
149
+ for (const c of p?.children ?? []) {
150
+ if (k++ > 3e3) return;
151
+ if (c.matches("section[data-manifest-key]") || fsRootName(c)) {
152
+ if (!known.has(c)) {
153
+ known.add(c);
154
+ idxOf.set(c, idx(rootOf(c)[1]));
155
+ io.observe(c);
156
+ }
157
+ } else observe(c, k);
158
+ }
159
+ };
160
+
161
+ // ---- view lifecycle -----------------------------------------------------------------------
162
+ const start = () => {
163
+ path = location.pathname;
164
+ // Sampled ONCE per view: per-event sampling overcounts visitors (2026-08-19).
165
+ on = cfg.h !== 0 && !DENY.test(path) && Math.random() < (cfg.hr ?? 1);
166
+ const r = crypto.getRandomValues(new Uint32Array(2));
167
+ vid = ((r[0] & 0x1fffff) * 4294967296 + r[1]).toString(36);
168
+ cfg.hv = on ? vid : ""; // read by vitals, for the INP A/B by view
169
+ t0 = last = input = now();
170
+ dhAt = -1e4;
171
+ dh = sd = am = 0;
172
+ burst = 0;
173
+ sent = "";
174
+ notes = [];
175
+ roots = new Map();
176
+ at = [];
177
+ ss = new Map();
178
+ seen = new Set();
179
+ clicks = [];
180
+ // Root indices are per view: an SPA view re-observes from scratch with a fresh dictionary.
181
+ io.disconnect();
182
+ known = new WeakSet();
183
+ idxOf = new WeakMap();
184
+ if (!on) return;
185
+ tick();
186
+ // An SPA view starts before its new DOM exists; look again once it has rendered.
187
+ setTimeout(
188
+ guard(() => {
189
+ if (on) {
190
+ tick();
191
+ dh = 0;
192
+ dhAt = -1e4;
193
+ tick();
194
+ }
195
+ }),
196
+ 2e3,
197
+ );
198
+ };
199
+
200
+ const emit = () => {
201
+ if (!on || cfg.h === 0) return;
202
+ drain();
203
+ tick();
204
+ const a: number[] = [];
205
+ for (let i = 0; i < at.length; i++) a.push(Math.round((at[i] || 0) / 100));
206
+ const hm: any = {
207
+ v: 1,
208
+ id: vid,
209
+ vw,
210
+ vh,
211
+ dh,
212
+ sd,
213
+ am: Math.round(am),
214
+ at: a,
215
+ s: [...roots.keys()].map((k) => k.slice(0, 120)),
216
+ ss: [...ss].map(([i, ms]) => [i, Math.round(ms / 100)]),
217
+ // Copies: the queue serialises later, and a dead flag set after this must not edit a
218
+ // record already queued.
219
+ c: clicks.map((c) => c.slice()),
220
+ };
221
+ // Never over the contract's 4 KB for this event: shed the newest clicks first.
222
+ let j;
223
+ while ((j = JSON.stringify(hm)).length > 3800 && hm.c.length) hm.c.pop();
224
+ // Unchanged since the last emission -- `hidden` then `pagehide` on the way out -- is not
225
+ // sent again: core drains on each, and a second copy would cost a second beacon. "Unchanged"
226
+ // ignores the few ms of attention that tick between the two; a second of it is a change.
227
+ const { am: a0, at: a1, ss: a2, ...rest } = hm;
228
+ const sig = JSON.stringify(rest);
229
+ if (sig == sent && hm.am - sentAm < 1e3) return;
230
+ sent = sig;
231
+ sentAm = hm.am;
232
+ enqueue("$heatmap", undefined, { path, heatmap: hm });
233
+ };
234
+
235
+ // ---- clicks -------------------------------------------------------------------------------
236
+ // The listener only takes notes: target, coordinates, scroll, time. The hashing and the layout
237
+ // reads happen AFTER THE NEXT PAINT (rAF, then a task), so none of it is inside the interaction
238
+ // INP measures -- and a layout read there would force the layout the click's own :active
239
+ // styles just invalidated. A route change or the end of the view drains the notes first, so a
240
+ // click is never attributed to the next view.
241
+ const clamp = (v: number) => (v > 255 ? 255 : v > 0 ? v | 0 : 0);
242
+ let notes: any[] = [];
243
+ const drain = () => {
244
+ for (const r of notes.splice(0)) record(r);
245
+ };
246
+ const record = ([t, cx, cy, sy, n, kb, tok]: any[]) => {
247
+ if (!t.isConnected) return; // gone before we looked: no anchor to hash
248
+ const [a, inter] = anchorOf(t),
249
+ [root, id] = rootOf(a);
250
+ const el = cyrb53(id + "|" + pathOf(root, a)).toString(36);
251
+ const r = a.getBoundingClientRect(),
252
+ ds = scrollY - sy;
253
+ let f = (inter ? 16 : 0) | (kb ? 32 : 0);
254
+ for (let p: Element | null = a; p && p != d.body; p = p.parentElement) {
255
+ const pos = getComputedStyle(p).position;
256
+ if (pos == "fixed" || pos == "sticky") {
257
+ f |= 8;
258
+ break;
259
+ }
260
+ }
261
+ // Where the element was AT THE CLICK: a fixed one does not move with scroll, the rest moved
262
+ // up by however far the page scrolled since.
263
+ const top = f & 8 ? r.top : r.top + ds,
264
+ left = r.left;
265
+ // A keyboard "click" has no coordinates; it happened on the element, so use its centre.
266
+ const x = kb ? left + r.width / 2 : cx,
267
+ y = kb ? top + r.height / 2 : cy;
268
+ // Rage: 3+ clicks within 1 s, each within 30 px of the first. One record, n = count.
269
+ if (
270
+ burst &&
271
+ burst[0] == el &&
272
+ n - burst[1] < 1e3 &&
273
+ Math.hypot(x - burst[2], y - burst[3]) <= 30
274
+ ) {
275
+ const c = (tok.c = burst[4]);
276
+ if (c[7] < 255) c[7]++;
277
+ if (c[7] > 2) c[8] |= 1;
278
+ return;
279
+ }
280
+ if (clicks.length >= 40) return;
281
+ const c = (tok.c = [
282
+ idx(id),
283
+ el,
284
+ clamp(((x - left) * 256) / r.width),
285
+ clamp(((y - top) * 256) / r.height),
286
+ Math.min(1e3, Math.max(0, Math.round((x * 1e3) / innerWidth))),
287
+ Math.max(0, Math.round(f & 8 ? y : y + sy)),
288
+ Math.round(n - t0),
289
+ 1,
290
+ f | tok.f,
291
+ ]);
292
+ clicks.push(c);
293
+ burst = [el, n, x, y, c];
294
+ };
295
+ listen(
296
+ "click",
297
+ (e: MouseEvent) => {
298
+ const t = e.target as Element;
299
+ // Untrusted clicks are not behaviour; ignored widgets and password fields are never recorded.
300
+ // A target that is not an Element throws in `closest`, which `guard` turns into "not recorded".
301
+ if (!on || cfg.h === 0 || !e.isTrusted || t.closest("[data-dq-ignore],input[type=password]"))
302
+ return;
303
+ const n = now(),
304
+ tok: any = { f: 0 };
305
+ if (!notes.length) requestAnimationFrame(() => setTimeout(guard(drain)));
306
+ notes.push([t, e.clientX, e.clientY, scrollY, n, e.detail === 0, tok]);
307
+ // Dead: nothing reacted within 1 s. Error: the errors module reported something in that second.
308
+ // Armed NOW, since the reaction is what follows the click. Focus moving onto a clicked button
309
+ // is not a reaction -- every button click does that.
310
+ if (!pending.size)
311
+ mo.observe(d, { subtree: true, childList: true, attributes: true, characterData: true });
312
+ pending.add(tok);
313
+ setTimeout(
314
+ guard(() => {
315
+ if (pending.delete(tok)) tok.f |= 2;
316
+ if (!pending.size) mo.disconnect();
317
+ if ((w.__dqLastErrorTs ?? -1) >= n) tok.f |= 4;
318
+ if (tok.c) tok.c[8] |= tok.f;
319
+ }),
320
+ 1e3,
321
+ );
322
+ },
323
+ { capture: true, passive: true },
324
+ );
325
+
326
+ listen("scroll", () => {
327
+ poke();
328
+ react();
329
+ if (on && !raf)
330
+ raf = requestAnimationFrame(
331
+ guard(() => {
332
+ raf = 0;
333
+ on && tick();
334
+ }),
335
+ );
336
+ });
337
+ for (const t of ["pointerdown", "pointermove", "keydown", "touchstart"]) listen(t, poke);
338
+ listen("visibilitychange", () => on && tick(), {}, d);
339
+ // `matches` throws on a non-Element target; `guard` makes that a no-op.
340
+ listen(
341
+ "focusin",
342
+ (e: FocusEvent) =>
343
+ (e.target as Element).matches("input,textarea,select,[contenteditable]") && react(),
344
+ {},
345
+ d,
346
+ );
347
+ // A page restored from the back/forward cache is a new view; the old one was emitted on pagehide.
348
+ listen("pageshow", (e: PageTransitionEvent) => e.persisted && start());
349
+
350
+ onFinal(emit);
351
+ // Core calls this BEFORE the new route's $pageview. A query-string change on the same path
352
+ // (PLP filters) is not a new view, matching core's replaceState rule.
353
+ onRoute?.((prev: string) => {
354
+ if (prev == location.pathname) return;
355
+ react();
356
+ emit();
357
+ start();
358
+ });
359
+ start();
360
+ });