@decocms/blocks 8.16.1 → 8.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) 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/builtins/data.d.ts +20 -6
  70. package/dist/v8/builtins/data.d.ts.map +1 -1
  71. package/dist/v8/builtins/data.js +33 -8
  72. package/dist/v8/builtins/data.js.map +1 -1
  73. package/dist/v8/cms.js +2 -2
  74. package/dist/v8/cms.js.map +1 -1
  75. package/dist/v8/settings.d.ts +28 -9
  76. package/dist/v8/settings.d.ts.map +1 -1
  77. package/dist/v8/settings.js +6 -10
  78. package/dist/v8/settings.js.map +1 -1
  79. package/dist/v8/telemetry.d.ts +13 -11
  80. package/dist/v8/telemetry.d.ts.map +1 -1
  81. package/dist/v8/telemetry.js +27 -17
  82. package/dist/v8/telemetry.js.map +1 -1
  83. package/dist/v8/types.d.ts +7 -3
  84. package/dist/v8/types.d.ts.map +1 -1
  85. package/package.json +6 -1
  86. package/skills/deco-storefront-performance/references/render-location.md +3 -2
  87. package/skills/deco-v7-to-v8-migration/references/telemetry.md +1 -1
  88. package/skills/deco-v7-to-v8-migration/scripts/siteSettings.ts +1 -1
  89. package/src/v8/analytics/client.ts +110 -0
  90. package/src/v8/analytics/runtime/globals.d.ts +36 -0
  91. package/src/v8/analytics/runtime/modules/click.ts +54 -0
  92. package/src/v8/analytics/runtime/modules/commerce.ts +73 -0
  93. package/src/v8/analytics/runtime/modules/consent.ts +150 -0
  94. package/src/v8/analytics/runtime/modules/deco.ts +207 -0
  95. package/src/v8/analytics/runtime/modules/engagement.ts +140 -0
  96. package/src/v8/analytics/runtime/modules/errors.ts +217 -0
  97. package/src/v8/analytics/runtime/modules/heatmap.ts +360 -0
  98. package/src/v8/analytics/runtime/modules/vitals.ts +128 -0
  99. package/src/v8/analytics/runtime/src/guards.ts +70 -0
  100. package/src/v8/analytics/runtime/src/index.ts +606 -0
  101. package/src/v8/analytics/runtime/src/queue.ts +40 -0
  102. package/src/v8/analytics/runtime/src/trim.ts +39 -0
  103. package/src/v8/analytics/runtime/view/heat-core.ts +335 -0
  104. package/src/v8/analytics/runtime/view/view.ts +596 -0
  105. package/src/v8/analytics/shared/anchor.ts +171 -0
  106. package/src/v8/analytics/shared/contract.ts +691 -0
  107. package/src/v8/analytics/tsconfig.json +14 -0
  108. package/src/v8/builtins/data.ts +44 -9
  109. package/src/v8/cms.ts +4 -4
  110. package/src/v8/settings.ts +13 -16
  111. package/src/v8/telemetry.ts +33 -29
  112. package/src/v8/types.ts +7 -3
