@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.
- package/dist/v8/analytics/client.d.ts +48 -0
- package/dist/v8/analytics/client.d.ts.map +1 -0
- package/dist/v8/analytics/client.js +71 -0
- package/dist/v8/analytics/client.js.map +1 -0
- package/dist/v8/analytics/runtime/modules/click.d.ts +2 -0
- package/dist/v8/analytics/runtime/modules/click.d.ts.map +1 -0
- package/dist/v8/analytics/runtime/modules/click.js +48 -0
- package/dist/v8/analytics/runtime/modules/click.js.map +1 -0
- package/dist/v8/analytics/runtime/modules/commerce.d.ts +2 -0
- package/dist/v8/analytics/runtime/modules/commerce.d.ts.map +1 -0
- package/dist/v8/analytics/runtime/modules/commerce.js +41 -0
- package/dist/v8/analytics/runtime/modules/commerce.js.map +1 -0
- package/dist/v8/analytics/runtime/modules/consent.d.ts +33 -0
- package/dist/v8/analytics/runtime/modules/consent.d.ts.map +1 -0
- package/dist/v8/analytics/runtime/modules/consent.js +154 -0
- package/dist/v8/analytics/runtime/modules/consent.js.map +1 -0
- package/dist/v8/analytics/runtime/modules/deco.d.ts +2 -0
- package/dist/v8/analytics/runtime/modules/deco.d.ts.map +1 -0
- package/dist/v8/analytics/runtime/modules/deco.js +209 -0
- package/dist/v8/analytics/runtime/modules/deco.js.map +1 -0
- package/dist/v8/analytics/runtime/modules/engagement.d.ts +2 -0
- package/dist/v8/analytics/runtime/modules/engagement.d.ts.map +1 -0
- package/dist/v8/analytics/runtime/modules/engagement.js +128 -0
- package/dist/v8/analytics/runtime/modules/engagement.js.map +1 -0
- package/dist/v8/analytics/runtime/modules/errors.d.ts +2 -0
- package/dist/v8/analytics/runtime/modules/errors.d.ts.map +1 -0
- package/dist/v8/analytics/runtime/modules/errors.js +167 -0
- package/dist/v8/analytics/runtime/modules/errors.js.map +1 -0
- package/dist/v8/analytics/runtime/modules/heatmap.d.ts +2 -0
- package/dist/v8/analytics/runtime/modules/heatmap.d.ts.map +1 -0
- package/dist/v8/analytics/runtime/modules/heatmap.js +316 -0
- package/dist/v8/analytics/runtime/modules/heatmap.js.map +1 -0
- package/dist/v8/analytics/runtime/modules/vitals.d.ts +2 -0
- package/dist/v8/analytics/runtime/modules/vitals.d.ts.map +1 -0
- package/dist/v8/analytics/runtime/modules/vitals.js +119 -0
- package/dist/v8/analytics/runtime/modules/vitals.js.map +1 -0
- package/dist/v8/analytics/runtime/src/guards.d.ts +10 -0
- package/dist/v8/analytics/runtime/src/guards.d.ts.map +1 -0
- package/dist/v8/analytics/runtime/src/guards.js +70 -0
- package/dist/v8/analytics/runtime/src/guards.js.map +1 -0
- package/dist/v8/analytics/runtime/src/index.d.ts +2 -0
- package/dist/v8/analytics/runtime/src/index.d.ts.map +1 -0
- package/dist/v8/analytics/runtime/src/index.js +562 -0
- package/dist/v8/analytics/runtime/src/index.js.map +1 -0
- package/dist/v8/analytics/runtime/src/queue.d.ts +15 -0
- package/dist/v8/analytics/runtime/src/queue.d.ts.map +1 -0
- package/dist/v8/analytics/runtime/src/queue.js +36 -0
- package/dist/v8/analytics/runtime/src/queue.js.map +1 -0
- package/dist/v8/analytics/runtime/src/trim.d.ts +13 -0
- package/dist/v8/analytics/runtime/src/trim.d.ts.map +1 -0
- package/dist/v8/analytics/runtime/src/trim.js +38 -0
- package/dist/v8/analytics/runtime/src/trim.js.map +1 -0
- package/dist/v8/analytics/runtime/view/heat-core.d.ts +69 -0
- package/dist/v8/analytics/runtime/view/heat-core.d.ts.map +1 -0
- package/dist/v8/analytics/runtime/view/heat-core.js +314 -0
- package/dist/v8/analytics/runtime/view/heat-core.js.map +1 -0
- package/dist/v8/analytics/runtime/view/view.d.ts +51 -0
- package/dist/v8/analytics/runtime/view/view.d.ts.map +1 -0
- package/dist/v8/analytics/runtime/view/view.js +525 -0
- package/dist/v8/analytics/runtime/view/view.js.map +1 -0
- package/dist/v8/analytics/shared/anchor.d.ts +71 -0
- package/dist/v8/analytics/shared/anchor.d.ts.map +1 -0
- package/dist/v8/analytics/shared/anchor.js +155 -0
- package/dist/v8/analytics/shared/anchor.js.map +1 -0
- package/dist/v8/analytics/shared/contract.d.ts +294 -0
- package/dist/v8/analytics/shared/contract.d.ts.map +1 -0
- package/dist/v8/analytics/shared/contract.js +652 -0
- package/dist/v8/analytics/shared/contract.js.map +1 -0
- package/dist/v8/fetch.d.ts.map +1 -1
- package/dist/v8/fetch.js +27 -2
- package/dist/v8/fetch.js.map +1 -1
- package/dist/v8/telemetry.d.ts +2 -0
- package/dist/v8/telemetry.d.ts.map +1 -1
- package/dist/v8/telemetry.js +21 -6
- package/dist/v8/telemetry.js.map +1 -1
- package/package.json +6 -1
- package/src/v8/analytics/client.ts +110 -0
- package/src/v8/analytics/runtime/globals.d.ts +36 -0
- package/src/v8/analytics/runtime/modules/click.ts +54 -0
- package/src/v8/analytics/runtime/modules/commerce.ts +73 -0
- package/src/v8/analytics/runtime/modules/consent.ts +150 -0
- package/src/v8/analytics/runtime/modules/deco.ts +207 -0
- package/src/v8/analytics/runtime/modules/engagement.ts +140 -0
- package/src/v8/analytics/runtime/modules/errors.ts +217 -0
- package/src/v8/analytics/runtime/modules/heatmap.ts +360 -0
- package/src/v8/analytics/runtime/modules/vitals.ts +128 -0
- package/src/v8/analytics/runtime/src/guards.ts +70 -0
- package/src/v8/analytics/runtime/src/index.ts +606 -0
- package/src/v8/analytics/runtime/src/queue.ts +40 -0
- package/src/v8/analytics/runtime/src/trim.ts +39 -0
- package/src/v8/analytics/runtime/view/heat-core.ts +335 -0
- package/src/v8/analytics/runtime/view/view.ts +596 -0
- package/src/v8/analytics/shared/anchor.ts +171 -0
- package/src/v8/analytics/shared/contract.ts +691 -0
- package/src/v8/analytics/tsconfig.json +14 -0
- package/src/v8/fetch.ts +27 -2
- package/src/v8/telemetry.ts +25 -5
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
/** Consent, and the stable identifier it unlocks.
|
|
2
|
+
*
|
|
3
|
+
* At tier 0 — the default, and what every site runs today — there is no consent to ask
|
|
4
|
+
* for and nothing here does anything. Identity is an HMAC over a salt the Worker rotates
|
|
5
|
+
* and deletes every day, which is what makes the collector cookieless and is the same
|
|
6
|
+
* design Plausible ships. Its cost is that the same person is a new identifier tomorrow,
|
|
7
|
+
* so retention cannot be measured at all.
|
|
8
|
+
*
|
|
9
|
+
* Tier 1 buys that back, and only where a visitor has actually agreed. We deliberately do
|
|
10
|
+
* NOT ship a banner: every serious storefront already runs a CMP — farmrio loads OneTrust,
|
|
11
|
+
* 898 KB of it — and a second prompt would ask the visitor twice while leaving it
|
|
12
|
+
* ambiguous which consent governs. So this listens for the consent that already exists
|
|
13
|
+
* and adds an explicit call for sites whose banner is homegrown.
|
|
14
|
+
*
|
|
15
|
+
* Three sources, in the order a site is likely to have them:
|
|
16
|
+
* 1. `__dq.consent(true|false)` — explicit, and always wins
|
|
17
|
+
* 2. IAB TCF v2 `__tcfapi` — what OneTrust and Cookiebot expose
|
|
18
|
+
* 3. Google Consent Mode — `analytics_storage` on the dataLayer, for GTM sites
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
const KEY = "_dq_cid";
|
|
22
|
+
|
|
23
|
+
type Listener = (granted: boolean) => void;
|
|
24
|
+
const listeners: Listener[] = [];
|
|
25
|
+
let granted: boolean | null = null; // null = not yet known, which is not "no"
|
|
26
|
+
|
|
27
|
+
/** A random identifier, not derived from anything about the visitor. It is a label the
|
|
28
|
+
* browser carries, so it can be deleted by the visitor and is meaningless anywhere else.
|
|
29
|
+
* The Worker hashes it with the site before storing, so the same browser is a different
|
|
30
|
+
* identifier on each customer's site — without that we would have built the cross-client
|
|
31
|
+
* identity graph that tier 0 exists to avoid. */
|
|
32
|
+
function mint(): string {
|
|
33
|
+
const b = new Uint8Array(16);
|
|
34
|
+
(globalThis.crypto ?? ({} as Crypto)).getRandomValues?.(b);
|
|
35
|
+
return Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function store(): Storage | null {
|
|
39
|
+
try {
|
|
40
|
+
return window.localStorage;
|
|
41
|
+
} catch {
|
|
42
|
+
return null;
|
|
43
|
+
} // blocked in some privacy modes
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The stable id, or "" when there is no consent. Reading this never creates one: an id
|
|
47
|
+
* minted before consent arrived is a persistent identifier set without permission, which
|
|
48
|
+
* is the exact thing consent is being asked about. */
|
|
49
|
+
export function clientId(): string {
|
|
50
|
+
if (granted !== true) return "";
|
|
51
|
+
const s = store();
|
|
52
|
+
if (!s) return "";
|
|
53
|
+
let v = "";
|
|
54
|
+
try {
|
|
55
|
+
v = s.getItem(KEY) ?? "";
|
|
56
|
+
} catch {
|
|
57
|
+
return "";
|
|
58
|
+
}
|
|
59
|
+
if (!v || v.length !== 32) {
|
|
60
|
+
v = mint();
|
|
61
|
+
try {
|
|
62
|
+
s.setItem(KEY, v);
|
|
63
|
+
} catch {
|
|
64
|
+
return "";
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return v;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Withdrawal has to erase, not merely stop sending. A visitor who says no and still finds
|
|
71
|
+
* the identifier in their browser was not given a choice, they were given a checkbox. */
|
|
72
|
+
function forget() {
|
|
73
|
+
try {
|
|
74
|
+
store()?.removeItem(KEY);
|
|
75
|
+
} catch {
|
|
76
|
+
/* nothing to do about it */
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function setConsent(v: boolean) {
|
|
81
|
+
if (granted === v) return;
|
|
82
|
+
granted = v;
|
|
83
|
+
if (!v) forget();
|
|
84
|
+
for (const fn of listeners) {
|
|
85
|
+
try {
|
|
86
|
+
fn(v);
|
|
87
|
+
} catch {
|
|
88
|
+
/* one listener must not stop another */
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function onConsent(fn: Listener) {
|
|
94
|
+
listeners.push(fn);
|
|
95
|
+
}
|
|
96
|
+
export function consentKnown(): boolean {
|
|
97
|
+
return granted !== null;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Wires up whichever CMP is present. Safe to call when none is: every branch is guarded,
|
|
101
|
+
* and a site with no banner simply never grants, which leaves it at tier 0. */
|
|
102
|
+
export function watchConsent(w: any) {
|
|
103
|
+
// 1. Google Consent Mode. GTM sites push `['consent', 'update', {analytics_storage}]`,
|
|
104
|
+
// and the state may already be on the dataLayer before we load.
|
|
105
|
+
const dl = w.dataLayer;
|
|
106
|
+
if (Array.isArray(dl)) {
|
|
107
|
+
const read = (a: any) => {
|
|
108
|
+
if (a?.[0] === "consent" && (a[1] === "update" || a[1] === "default") && a[2]) {
|
|
109
|
+
if (a[2].analytics_storage === "granted") setConsent(true);
|
|
110
|
+
else if (a[2].analytics_storage === "denied") setConsent(false);
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
for (const a of dl) read(a);
|
|
114
|
+
const push = dl.push.bind(dl);
|
|
115
|
+
dl.push = function (...args: any[]) {
|
|
116
|
+
try {
|
|
117
|
+
read(args[0]);
|
|
118
|
+
} catch {
|
|
119
|
+
/* keep GTM working */
|
|
120
|
+
}
|
|
121
|
+
return push(...args);
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// 2. IAB TCF v2. Purpose 1 is "store and access information on a device", which is
|
|
126
|
+
// exactly what an identifier in localStorage is — not purpose 8 (measurement), which
|
|
127
|
+
// covers what we do with it once stored.
|
|
128
|
+
if (typeof w.__tcfapi === "function") {
|
|
129
|
+
try {
|
|
130
|
+
w.__tcfapi("addEventListener", 2, (data: any, ok: boolean) => {
|
|
131
|
+
if (!ok || !data) return;
|
|
132
|
+
if (data.eventStatus !== "tcloaded" && data.eventStatus !== "useractioncomplete") return;
|
|
133
|
+
setConsent(Boolean(data.purpose?.consents?.[1]));
|
|
134
|
+
});
|
|
135
|
+
} catch {
|
|
136
|
+
/* a CMP that throws is a CMP that has not granted */
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// Registered like every other module: core exposes the hook, this fills it in. A site at
|
|
142
|
+
// tier 0 downloads none of this — the same rule that keeps `commerce` off a blog.
|
|
143
|
+
window.__dqRegister?.((_enqueue, api: Record<string, unknown>) => {
|
|
144
|
+
watchConsent(window as any);
|
|
145
|
+
(window as any).__dqCid = clientId;
|
|
146
|
+
// Overrides the core no-op, so a homegrown banner has something to call.
|
|
147
|
+
api.consent = (v: unknown) => setConsent(Boolean(v));
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
export const CONSENT_KEY = KEY;
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
/** Adapter for deco storefronts.
|
|
2
|
+
*
|
|
3
|
+
* Two jobs, both about not asking a site to instrument twice: read the experiment
|
|
4
|
+
* assignment the origin already made, and forward the analytics events the framework
|
|
5
|
+
* already dispatches.
|
|
6
|
+
*
|
|
7
|
+
* It reads `deco_segment` rather than the event bus for flags because the cookie is set
|
|
8
|
+
* by the origin before any script runs, so the assignment is on the very first event —
|
|
9
|
+
* including the pageview. Waiting for the bus would attribute the landing pageview to no
|
|
10
|
+
* variant, which is the one event an experiment most needs attributed.
|
|
11
|
+
*/
|
|
12
|
+
import { LIMITS, STOREFRONT_EXP } from "../../shared/contract.ts";
|
|
13
|
+
|
|
14
|
+
type Props = Record<string, string | number | boolean>;
|
|
15
|
+
|
|
16
|
+
window.__dqRegister?.((enqueue, api: Record<string, unknown>) => {
|
|
17
|
+
const setExperiment = api.setExperiment as ((k: string, v: string) => void) | undefined;
|
|
18
|
+
|
|
19
|
+
// ---- assignment, from the cookie the origin already set ---------------------
|
|
20
|
+
//
|
|
21
|
+
// deco_segment is base64 of URI-encoded JSON: { active: string[], inactiveDrawn: [] }.
|
|
22
|
+
// It carries flag NAMES and nothing else — see deco/runtime/middleware.ts, which writes
|
|
23
|
+
// it from `flag.value` as a boolean.
|
|
24
|
+
//
|
|
25
|
+
// So both lists matter. `inactiveDrawn` means "evaluated for this visitor and came out
|
|
26
|
+
// false", which IS the control group: recording only the active flags would leave an
|
|
27
|
+
// experiment with a treatment arm and no baseline to compare it against, and a
|
|
28
|
+
// conversion rate with nothing to compare it to is not a result.
|
|
29
|
+
try {
|
|
30
|
+
const raw = document.cookie
|
|
31
|
+
.split(";")
|
|
32
|
+
.map((c) => c.trim())
|
|
33
|
+
.find((c) => c.startsWith("deco_segment="));
|
|
34
|
+
if (raw) {
|
|
35
|
+
const json = JSON.parse(decodeURIComponent(atob(raw.slice("deco_segment=".length))));
|
|
36
|
+
const set = (name: string, variant: string) => {
|
|
37
|
+
// Experiment keys allow hyphens; anything else the Worker normalises and flags.
|
|
38
|
+
if (name && name.length <= LIMITS.expKeyLen) setExperiment?.(name, variant);
|
|
39
|
+
};
|
|
40
|
+
for (const name of json.active ?? []) set(String(name), "on");
|
|
41
|
+
for (const name of json.inactiveDrawn ?? []) set(String(name), "off");
|
|
42
|
+
}
|
|
43
|
+
} catch {
|
|
44
|
+
// A malformed cookie is a site problem, not a reason to stop collecting.
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// ---- the side of a Fresh x TanStack split ------------------------------------
|
|
48
|
+
//
|
|
49
|
+
// `withABTesting` keeps the side in `_deco_bucket` as `<side>:<percent>` (`worker:50`), set at
|
|
50
|
+
// the edge before the document reaches the browser, so it too is on the first event. Recorded
|
|
51
|
+
// as the `storefront` experiment with the names the store Worker stamps on what it sends
|
|
52
|
+
// through `EdgeIngest` -- the two halves of the funnel only group together if they agree, and
|
|
53
|
+
// `STOREFRONT_EXP` is where they do. An unknown side is skipped rather than recorded raw: a
|
|
54
|
+
// third variant nobody emits at the edge would be a funnel with no ruler.
|
|
55
|
+
try {
|
|
56
|
+
const raw = document.cookie
|
|
57
|
+
.split(";")
|
|
58
|
+
.map((c) => c.trim())
|
|
59
|
+
.find((c) => c.startsWith(`${STOREFRONT_EXP.cookie}=`));
|
|
60
|
+
const side = raw
|
|
61
|
+
? decodeURIComponent(raw.slice(STOREFRONT_EXP.cookie.length + 1)).split(":")[0]
|
|
62
|
+
: "";
|
|
63
|
+
const variant = STOREFRONT_EXP.variants[side];
|
|
64
|
+
if (variant) setExperiment?.(STOREFRONT_EXP.name, variant);
|
|
65
|
+
} catch {
|
|
66
|
+
// Same as above: a bad cookie costs the arm, never the collection.
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// ---- events, from the bus the framework already has -------------------------
|
|
70
|
+
//
|
|
71
|
+
// deco dispatches commerce events in the Google Analytics shape. Mapped to our names
|
|
72
|
+
// rather than forwarded verbatim: `add_to_cart` here has a typed value column, and
|
|
73
|
+
// passing GA's nested `ecommerce.items` through as props would put money in a string.
|
|
74
|
+
const NAME_MAP: Record<string, string> = {
|
|
75
|
+
view_item: "view_item",
|
|
76
|
+
view_item_list: "view_item_list",
|
|
77
|
+
select_item: "select_item",
|
|
78
|
+
add_to_cart: "add_to_cart",
|
|
79
|
+
remove_from_cart: "remove_from_cart",
|
|
80
|
+
begin_checkout: "begin_checkout",
|
|
81
|
+
purchase: "purchase",
|
|
82
|
+
search: "$search",
|
|
83
|
+
view_promotion: "view_promotion",
|
|
84
|
+
select_promotion: "select_promotion",
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
/** A storefront can hand the bus its products in one of two shapes, and both are deco's.
|
|
88
|
+
*
|
|
89
|
+
* `items` is the GA4 shape `mapProductToAnalyticsItem` builds. `products` is the schema.org
|
|
90
|
+
* `Product` itself, which the `DECO` adapter of the Azzas tracking SDK expects and builds the
|
|
91
|
+
* GA4 payload from on its own -- the FARM sends every commerce event that way. Reading only
|
|
92
|
+
* `items` stored 94k `add_to_cart` from the FARM in five days with not one item id or value:
|
|
93
|
+
* the event names arrived, so every panel looked instrumented, and nothing said which product.
|
|
94
|
+
*
|
|
95
|
+
* The id follows `mapProductToAnalyticsItem`: `item_id` is `productID` (the SKU), so a site
|
|
96
|
+
* sending either shape lands the same id in `item_ids`. `sku` is the fallback because the
|
|
97
|
+
* lighter Product the FARM puts on shelf cards carries `sku` and no `productID`. */
|
|
98
|
+
const productId = (pr: any) => String(pr?.productID ?? pr?.sku ?? "");
|
|
99
|
+
|
|
100
|
+
/** Price of one unit off a schema.org `AggregateOffer`. `lowPrice` is the price the shopper
|
|
101
|
+
* sees; the first offer is the fallback for the trimmed Product on shelf cards. */
|
|
102
|
+
const unitPrice = (pr: any): number | undefined => {
|
|
103
|
+
const o = pr?.offers;
|
|
104
|
+
const v = o?.lowPrice ?? o?.offers?.[0]?.price;
|
|
105
|
+
return typeof v === "number" ? v : undefined;
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
/** Events where `value` means money that moved. A `view_item_list` of 40 cards has no value:
|
|
109
|
+
* summing the shelf would put a number in a revenue column that no shopper ever paid. */
|
|
110
|
+
const VALUED = new Set(["add_to_cart", "remove_from_cart", "begin_checkout", "purchase"]);
|
|
111
|
+
|
|
112
|
+
const money = (name: string, p: any) => {
|
|
113
|
+
const items = p?.items ?? p?.ecommerce?.items;
|
|
114
|
+
const products = Array.isArray(items) ? undefined : p?.products;
|
|
115
|
+
const out: Record<string, unknown> = {};
|
|
116
|
+
if (typeof p?.value === "number") out.value = p.value;
|
|
117
|
+
if (typeof p?.currency === "string") out.currency = p.currency;
|
|
118
|
+
if (Array.isArray(items)) {
|
|
119
|
+
out.items_count = items.length;
|
|
120
|
+
out.item_ids = items
|
|
121
|
+
.map((i: any) => String(i?.item_id ?? i?.id ?? ""))
|
|
122
|
+
.filter(Boolean)
|
|
123
|
+
.slice(0, LIMITS.itemIds);
|
|
124
|
+
} else if (Array.isArray(products)) {
|
|
125
|
+
out.items_count = products.length;
|
|
126
|
+
out.item_ids = products.map(productId).filter(Boolean).slice(0, LIMITS.itemIds);
|
|
127
|
+
// Only when the site did not say it, and only on events where a value is money.
|
|
128
|
+
if (out.value === undefined && VALUED.has(name)) {
|
|
129
|
+
let sum = 0;
|
|
130
|
+
let priced = 0;
|
|
131
|
+
for (const pr of products) {
|
|
132
|
+
const u = unitPrice(pr);
|
|
133
|
+
if (u === undefined) continue;
|
|
134
|
+
sum += u * (typeof pr?.quantity === "number" && pr.quantity > 0 ? pr.quantity : 1);
|
|
135
|
+
priced++;
|
|
136
|
+
}
|
|
137
|
+
// All or nothing: a cart of three with one unpriced item is not worth the two we
|
|
138
|
+
// could price, and a partial sum would look exactly like a real one.
|
|
139
|
+
if (priced && priced === products.length) out.value = Math.round(sum * 100) / 100;
|
|
140
|
+
}
|
|
141
|
+
const cur = products[0]?.offers?.priceCurrency;
|
|
142
|
+
if (out.currency === undefined && typeof cur === "string" && out.value !== undefined)
|
|
143
|
+
out.currency = cur;
|
|
144
|
+
}
|
|
145
|
+
if (typeof p?.transaction_id === "string") out.transaction_id = p.transaction_id;
|
|
146
|
+
return out;
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
/** Subscribe WHENEVER the bus shows up, not only if it is already there.
|
|
150
|
+
*
|
|
151
|
+
* This was `window?.DECO?.events?.subscribe?.(…)` — one attempt, optional-chained, no retry —
|
|
152
|
+
* and it lost every commerce event on a real site. React hoists `<script async>` into `<head>`
|
|
153
|
+
* regardless of where the component sits in the tree: measured on igor-tanstack.deco.site,
|
|
154
|
+
* our tag is at byte 200 and the inline block that defines `DECO.events` is at byte 1905, in
|
|
155
|
+
* the body. So this ran first, found nothing, and never tried again. Two `view_promotion`
|
|
156
|
+
* events fired and went nowhere, with no error and a page that looked perfectly instrumented.
|
|
157
|
+
*
|
|
158
|
+
* NOTHING IS LOST BY ARRIVING LATE, which is what makes polling the right answer rather than
|
|
159
|
+
* a patch: the bus keeps a `_q` and `subscribe` replays it to a new subscriber. So the only
|
|
160
|
+
* requirement is to subscribe eventually.
|
|
161
|
+
*
|
|
162
|
+
* Bounded at ten seconds. A page that has not defined the bus by then does not have one —
|
|
163
|
+
* a site without the deco runtime is a normal thing, and an interval left running forever
|
|
164
|
+
* would be this module's parting gift to every such page.
|
|
165
|
+
*/
|
|
166
|
+
const onBus = (fn: (event: any) => void) => {
|
|
167
|
+
const w = (globalThis as any).window;
|
|
168
|
+
const now = w?.DECO?.events;
|
|
169
|
+
if (typeof now?.subscribe === "function") {
|
|
170
|
+
now.subscribe(fn);
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
let tries = 0;
|
|
174
|
+
const iv = setInterval(() => {
|
|
175
|
+
const bus = (globalThis as any).window?.DECO?.events;
|
|
176
|
+
if (typeof bus?.subscribe === "function") {
|
|
177
|
+
clearInterval(iv);
|
|
178
|
+
bus.subscribe(fn);
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
if (++tries >= 100) clearInterval(iv);
|
|
182
|
+
}, 100);
|
|
183
|
+
};
|
|
184
|
+
|
|
185
|
+
onBus((event: any) => {
|
|
186
|
+
if (!event?.name) return;
|
|
187
|
+
|
|
188
|
+
// The bus replays a synthetic "deco" event on subscribe, carrying the same flags the
|
|
189
|
+
// cookie already gave us. Ignored rather than mapped: it is not something a visitor
|
|
190
|
+
// did, and turning it into an event would put a row in the table for every page load
|
|
191
|
+
// that means nothing.
|
|
192
|
+
if (event.name === "deco") return;
|
|
193
|
+
|
|
194
|
+
const mapped = NAME_MAP[event.name];
|
|
195
|
+
if (!mapped) return; // unknown bus events are not forwarded blind
|
|
196
|
+
|
|
197
|
+
const p = event.params ?? {};
|
|
198
|
+
const props: Props = {};
|
|
199
|
+
// The schema.org shape carries the list on the product, not on the event.
|
|
200
|
+
const list = p.item_list_name ?? p.products?.[0]?.item_list_name;
|
|
201
|
+
if (typeof list === "string") props.list = list.slice(0, 200);
|
|
202
|
+
if (typeof p.search_term === "string")
|
|
203
|
+
props.term = p.search_term.trim().toLowerCase().slice(0, 200);
|
|
204
|
+
|
|
205
|
+
enqueue(mapped, props, money(event.name, p));
|
|
206
|
+
});
|
|
207
|
+
});
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
/** Enhanced measurement: the four things every site wants counted and nobody wants to
|
|
2
|
+
* instrument by hand — how far people scroll, which links take them away, what they
|
|
3
|
+
* download, and what they search for.
|
|
4
|
+
*
|
|
5
|
+
* The reason this is a MODULE and not core: it is automatic, and automatic collection is
|
|
6
|
+
* where an analytics SDK gets expensive without anyone deciding to spend. A blog does not
|
|
7
|
+
* need outbound-click tracking and should not download the code for it.
|
|
8
|
+
*
|
|
9
|
+
* Every counter here is bounded on purpose. GA4 fires a scroll event at each of four
|
|
10
|
+
* thresholds, which is four events per page for one number; it sends an outbound event
|
|
11
|
+
* per click including the same link clicked twice; and none of it is capped. At 400M
|
|
12
|
+
* events a month those choices are the difference between a bill you planned and one you
|
|
13
|
+
* did not.
|
|
14
|
+
*/
|
|
15
|
+
import { LIMITS } from "../../shared/contract.ts";
|
|
16
|
+
|
|
17
|
+
window.__dqRegister?.((enqueue, _api: Record<string, unknown>, onFinal, onRoute) => {
|
|
18
|
+
// ---- scroll ---------------------------------------------------------------
|
|
19
|
+
// One event per page load carrying the DEEPEST point reached, not one per threshold
|
|
20
|
+
// crossed. Four events to communicate a single number is the shape GA4 chose, and the
|
|
21
|
+
// extra three carry no information the fourth does not.
|
|
22
|
+
let deepest = 0;
|
|
23
|
+
let scrollSent = false;
|
|
24
|
+
|
|
25
|
+
const depth = () => {
|
|
26
|
+
const doc = document.documentElement;
|
|
27
|
+
const viewport = window.innerHeight || doc.clientHeight || 0;
|
|
28
|
+
const total = Math.max(doc.scrollHeight, document.body?.scrollHeight ?? 0);
|
|
29
|
+
if (total <= viewport) return 100; // nothing to scroll: the page was fully seen
|
|
30
|
+
const seen = (window.scrollY || doc.scrollTop || 0) + viewport;
|
|
31
|
+
return Math.max(0, Math.min(100, Math.round((seen / total) * 100)));
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
// Passive: a scroll listener that can block scrolling is a listener that made the site
|
|
35
|
+
// worse to use, which is the one thing analytics must never do.
|
|
36
|
+
addEventListener(
|
|
37
|
+
"scroll",
|
|
38
|
+
() => {
|
|
39
|
+
const d = depth();
|
|
40
|
+
if (d > deepest) deepest = d;
|
|
41
|
+
},
|
|
42
|
+
{ passive: true },
|
|
43
|
+
);
|
|
44
|
+
|
|
45
|
+
// `prev` is set when an SPA route closes the view: the path it was measured on goes with it,
|
|
46
|
+
// and the live document is already the next route's, so only what was tracked counts.
|
|
47
|
+
function sendScroll(prev?: string) {
|
|
48
|
+
if (scrollSent) return;
|
|
49
|
+
const d = prev ? deepest : Math.max(deepest, depth());
|
|
50
|
+
// Rounded to a bucket. The difference between 61% and 62% is noise, and storing it
|
|
51
|
+
// raw would put a hundred distinct values into a LowCardinality dictionary for no
|
|
52
|
+
// question anyone asks.
|
|
53
|
+
const bucket = Math.min(100, Math.round(d / 25) * 25);
|
|
54
|
+
scrollSent = true;
|
|
55
|
+
enqueue("$scroll", { depth: String(bucket) }, prev ? { path: prev } : undefined);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// ---- outbound links and downloads -----------------------------------------
|
|
59
|
+
const DOWNLOAD_EXT =
|
|
60
|
+
/\.(pdf|zip|rar|7z|gz|tar|csv|xlsx?|docx?|pptx?|txt|dmg|exe|pkg|apk|mp3|mp4|mov|avi|wav)($|\?)/i;
|
|
61
|
+
|
|
62
|
+
// Same link clicked twice in one page load is one fact, not two. Rage-clicking a slow
|
|
63
|
+
// link is the common case and it is exactly the case that would inflate the number.
|
|
64
|
+
const clicked = new Set<string>();
|
|
65
|
+
const MAX_CLICKS = 20;
|
|
66
|
+
|
|
67
|
+
addEventListener(
|
|
68
|
+
"click",
|
|
69
|
+
(e) => {
|
|
70
|
+
const el = (e.target as Element | null)?.closest?.("a[href]") as HTMLAnchorElement | null;
|
|
71
|
+
if (!el) return;
|
|
72
|
+
|
|
73
|
+
const href = el.href;
|
|
74
|
+
if (!href || href.startsWith("javascript:")) return;
|
|
75
|
+
|
|
76
|
+
let url: URL;
|
|
77
|
+
try {
|
|
78
|
+
url = new URL(href, location.href);
|
|
79
|
+
} catch {
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") return;
|
|
83
|
+
|
|
84
|
+
if (clicked.size >= MAX_CLICKS || clicked.has(href)) return;
|
|
85
|
+
|
|
86
|
+
const isDownload =
|
|
87
|
+
el.hasAttribute("download") || DOWNLOAD_EXT.test(url.pathname + url.search);
|
|
88
|
+
const isOutbound = url.host !== location.host;
|
|
89
|
+
if (!isDownload && !isOutbound) return;
|
|
90
|
+
|
|
91
|
+
clicked.add(href);
|
|
92
|
+
// The URL is the whole point of the event, so it gets the path budget rather than the
|
|
93
|
+
// value budget — a truncated destination answers nothing.
|
|
94
|
+
const target = (url.host + url.pathname).slice(0, LIMITS.pathLen);
|
|
95
|
+
enqueue(isDownload ? "$download" : "$outbound", { target });
|
|
96
|
+
},
|
|
97
|
+
{ capture: true, passive: true },
|
|
98
|
+
);
|
|
99
|
+
|
|
100
|
+
// ---- site search ----------------------------------------------------------
|
|
101
|
+
// A closed list of parameter names, for the same reason the campaign vocabulary is
|
|
102
|
+
// closed: an open one lets any query string mint a dimension value. These are the ones
|
|
103
|
+
// that actually appear on storefronts.
|
|
104
|
+
const SEARCH_PARAMS = ["q", "s", "search", "query", "termo", "busca", "keyword"];
|
|
105
|
+
|
|
106
|
+
(function searchOnce() {
|
|
107
|
+
try {
|
|
108
|
+
const qs = new URLSearchParams(location.search);
|
|
109
|
+
for (const key of SEARCH_PARAMS) {
|
|
110
|
+
const term = qs.get(key);
|
|
111
|
+
if (!term) continue;
|
|
112
|
+
enqueue("$search", {
|
|
113
|
+
// Lowercased and trimmed so "Tenis", "tenis " and "tenis" are one term rather
|
|
114
|
+
// than three rows in a top-searches report.
|
|
115
|
+
term: term.trim().toLowerCase().slice(0, LIMITS.valueLen),
|
|
116
|
+
param: key,
|
|
117
|
+
});
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
} catch {
|
|
121
|
+
/* a malformed query string is not worth breaking collection over */
|
|
122
|
+
}
|
|
123
|
+
})();
|
|
124
|
+
|
|
125
|
+
// ---- flush ----------------------------------------------------------------
|
|
126
|
+
// Scroll depth is only known when the visitor leaves. Core runs this immediately
|
|
127
|
+
// before its own last flush, so the event rides out with everything else instead of
|
|
128
|
+
// buying a request of its own — three modules each flushing cost three requests for
|
|
129
|
+
// what is one visit's worth of data.
|
|
130
|
+
onFinal(() => sendScroll());
|
|
131
|
+
// One `$scroll` per VIEW. Before this, an SPA's route 2 inherited route 1's depth and the
|
|
132
|
+
// whole visit sent a single event at the end, attributed to whichever path was last. A
|
|
133
|
+
// query-string change on the same path is the same view, as it is for core's pageview.
|
|
134
|
+
onRoute?.((prev) => {
|
|
135
|
+
if (prev === location.pathname) return;
|
|
136
|
+
sendScroll(prev);
|
|
137
|
+
deepest = 0;
|
|
138
|
+
scrollSent = false;
|
|
139
|
+
});
|
|
140
|
+
});
|