@@ -0,0 +1,606 @@
1
+ import {
2
+ LIMITS,
3
+ WIRE,
4
+ CAMPAIGN_KEYS,
5
+ campaignKey,
6
+ isSampleable,
7
+ type Props,
8
+ } from "../../shared/contract.ts";
9
+ import { trimProps } from "./trim.ts";
10
+ import { BoundedQueue, type QueuedEvent } from "./queue.ts";
11
+ import { shouldSkip, whenVisible } from "./guards.ts";
12
+
13
+ type Cfg = {
14
+ s: string; // site id
15
+ k?: string; // self-serve key, when not resolved from Host
16
+ r?: number; // sampling
17
+ tier?: 0 | 1; // 1 = a stable id is allowed, WITH consent
18
+ hash?: boolean; // the site routes on location.hash
19
+ dev?: boolean; // collect even on a development host
20
+ x?: Record<string, string>; // experiment map, injected by SSR
21
+ e?: string; // endpoint
22
+ q?: unknown[] | { push: (r: unknown) => void }; // stub queue; a live dispatcher after boot
23
+ killed?: boolean;
24
+ hr?: number; // heatmap module: per-view sampling rate
25
+ er?: string[]; // errors module: cross-origin hosts that count as ours
26
+ h?: number; // heatmap module: 0 = switched off by the server
27
+ };
28
+
29
+ const w = globalThis as typeof globalThis & Record<string, any>;
30
+ const cfg: Cfg = w.__dq ?? (w.__dq = { s: "unknown" });
31
+ /** Config carried on the script tag itself, read before anything else.
32
+ *
33
+ * Instrumenting a real TanStack storefront found the hazard this exists for: the
34
+ * framework hoisted `<script async src=".../_dq/a.js">` into `<head>`, ABOVE the inline
35
+ * block that was supposed to configure it — measured at byte 190 against byte 1108. The
36
+ * collector therefore ran with no `dev` flag, `shouldSkip` correctly saw a development
37
+ * host, and boot returned early. The only symptom was silence, and `window.__dq` looked
38
+ * half-built afterwards.
39
+ *
40
+ * An attribute cannot lose that race: it is on the element that is executing. This is
41
+ * why OneDollarStats carries `data-hostname` and `data-devmode` rather than expecting a
42
+ * global to be there first, and it is the shape `<Stats />` (6.3) has to ship. */
43
+ const tag = (() => {
44
+ try {
45
+ return (
46
+ (document.currentScript as HTMLScriptElement | null) ??
47
+ document.querySelector<HTMLScriptElement>('script[src*="/_dq/a.js"]')
48
+ );
49
+ } catch {
50
+ return null;
51
+ }
52
+ })();
53
+ const attr = (n: string) => tag?.dataset?.[n];
54
+
55
+ /** Where beacons go.
56
+ *
57
+ * Derived from the SCRIPT'S OWN src, not from a relative path. Instrumenting a real
58
+ * storefront found why: the tag was loaded from our collector, the beacon used `/_dq/e`,
59
+ * and a relative path resolves against the PAGE's origin — so every event was posted to
60
+ * the shop's own server, which answered 200 with its homepage. Nothing reached the
61
+ * collector and nothing reported an error, because a 200 is a 200.
62
+ *
63
+ * A site on our CDN is unaffected, since both are the same origin; that is exactly why
64
+ * this survived every local test. It breaks for every site that is NOT on our CDN — the
65
+ * self-serve tier, which is the whole reason the `?k=` path exists.
66
+ *
67
+ * An explicit `cfg.e` still wins, and the relative path remains the last resort. */
68
+ const ENDPOINT = (() => {
69
+ if (cfg.e) return cfg.e;
70
+ try {
71
+ const src = tag?.src;
72
+ if (src) return new URL("/_dq/e", src).toString();
73
+ } catch {
74
+ /* a src we cannot parse is not a reason to fail to collect */
75
+ }
76
+ return "/_dq/e";
77
+ })();
78
+
79
+ const queue = new BoundedQueue();
80
+ let superProps: Record<string, string> = {};
81
+ let optedOut = false;
82
+ /** Readable from config so it is on BEFORE boot. The skip reason — "local", "opt-out",
83
+ * "automation" — is logged during boot, so a flag that can only be set by calling a
84
+ * method afterwards cannot explain the one failure it exists for: nothing arrives and
85
+ * there is no way to tell whether the tag is wrong, the site is wrong, or the host is
86
+ * excluded. OneDollarStats reaches the same conclusion with `data-devmode`. */
87
+
88
+ if (attr("dev") !== undefined)
89
+ (w as any).__dq = Object.assign((w as any).__dq ?? {}, { dev: attr("dev") !== "false" });
90
+ if (attr("debug") !== undefined)
91
+ (w as any).__dq = Object.assign((w as any).__dq ?? {}, { debug: attr("debug") !== "false" });
92
+
93
+ let skipped = false;
94
+ let debugOn = Boolean((w as any).__dq?.debug);
95
+ let timer: number | undefined;
96
+ let firstSent = false;
97
+
98
+ /** Run just before the last flush of a page load, so a module can add what it only knows
99
+ * at the end without spending a request of its own. */
100
+ const finalHooks: Array<() => void> = [];
101
+ /** Run when an SPA navigation changes the URL, BEFORE the new `$pageview`, with the path that
102
+ * is being left. A module measuring "this view" closes it here, so route 2 does not inherit
103
+ * route 1's scroll depth -- which is exactly what `$scroll` did before this existed. */
104
+ const routeHooks: Array<(prev: string) => void> = [];
105
+
106
+ const log = (...a: unknown[]) => debugOn && console.log("[dq]", ...a);
107
+ const uuidv7 = (): string => {
108
+ // Time-ordered so replay dedups by a key that also sorts, without pulling a dependency.
109
+ const t = Date.now();
110
+ const hex = t.toString(16).padStart(12, "0");
111
+ const r = crypto.getRandomValues(new Uint8Array(10));
112
+ const h = [...r].map((b) => b.toString(16).padStart(2, "0")).join("");
113
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-7${h.slice(0, 3)}-${(
114
+ (parseInt(h[3], 16) & 0x3) | 0x8
115
+ ).toString(16)}${h.slice(4, 7)}-${h.slice(7, 19)}`;
116
+ };
117
+
118
+ function enqueue(
119
+ rawName: unknown,
120
+ rawProps: unknown,
121
+ extra?: Record<string, unknown>,
122
+ urgent = false,
123
+ ) {
124
+ if (optedOut || cfg.killed) return;
125
+ // Only the tail is sheddable. `$` events carry every core metric and are bounded per
126
+ // pageview anyway, so exempting them costs almost no volume and keeps visitor counts,
127
+ // sessions and vitals exact at any rate.
128
+ if (
129
+ typeof cfg.r === "number" &&
130
+ cfg.r < 1 &&
131
+ isSampleable(String(rawName ?? "")) &&
132
+ Math.random() > cfg.r
133
+ )
134
+ return;
135
+
136
+ // Only the two violations that cost upload bytes are caught here; the Worker owns the
137
+ // rest, including the event name. Sending a name unnormalised costs nothing and saves
138
+ // 2.3 KB of normaliser in every visitor's download.
139
+ const trunc = new Set<string>();
140
+ const props = trimProps({ ...superProps, ...((rawProps as object) ?? {}) }, (f) => trunc.add(f));
141
+ const name = String(rawName ?? "").slice(0, LIMITS.nameLen * 2);
142
+
143
+ // Short keys on the wire. Field names are a double-digit share of a ~293 byte event, and
144
+ // the visitor pays that upload — often on mobile data. The Worker expands them, so
145
+ // nothing downstream ever sees the abbreviation.
146
+ const e: QueuedEvent = {
147
+ [WIRE.event_id]: uuidv7(),
148
+ [WIRE.ts]: new Date().toISOString(),
149
+ [WIRE.name]: name,
150
+ [WIRE.path]: location.pathname.slice(0, LIMITS.pathLen),
151
+ [WIRE.props]: props,
152
+ };
153
+ if (document.referrer) e[WIRE.referrer] = document.referrer.slice(0, LIMITS.refLen);
154
+ // On EVERY event of the page load, not just the landing pageview: an event fired
155
+ // after a client-side route change still belongs to the campaign that brought the
156
+ // visitor, and by then the query string is long gone.
157
+ if (hasCampaign) e[WIRE.utm] = campaign;
158
+ // Installed by the consent module, which only tier-1 sites download. Core asks; it does
159
+ // not know what consent is, the same way it does not know what a cart is.
160
+ const ci = (w as any).__dqCid?.();
161
+ if (ci) e[WIRE.client_id] = ci;
162
+ if (cfg.x && Object.keys(cfg.x).length) e[WIRE.exp] = cfg.x;
163
+
164
+ // Absent rather than empty: a key that is not sent costs nothing, while an empty one
165
+ // costs its own name on every event.
166
+ if (extra) {
167
+ for (const [k, v] of Object.entries(extra)) {
168
+ if (v === undefined || v === null || v === "") continue;
169
+ const short = (WIRE as Record<string, string>)[k];
170
+ e[short ?? k] = v;
171
+ }
172
+ }
173
+ if (trunc.size) e[WIRE._trunc] = [...trunc];
174
+
175
+ queue.push(e);
176
+ // The FIRST event of a page load goes immediately; everything after it batches.
177
+ //
178
+ // End-to-end latency measured 8.3s and none of it was the warehouse — ClickHouse answers
179
+ // in milliseconds. It was this queue: an event waits up to flushMs before anyone can see
180
+ // it, which makes a realtime view structurally impossible however fast the read side is.
181
+ //
182
+ // Flushing only the first costs ONE extra request per page load rather than one per
183
+ // event, so the batching that protects the collector is untouched — and the first event
184
+ // is the one realtime needs, because it is the pageview saying a visitor arrived.
185
+ if (!firstSent) {
186
+ firstSent = true;
187
+ flush();
188
+ return;
189
+ }
190
+
191
+ // Some events must not wait, and CORE DOES NOT DECIDE WHICH. This started as a name
192
+ // check here -- `name === "purchase"` -- which put the word "purchase" in the core
193
+ // bundle and broke the test asserting that a site without the commerce module does not
194
+ // download commerce vocabulary. That test was right: core does not know what a cart is,
195
+ // and the module that owns an event is the only thing that can judge what losing it
196
+ // costs. So urgency arrives as a parameter from the caller.
197
+ if (urgent) {
198
+ flush();
199
+ return;
200
+ }
201
+
202
+ log("queued", name, e);
203
+ if (queue.length >= LIMITS.eventsPerBatch) flush();
204
+ }
205
+
206
+ function applyCommand(cmd: Record<string, unknown> | null) {
207
+ if (!cmd) return;
208
+ if (cmd.k) {
209
+ cfg.killed = true;
210
+ log("killed by server");
211
+ }
212
+ if (typeof cmd.r === "number") {
213
+ cfg.r = cmd.r;
214
+ log("sampling ->", cmd.r);
215
+ }
216
+ // Module-level switch: `{h:0}` stops the heatmap module for the rest of the page load
217
+ // without touching core collection.
218
+ if ("h" in cmd) cfg.h = cmd.h as number;
219
+ }
220
+
221
+ const payload = (events: QueuedEvent[]) => JSON.stringify({ site: cfg.s, key: cfg.k, events });
222
+
223
+ /** The last chance to deliver, so it does not get to fail quietly.
224
+ *
225
+ * sendBeacon returns false more often than people expect: over the browser's beacon
226
+ * queue limit, blocked by a connect-src CSP, or simply absent. Some privacy modes throw
227
+ * instead of returning false. Either way the batch is still in hand, and keepalive fetch
228
+ * survives unload too — so it is the fallback rather than the primary, which sendBeacon
229
+ * remains because it is the more reliable of the two during teardown. */
230
+ function sendFinal(body: string): void {
231
+ try {
232
+ const blob = new Blob([body], { type: "text/plain" });
233
+ if (navigator.sendBeacon && navigator.sendBeacon(ENDPOINT, blob)) {
234
+ log("final via sendBeacon", body.length);
235
+ return;
236
+ }
237
+ log("sendBeacon declined, falling back");
238
+ } catch (e) {
239
+ log("sendBeacon threw, falling back", e);
240
+ }
241
+
242
+ try {
243
+ fetch(ENDPOINT, {
244
+ method: "POST",
245
+ body,
246
+ keepalive: true,
247
+ headers: { "Content-Type": "text/plain" },
248
+ }).catch(() => {});
249
+ log("final via keepalive fetch", body.length);
250
+ } catch (e) {
251
+ log("both transports failed", e);
252
+ }
253
+ }
254
+
255
+ function flush(final = false) {
256
+ if (final) {
257
+ // Drain everything, not one batch. A tab closing with 120 events queued would
258
+ // otherwise deliver 50 and lose 70 — and nothing would report the loss.
259
+ let batch: QueuedEvent[];
260
+ while ((batch = queue.drain()).length) sendFinal(payload(batch));
261
+ return;
262
+ }
263
+
264
+ const batch = queue.drain();
265
+ if (!batch.length) return;
266
+
267
+ // text/plain avoids the CORS preflight: application/json cross-origin would trigger an
268
+ // OPTIONS before every beacon and double the request count.
269
+ fetch(ENDPOINT + (debugOn ? "?debug=1" : ""), {
270
+ method: "POST",
271
+ body: payload(batch),
272
+ keepalive: true,
273
+ headers: { "Content-Type": "text/plain" },
274
+ })
275
+ .then((r) => (r.status === 200 ? r.json() : null))
276
+ .then((cmd) => {
277
+ // With debug on the Worker echoes the flags it applied, so a developer sees what was
278
+ // rewritten without querying the warehouse — and without the client carrying the
279
+ // normaliser to find out.
280
+ const c = cmd as { _trunc?: string[] } | null;
281
+ if (c?._trunc && debugOn) console.warn("[dq] server adjusted:", c._trunc);
282
+ applyCommand(c as Record<string, unknown> | null);
283
+ })
284
+ .catch(() => {
285
+ /* losing a batch is not worth breaking the page over */
286
+ });
287
+ }
288
+
289
+ function pageview(props?: Props) {
290
+ enqueue("$pageview", props);
291
+ }
292
+
293
+ /** trimProps accepts primitives and returns them unchanged; superProps is the string map
294
+ * every event spreads. Narrow here rather than widening superProps. */
295
+ /** Campaign parameters live in the query string of the LANDING url and are gone by the
296
+ * next navigation. Captured once at load and attached to every event in this page load.
297
+ *
298
+ * Deliberately NOT persisted to storage: keeping them across page loads would need
299
+ * device storage, which is the one thing that turns a cookieless collector into one
300
+ * that needs a consent banner. Attribution across the visit is a server-side question
301
+ * instead — the landing event carries the campaign, and a session inherits it from its
302
+ * own first event. */
303
+ const campaign: Record<string, string> = (() => {
304
+ const out: Record<string, string> = {};
305
+ try {
306
+ const q = new URLSearchParams(location.search);
307
+ for (const raw of CAMPAIGN_KEYS) {
308
+ const v = q.get(raw);
309
+ if (!v) continue;
310
+ const k = campaignKey(raw);
311
+ if (k) out[k] = v.slice(0, 200);
312
+ }
313
+ } catch {
314
+ /* a malformed query string is not worth breaking collection over */
315
+ }
316
+ return out;
317
+ })();
318
+
319
+ const hasCampaign = Object.keys(campaign).length > 0;
320
+
321
+ const asStrings = (o: Record<string, unknown>): Record<string, string> => {
322
+ const out: Record<string, string> = {};
323
+ for (const k in o) out[k] = String(o[k]);
324
+ return out;
325
+ };
326
+
327
+ const api = {
328
+ track: (name: string, props?: Props) => enqueue(name, props),
329
+ pageview,
330
+ // trimProps, not sanitizeProps: the latter has never existed anywhere in the repo. A
331
+ // rename in "one payload contract" (f07c704) missed these two call sites; esbuild
332
+ // treats an unknown identifier as a runtime global rather than an error, and nothing
333
+ // typechecked — so two of the fourteen documented API methods have thrown
334
+ // ReferenceError ever since, silently, because no test called them.
335
+ //
336
+ // The no-op flag sink is deliberate: enqueue() re-trims { ...superProps, ...props } on
337
+ // every event, so anything worth flagging is flagged there with the event it affects.
338
+ // Flagging here as well would attribute it to whichever event happened to be next.
339
+ set: (p: Props) => {
340
+ superProps = { ...superProps, ...asStrings(trimProps(p, () => {})) };
341
+ },
342
+ setOnce: (p: Props) => {
343
+ const clean = asStrings(trimProps(p, () => {}));
344
+ for (const k in clean) if (!(k in superProps)) superProps[k] = clean[k];
345
+ },
346
+ unset: (keys: string[]) => {
347
+ for (const k of keys) delete superProps[k];
348
+ },
349
+ setExperiment: (id: string, variant: string) => {
350
+ cfg.x = { ...(cfg.x ?? {}), [id]: variant };
351
+ },
352
+ variant: (id: string) => cfg.x?.[id],
353
+ captureException: (err: unknown, props?: Props) => {
354
+ const e = err as Error;
355
+ enqueue("$error", props, {
356
+ error_type: e?.name ?? "Error",
357
+ error_message: String(e?.message ?? err).slice(0, LIMITS.valueLen),
358
+ error_stack: (e?.stack ?? "").slice(0, 8000),
359
+ });
360
+ },
361
+ optIn: () => {
362
+ optedOut = false;
363
+ try {
364
+ localStorage.removeItem("__dq_ignore");
365
+ } catch {}
366
+ },
367
+ optOut: () => {
368
+ optedOut = true;
369
+ try {
370
+ localStorage.setItem("__dq_ignore", "true");
371
+ } catch {}
372
+ },
373
+ hasOptedOut: () => optedOut,
374
+ /** Replaced by the consent module on a tier-1 site. Left as a no-op so a site that
375
+ * calls it at tier 0 does not throw — declining consent that was never asked for is
376
+ * not an error. */
377
+ consent: (_v: unknown) => {},
378
+ /** Send whatever is queued now. Useful before a hard navigation the SDK cannot see,
379
+ * such as handing off to a payment provider. */
380
+ flush: () => flush(),
381
+ debug: (on = true) => {
382
+ debugOn = on;
383
+ },
384
+ reset: () => {
385
+ superProps = {};
386
+ },
387
+ };
388
+
389
+ /** The seam optional modules attach to. Core knows how to queue an event and nothing
390
+ * about what the event means — a module can add named helpers on top without the core
391
+ * learning what a cart is. */
392
+ w.__dqRegister = (
393
+ fn: (
394
+ e: typeof enqueue,
395
+ api: Record<string, unknown>,
396
+ onFinal: (h: () => void) => void,
397
+ onRoute: (h: (prev: string) => void) => void,
398
+ ) => void,
399
+ ) => {
400
+ // A module must not install its helpers when collection is off. Found on a real
401
+ // storefront: with boot skipped, `window.__dq` carried `addToCart` and
402
+ // `captureException` from the modules while core's own `pageview` and `flush` were
403
+ // absent — a half-built object that invites a site to call into a runtime that will
404
+ // never send. Skipped means skipped, for everyone.
405
+ if (skipped) return;
406
+ try {
407
+ fn(
408
+ enqueue,
409
+ cfg as Record<string, unknown>,
410
+ (h) => {
411
+ finalHooks.push(h);
412
+ },
413
+ (h) => {
414
+ routeHooks.push(h);
415
+ },
416
+ );
417
+ } catch (err) {
418
+ log("module failed", err);
419
+ }
420
+ };
421
+
422
+ /** One call recorded by the stub, replayed against the real API.
423
+ *
424
+ * Two shapes. `{ m, a }` is the official snippet's: a METHOD and its arguments, so a helper
425
+ * called before boot (`viewItem`, `purchase`, `captureException`) arrives with its typed columns
426
+ * -- value, currency, item_ids, transaction_id -- instead of being flattened into props or
427
+ * dropped. Anything else is the original `track` stub's `[name, props]`, which keeps working.
428
+ *
429
+ * `replaying` stops the one loop this can make: a method no module provided is still the stub,
430
+ * and the stub pushes straight back here. That call is dropped, with a debug line saying why. */
431
+ let replaying = false;
432
+ function replay(r: unknown) {
433
+ if (!r || replaying) {
434
+ if (r) log("no such method; dropped", r);
435
+ return;
436
+ }
437
+ replaying = true;
438
+ try {
439
+ const rec = r as { m?: unknown; a?: ArrayLike<unknown> } & ArrayLike<unknown>;
440
+ if (typeof rec.m === "string") {
441
+ const fn = (cfg as Record<string, unknown>)[rec.m];
442
+ if (typeof fn === "function") fn(...Array.from(rec.a ?? []));
443
+ else log("no such method; dropped", rec.m);
444
+ } else {
445
+ enqueue(rec[0], rec[1]);
446
+ }
447
+ } catch (e) {
448
+ log("replay failed", e);
449
+ } finally {
450
+ replaying = false;
451
+ }
452
+ }
453
+
454
+ function boot() {
455
+ // ONCE PER PAGE, whatever put the tag there.
456
+ //
457
+ // Two identical `<script src>` tags both execute — the browser reuses the cached RESOURCE, not
458
+ // the execution — and measured, that is two `$pageview` events for one page load, doubling
459
+ // every number the page produces. It stopped being hypothetical when the TanStack framework
460
+ // started mounting the tag itself: any site that had already added it by hand now has both,
461
+ // and the duplicate arrives on a dependency bump rather than on a code change anyone reviews.
462
+ //
463
+ // The guard belongs HERE and not in either component, because the component can only know
464
+ // about itself. This covers every way a page ends up with two tags — two components, a
465
+ // component plus a hand-pasted snippet, a tag manager that injects a third.
466
+ //
467
+ // `w` rather than a module-level flag: two copies of this bundle are two module scopes, so a
468
+ // local `let` would be two separate flags, each false.
469
+ if (w.__dqBooted) {
470
+ log("already booted; this tag is a duplicate");
471
+ return;
472
+ }
473
+ w.__dqBooted = true;
474
+
475
+ // VIEW MODE: Studio framing this page to draw a heatmap over it. Nothing is collected -- no
476
+ // pageview, no module, no beacon -- and the overlay is a separate chunk that only this branch
477
+ // downloads; every other visitor pays for this test and nothing else. The chunk does the
478
+ // origin handshake: until an allow-listed parent speaks first, it does nothing at all.
479
+ if (/[?&]dq_view=1(&|$)/.test(location.search) && w.top !== w.self) {
480
+ skipped = true;
481
+ const s = document.createElement("script");
482
+ s.src = ENDPOINT.replace(/\/_dq\/e$/, "/_dq/v.js");
483
+ document.head.appendChild(s);
484
+ return;
485
+ }
486
+
487
+ const skip = shouldSkip(w);
488
+ if (skip) {
489
+ skipped = true;
490
+ log("not collecting:", skip);
491
+ return;
492
+ }
493
+
494
+ const stubbed = (cfg.q ?? []) as unknown[];
495
+ Object.assign(cfg, api);
496
+ // From here on the stub's queue is a live dispatcher, so a stub method a site captured before
497
+ // boot (or one no module replaced) still delivers instead of pushing into an array nobody reads.
498
+ cfg.q = { push: replay };
499
+ // A MICROTASK, because the commerce helpers do not exist yet: modules are appended after core
500
+ // in the same bundle and register when it finishes executing. Replaying here would find
501
+ // `viewItem` still pointing at the stub, which is exactly how a storefront that fires
502
+ // `view_item` before the script loads lost 94% of them.
503
+ queueMicrotask(() => {
504
+ for (const r of stubbed) replay(r);
505
+ });
506
+
507
+ whenVisible(document, () => pageview());
508
+
509
+ // SPA navigation. The framework serves full documents, but islands and client routers
510
+ // change the URL without one.
511
+ // One notion of "the URL changed", shared by every path that can change it.
512
+ //
513
+ // pushState, popstate and hashchange are not independent events: assigning
514
+ // `location.hash` fires hashchange AND popstate, so a hash-routed site counted every
515
+ // navigation twice — measured, five page views for what was three. Routing all three
516
+ // through here makes a repeat of the same URL a no-op, which also covers the router that
517
+ // calls pushState and then dispatches popstate itself.
518
+ //
519
+ // The hash is part of "the URL" only on a site that routes on it. Elsewhere a click on
520
+ // `#reviews` is an anchor -- and it still fires popstate, so leaving the fragment in the key
521
+ // counted every in-page jump as a page view even with `hash` off.
522
+ const here = () => location.pathname + location.search + (cfg.hash ? location.hash : "");
523
+ let lastUrl = here();
524
+ let lastPath = location.pathname;
525
+ const route = () => {
526
+ const prev = lastPath;
527
+ lastPath = location.pathname;
528
+ for (const fn of routeHooks) {
529
+ try {
530
+ fn(prev);
531
+ } catch {
532
+ /* one module must not stop another */
533
+ }
534
+ }
535
+ };
536
+ const navigated = () => {
537
+ const now = here();
538
+ if (now === lastUrl) return;
539
+ lastUrl = now;
540
+ route();
541
+ pageview();
542
+ };
543
+
544
+ const push = history.pushState;
545
+ if (push) {
546
+ history.pushState = function (this: History, ...a: any[]) {
547
+ push.apply(this, a as any);
548
+ navigated();
549
+ } as any;
550
+ addEventListener("popstate", navigated);
551
+ }
552
+
553
+ // replaceState was not patched at all, and routers use it constantly — canonical
554
+ // rewrites, redirects, writing filter state into the URL. Only a changed PATH counts
555
+ // here: a PLP rewriting its query string on every filter click is one page view, and
556
+ // firing on each would turn browsing into a traffic spike. This is deliberately stricter
557
+ // than `navigated`, which treats any URL change as a navigation.
558
+ const replace = history.replaceState;
559
+ if (replace) {
560
+ history.replaceState = function (this: History, ...a: any[]) {
561
+ const before = location.pathname;
562
+ replace.apply(this, a as any);
563
+ if (location.pathname !== before) {
564
+ lastUrl = here();
565
+ route();
566
+ pageview();
567
+ }
568
+ } as any;
569
+ }
570
+
571
+ // Hash routing, opt-in per site. NOT automatic: on an ordinary page `#secao` is an
572
+ // anchor, and counting those would inflate every long article and every FAQ. A site that
573
+ // routes on the hash declares it — which is how Plausible and OneDollarStats handle it
574
+ // too, each with a mode for the case.
575
+ if (cfg.hash) addEventListener("hashchange", navigated);
576
+
577
+ timer = setInterval(() => flush(), LIMITS.flushMs) as unknown as number;
578
+
579
+ // Both, on purpose. pagehide misses backgrounding on mobile, and visibilitychange
580
+ // misses some desktop closes; a page can also be restored from bfcache after either.
581
+ // Double-firing is harmless because a drained queue makes the second call a no-op.
582
+ // Modules that only know their value when the page ends — scroll depth, the vitals,
583
+ // the accumulated error repeats — contribute HERE, and then ONE flush carries all of
584
+ // it. Each of them used to call flush() itself, which produced four requests on the
585
+ // way out where one would do: the collector paying per module rather than per visit.
586
+ const onFinal = () => {
587
+ for (const fn of finalHooks) {
588
+ try {
589
+ fn();
590
+ } catch {
591
+ /* one module must not stop another */
592
+ }
593
+ }
594
+ flush(true);
595
+ };
596
+ addEventListener("pagehide", onFinal);
597
+ // On document, not window: visibilitychange is specified to fire at the Document. It
598
+ // does bubble, so a window listener happens to work in a real browser — but relying on
599
+ // that is fragile, and it silently does nothing for any dispatch that is not bubbling.
600
+ document.addEventListener("visibilitychange", () => {
601
+ if (document.visibilityState === "hidden") onFinal();
602
+ });
603
+ }
604
+
605
+ boot();
606
+ export {};
@@ -0,0 +1,40 @@
1
+ import { F_QUEUE_OVERFLOW, LIMITS, WIRE } from "../../shared/contract.ts";
2
+
3
+ export type QueuedEvent = Record<string, unknown>;
4
+
5
+ /** Bounded, because a page firing events in a loop must not grow memory in a customer's
6
+ * browser without limit. Drops the oldest and marks the survivor, so the loss is visible
7
+ * in the data rather than inferred from a gap. */
8
+ export class BoundedQueue {
9
+ private items: QueuedEvent[] = [];
10
+
11
+ push(e: QueuedEvent): void {
12
+ if (this.items.length >= LIMITS.queueMax) {
13
+ this.items.shift();
14
+ const t = (e[WIRE._trunc] as string[] | undefined) ?? [];
15
+ if (!t.includes(F_QUEUE_OVERFLOW)) t.push(F_QUEUE_OVERFLOW);
16
+ e[WIRE._trunc] = t;
17
+ }
18
+ this.items.push(e);
19
+ }
20
+
21
+ /** Up to `eventsPerBatch` events AND `batchBytes` of them. Fifty `$error`s at 8 KB each is a
22
+ * 400 KB body: the collector answers 413, and keepalive or sendBeacon refuses it outright, so
23
+ * the whole batch was lost. Always at least one event, so an oversize one cannot wedge the
24
+ * queue; the collector judges it alone. */
25
+ drain(): QueuedEvent[] {
26
+ let n = 0,
27
+ bytes = 0;
28
+ const enc = new TextEncoder();
29
+ while (n < this.items.length && n < LIMITS.eventsPerBatch) {
30
+ bytes += enc.encode(JSON.stringify(this.items[n])).length + 1;
31
+ if (n && bytes > LIMITS.batchBytes) break;
32
+ n++;
33
+ }
34
+ return this.items.splice(0, n);
35
+ }
36
+
37
+ get length(): number {
38
+ return this.items.length;
39
+ }
40
+ }
@@ -0,0 +1,39 @@
1
+ import { F_PROPS_COUNT, F_PROPS_LEN, F_PROPS_TYPE, LIMITS } from "../../shared/contract.ts";
2
+
3
+ /** The client's share of the contract, kept to the two violations that actually cost
4
+ * upload bytes: an oversized value and a non-primitive that would be serialised whole.
5
+ *
6
+ * Everything else — charset, reserved names, currency, timestamps — is left to the
7
+ * Worker. Shipping the full normaliser cost 2.3 KB minified in every visitor's download
8
+ * to save bytes on payloads most sites never send, which is the wrong trade. The Worker
9
+ * is the authority regardless, so the client's job is bandwidth, not correctness.
10
+ *
11
+ * What a developer loses by not normalising here is visibility, and that comes back the
12
+ * cheaper way: with `debug()` on, the collect response echoes the flags the Worker
13
+ * applied. Zero bytes in the normal path, full feedback when someone is looking. */
14
+ export function trimProps(input: unknown, flag: (f: string) => void): Record<string, unknown> {
15
+ const out: Record<string, unknown> = {};
16
+ if (!input || typeof input !== "object" || Array.isArray(input)) return out;
17
+
18
+ let n = 0;
19
+ for (const [k, v] of Object.entries(input as Record<string, unknown>)) {
20
+ if (n >= LIMITS.propKeys) {
21
+ flag(F_PROPS_COUNT);
22
+ break;
23
+ }
24
+ if (v === null || v === undefined) continue;
25
+
26
+ const t = typeof v;
27
+ if (t !== "string" && t !== "number" && t !== "boolean") {
28
+ flag(F_PROPS_TYPE);
29
+ continue;
30
+ }
31
+
32
+ out[k] =
33
+ t === "string" && (v as string).length > LIMITS.valueLen
34
+ ? (flag(F_PROPS_LEN), (v as string).slice(0, LIMITS.valueLen))
35
+ : v;
36
+ n++;
37
+ }
38
+ return out;
39
+ }