@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,652 @@
1
+ /** The payload contract — one definition, imported by the runtime and by the Worker.
2
+ *
3
+ * It lived in two files with duplicated constants, which is the reliable way to end up
4
+ * with a client truncating at 200 and a server truncating at 250. The runtime applies
5
+ * these rules to save bandwidth; the Worker applies them because the endpoint is public
6
+ * and the client is by definition untrusted. Same rules, different reasons.
7
+ *
8
+ * Fields deliberately do NOT share one charset. Applying a single rule everywhere is the
9
+ * mistake: `plp-ranking` is a frozen experiment key owned by another team and contains a
10
+ * hyphen, and an order id from a customer's OMS is opaque and case-sensitive. Normalising
11
+ * those would break a join and an invoice respectively.
12
+ */
13
+ export const LIMITS = {
14
+ requestBytes: 64 * 1024,
15
+ // What the runtime puts in ONE request, under `requestBytes` with room for the envelope. Also
16
+ // under the browser's 64 KB keepalive/beacon quota, so a final flush is never refused whole.
17
+ batchBytes: 56 * 1024,
18
+ eventsPerBatch: 50,
19
+ eventBytes: 1024,
20
+ errorEventBytes: 8 * 1024,
21
+ // `$heatmap`: one event per page view carrying its clicks, scroll and attention. Measured
22
+ // ~450-500 B for a typical storefront view; the client sheds its newest clicks to stay
23
+ // under 3,800 B, so this is a ceiling the runtime never reaches on its own.
24
+ heatmapEventBytes: 4 * 1024,
25
+ hmClicks: 40, // click records per view (a rage burst is ONE record with a count)
26
+ hmRoots: 32, // root dictionary entries per view
27
+ hmBands: 40, // attention bands, 2.5% of the document each
28
+ hmRootLen: 120, // a root identity: manifest key + ordinal, or fs:<component>#n
29
+ queueMax: 200,
30
+ // GA4's limit. Anything valid there is valid here, so a migration does not hit a new
31
+ // ceiling on arrival.
32
+ nameLen: 40,
33
+ propKeys: 24, // GA4 allows 25
34
+ keyLen: 40,
35
+ valueLen: 200,
36
+ expEntries: 8,
37
+ expKeyLen: 60,
38
+ pathLen: 512,
39
+ refLen: 256,
40
+ itemIds: 20,
41
+ itemIdLen: 64,
42
+ transactionIdLen: 64, // order ids run longer than a prop key
43
+ flushMs: 10_000,
44
+ };
45
+ /** `_trunc` is `LowCardinality(String)`. A free-text flag would rebuild the cardinality
46
+ * problem inside the column that exists to detect it, so the vocabulary is closed —
47
+ * and small, which keeps its dictionary at a handful of entries for the whole fleet. */
48
+ /** Flags are namespaced by the field they concern. `value.type` was ambiguous: there is
49
+ * also a column called `value` holding money, so a reader could not tell whether the flag
50
+ * meant "a prop was the wrong type" or "the amount would not parse". Now `props.*` is
51
+ * about the props map and `amount.*` is about money.
52
+ *
53
+ * The four the client needs are exported individually as well as in the map below.
54
+ * esbuild cannot tree-shake a single property off an object it sees referenced, so
55
+ * `FLAGS.propsCount` drags all twenty-one strings into the browser bundle. Naming them
56
+ * separately keeps the client at the four it uses. */
57
+ export const F_PROPS_COUNT = "props.count";
58
+ export const F_PROPS_TYPE = "props.type";
59
+ export const F_PROPS_LEN = "props.len";
60
+ export const F_QUEUE_OVERFLOW = "queue.overflow";
61
+ /** More events arrived in one request than `eventsPerBatch` allows. The surplus is discarded
62
+ * and the survivors carry this, so the loss is visible in the warehouse rather than inferred
63
+ * from a gap — the same contract `queue.overflow` makes on the client. */
64
+ export const F_BATCH_OVERFLOW = "batch.overflow";
65
+ export const FLAGS = {
66
+ nameEmpty: "name.empty",
67
+ nameCharset: "name.charset",
68
+ nameLen: "name.len",
69
+ nameReserved: "name.reserved",
70
+ keyCharset: "key.charset",
71
+ keyLen: "key.len",
72
+ propsCount: F_PROPS_COUNT,
73
+ propsType: F_PROPS_TYPE,
74
+ propsLen: F_PROPS_LEN,
75
+ propsControl: "props.control",
76
+ expCount: "exp.count",
77
+ expCharset: "exp.charset",
78
+ currencyInvalid: "currency.invalid",
79
+ amountType: "amount.type",
80
+ pathLen: "path.len",
81
+ refLen: "referrer.len",
82
+ itemIdsCount: "item_ids.count",
83
+ tsSkew: "ts.skew",
84
+ queueOverflow: F_QUEUE_OVERFLOW,
85
+ eventSize: "event.size",
86
+ // The sender's id was absent or not a UUID, so the Worker minted one. Recorded rather
87
+ // than silent because it costs the event its only dedup key: `uniqExact(event_id)` can
88
+ // no longer collapse a retry of the same event, and a number that quietly counts a
89
+ // retry twice is worse than one that says why.
90
+ eventIdMinted: "event_id.minted",
91
+ // Tier 0 identity for this row was built from a DERIVED salt because the day's stored one was
92
+ // missing — a cron that did not run. Derived from YESTERDAY's random salt, not from any
93
+ // secret, so the day is recomputable only until that salt expires from KV (around 03:10 UTC
94
+ // the following day), and then by nobody. Recorded rather than silent: "which days were recomputable,
95
+ // and for how long" has to be answerable from the warehouse. Rows written before 2026-10-27
96
+ // carry the same flag for a salt derived from `SALT_SECRET`/`VISITOR_SECRET`.
97
+ saltDerived: "salt.derived",
98
+ // Neither today's nor yesterday's salt was in KV, so this isolate minted a random salt for
99
+ // the day and holds it only in memory. Unrecomputable by anyone, and that costs counting:
100
+ // a visitor whose requests reach two isolates is two visitor_ids that day. Recorded so a
101
+ // fragmented day's unique counts are known to be inflated rather than trusted.
102
+ saltEphemeral: "salt.ephemeral",
103
+ // A tier 1 site sent a consented client id and there was no VISITOR_SECRET to hash it with,
104
+ // so this row fell back to tier 0 identity. Recorded because the failure is otherwise
105
+ // INVISIBLE AND EXPENSIVE: the site keeps collecting, every number looks right, and the one
106
+ // thing consent was collected to enable -- following the same person across days -- silently
107
+ // does not happen. The remedy is a deploy, so it has to be findable in the warehouse.
108
+ consentNoSecret: "consent.no_secret",
109
+ // DEPRECATED, never stamped any more. It meant "`SALT_SECRET` is unset, so tier 0's fallback
110
+ // would derive from `VISITOR_SECRET`". Tier 0 no longer has a secret at all (#13), so the
111
+ // state it described cannot exist. Declared still because rows written before 2026-10-27
112
+ // carry it, and this is where the `_trunc` vocabulary is closed.
113
+ saltSecretUnsplit: "salt.unsplit",
114
+ originMismatch: "origin.mismatch",
115
+ // An event or a prop key the site never declared. Recorded, never rejected: a taxonomy
116
+ // that drops data punishes the analyst for the developer's mistake, and the whole
117
+ // point of a registry is to make drift VISIBLE, not to lose the drifted data.
118
+ nameUnregistered: "name.unregistered",
119
+ propsUnregistered: "props.unregistered",
120
+ // The only two flags no collected event ever carries: they are written by `ops/backfill.mjs`
121
+ // on rows imported from the vendor we are replacing, and the Worker never sets them.
122
+ //
123
+ // They live here anyway, because this is where the `_trunc` vocabulary is CLOSED. A value in
124
+ // that column that is not declared here is off-contract, and the reason the vocabulary is
125
+ // closed at all -- keeping a LowCardinality dictionary at a handful of entries -- does not
126
+ // care which process wrote the row.
127
+ //
128
+ // `import.vendor` is provenance. `site_id_source = 'import'` already says a row was not
129
+ // collected; it does not say by whom, and the day a second vendor or a customer CSV arrives,
130
+ // "not host and not tag" identifies nothing.
131
+ //
132
+ // `import.day_grain` is a warning about the row's TIME. The vendor cannot report hours --
133
+ // `time:hour` collapses to a single bucket on their side -- so every imported event of a day
134
+ // sits at 00:00 of that day, and any hourly panel over an imported window is a midnight spike
135
+ // and nothing else. We do not synthesise a diurnal curve to make that chart look reasonable:
136
+ // an invented shape is worse than an absent one, because only the absent one is discoverable.
137
+ // This flag is how it is discovered.
138
+ //
139
+ // NEITHER IS A TRUST BOUNDARY. `flagSink` carries a payload's prior `_trunc` through without
140
+ // checking it against this list, so any browser can post either string -- as it already could
141
+ // before they were named here. The mark billing reads is `site_id_source`, which the Worker
142
+ // resolves and the payload cannot influence. These two are for a human reading a row.
143
+ // `$heatmap` only. `hm.len`: an array or a value was capped to its LIMITS bound. `hm.shape`:
144
+ // something was the wrong type or out of range and was DROPPED -- a click with no valid anchor
145
+ // hash, a section index pointing nowhere, a missing view id. Two flags rather than one per
146
+ // field, for the reason the vocabulary is closed at all.
147
+ hmLen: "hm.len",
148
+ hmShape: "hm.shape",
149
+ // `edge_events` only. The store's Worker called `EdgeIngest.write` without a bot score, so the
150
+ // row carries 99, the same "unknown, keep it" default a request without `cf.botManagement`
151
+ // gets on `workers.dev`. Marked because an RPC call carries no `request.cf` of its own: the
152
+ // score exists only if the caller forwarded it, and a funnel with bots quietly left in has to
153
+ // be findable.
154
+ edgeNoBotScore: "edge.no_bot_score",
155
+ importVendor: "import.vendor",
156
+ importDayGrain: "import.day_grain",
157
+ };
158
+ /** Platform events. Anything else arriving with a `$` is a site reaching into a namespace
159
+ * that is not its own: the prefix is stripped and the attempt recorded. */
160
+ /** Platform events. Anything else arriving with a `$` is a site reaching into a namespace
161
+ * that is not its own: the prefix is stripped and the attempt recorded.
162
+ *
163
+ * The engagement four are reserved for the same reason as the rest — they are generated
164
+ * by our module, not by the site, so a registry must not ask a site to declare them and
165
+ * a site must not be able to forge them. */
166
+ export const RESERVED_NAMES = [
167
+ "$pageview",
168
+ "$error",
169
+ "$vitals",
170
+ "$exposure",
171
+ "$scroll",
172
+ "$outbound",
173
+ "$download",
174
+ "$search",
175
+ // One per sampled page view, from the heatmap module. Reserved for the same two reasons as
176
+ // the engagement four, and the second matters more here: sampling is decided per VIEW by the
177
+ // module (`heatmapRate`), so the per-event valve must never touch it.
178
+ "$heatmap",
179
+ ];
180
+ /** Whether the sampling valve is allowed to drop this event.
181
+ *
182
+ * Sampling used to apply to EVERYTHING, `$pageview` included, and that is not what anyone
183
+ * else does: GA4 samples in the REPORT when a query exceeds its quota, never at
184
+ * collection, and Plausible does not sample at all. Dropping pageviews also produced the
185
+ * worst possible arithmetic — a visitor with k events survives a rate r with probability
186
+ * 1-(1-r)^k, so a nominal 10% sample kept ~50% of visitors while keeping exactly 10% of
187
+ * events, a five-fold overcount of uniques.
188
+ *
189
+ * The collector's own `$` events are exempt, and that dissolves the problem rather than
190
+ * mitigating it: every visit carries a `$pageview`, so if pageviews never drop then
191
+ * visitor counts are exact at any rate. They are also bounded per pageview by
192
+ * construction — one pageview, one vitals, one scroll, errors already collapsed into
193
+ * `error_count` — so exempting them sheds almost no volume.
194
+ *
195
+ * What floods a site is custom events: `track()` in a render loop is the emergency this
196
+ * valve exists for, and it is the only thing the valve now touches. */
197
+ export function isSampleable(name) {
198
+ return !name.startsWith("$");
199
+ }
200
+ /** What the store's own Worker may write through `EdgeIngest`, and the props each one carries.
201
+ *
202
+ * A CLOSED vocabulary, unlike the tag's. The edge is ours: these are the requests a store
203
+ * Worker sees on both sides of a Fresh x TanStack split, emitted by one wrapper rather than by
204
+ * each site's code, and that sameness is the whole reason they can be a ruler for an A/B test
205
+ * between two codebases. A name outside this list is refused and counted; a prop outside it is
206
+ * kept and flagged `props.unregistered`, like the site registry does.
207
+ *
208
+ * They land in `edge_events`, never in `raw_events` (D20), so no panel, rollup or session
209
+ * built on the tag ever counts a checkout API call as a page view. */
210
+ export const EDGE_EVENTS = {
211
+ /** One per HTML document, on both sides of the split. `og` is the orderGroup on the order
212
+ * confirmation (`/checkout/orderPlaced?og=`): it links a VTEX order to the visit that saw it.
213
+ * `sc` is the sales channel of the request; `cart` the hashed orderForm on checkout documents. */
214
+ $edge_page: ["page", "status", "prefetch", "cache", "ttfb_ms", "og", "sc", "cart", "fetch_site"],
215
+ /** One per call to the VTEX checkout API. `step` includes `gatewayCallback`. The cart shape
216
+ * (`qty` .. `items_value`, `payment`, `coupon`) is read from the orderForm that `shippingData`
217
+ * and `paymentData` return; `error` is the VTEX code and message on a status >= 400. */
218
+ checkout_step: [
219
+ "step",
220
+ "status",
221
+ "cart",
222
+ "payment",
223
+ "coupon",
224
+ "shipping_paid",
225
+ "items",
226
+ "referer",
227
+ "error",
228
+ "ms",
229
+ "from_checkout",
230
+ "qty",
231
+ "lines",
232
+ "sellers",
233
+ "packages",
234
+ "shipping",
235
+ "items_value",
236
+ ],
237
+ /** One per call that changes the cart outside the checkout: `add`, `remove`, `update`,
238
+ * `coupon`, `simulate`. The route differs per side (v7's invoke route on Fresh, the TanStack
239
+ * invoke route), and the store Worker maps both to this. */
240
+ cart_action: ["action", "status", "cart", "items"],
241
+ /** What the shopper is paying and why, beside `checkout_step` on `shippingData` and
242
+ * `paymentData`: discounts, promotions, the orderForm's messages, unavailable items, gifts,
243
+ * who VTEX thinks the shopper is, and what the payment POST asked for. */
244
+ checkout_summary: [
245
+ "step",
246
+ "status",
247
+ "cart",
248
+ "value",
249
+ "items_value",
250
+ "discounts",
251
+ "shipping",
252
+ "qty",
253
+ "lines",
254
+ "promos",
255
+ "promo_hash",
256
+ "promo_names",
257
+ "messages",
258
+ "message_count",
259
+ "unavailable",
260
+ "selectable_gifts",
261
+ "gift_items",
262
+ "priced_items",
263
+ "utm_source",
264
+ "coupon",
265
+ "tags",
266
+ "channels",
267
+ "pay_systems",
268
+ "installments",
269
+ "pay_value",
270
+ "logged_in",
271
+ "can_edit",
272
+ "email",
273
+ "profile_id",
274
+ "saved_cards",
275
+ "saved_addresses",
276
+ "cookies",
277
+ ],
278
+ /** The checkout page's own beacon, forwarded by the store Worker: JS errors, the step the
279
+ * shopper is on, the click on "place order" (`kind = buy`) and what followed it, the messages
280
+ * on screen, the exit. `kind` is the beacon's, `msg`/`aux`/`n` its three fields. */
281
+ checkout_js: ["kind", "msg", "aux", "n", "cart"],
282
+ };
283
+ /** Props per edge event. Above the tag's `propKeys` because the vocabulary is closed and ours:
284
+ * `checkout_summary` carries 32 fields, and packing them into fewer keys would trade a query on
285
+ * a column for a parse of a string. */
286
+ export const EDGE_PROP_KEYS = 40;
287
+ /** Size budget per edge event, for the same reason: the tag's 1 KB is a budget for a visitor's
288
+ * upload on mobile data, and an edge event never travels over one. */
289
+ export const EDGE_EVENT_BYTES = 4096;
290
+ export const EDGE_EVENT_NAMES = Object.keys(EDGE_EVENTS);
291
+ /** The side of a Fresh x TanStack split, as an experiment.
292
+ *
293
+ * `withABTesting` (decocms/blocks, compat-v7) keeps the side in the `_deco_bucket` cookie as
294
+ * `<side>:<percent>`. The runtime's deco adapter reads it into `exp`, and the store Worker
295
+ * stamps the same pair on what it sends through `EdgeIngest`, so both halves of the funnel
296
+ * group by one experiment with one pair of variant names. Changing a value here without
297
+ * changing the store side splits the funnel in two. */
298
+ export const STOREFRONT_EXP = {
299
+ cookie: "_deco_bucket",
300
+ name: "storefront",
301
+ variants: { worker: "tanstack", fallback: "fresh" },
302
+ };
303
+ /** The campaign parameters worth a typed column, and nothing else. `utm` is a Map with
304
+ * LowCardinality keys: an open vocabulary is exactly how that becomes a cardinality
305
+ * problem, since anything appending `utm_<random>` to a URL would mint a key forever.
306
+ * The five UTM parameters are the standard set; `gclid` and `fbclid` are here because
307
+ * they are what actually arrives from paid traffic and are otherwise lost. */
308
+ export const CAMPAIGN_KEYS = [
309
+ "utm_source",
310
+ "utm_medium",
311
+ "utm_campaign",
312
+ "utm_term",
313
+ "utm_content",
314
+ "gclid",
315
+ "fbclid",
316
+ ];
317
+ /** Strip the `utm_` prefix on the way in: the column is already called `utm`, so storing
318
+ * `utm_source` spends five characters per row per key restating it. */
319
+ export const campaignKey = (raw) => {
320
+ const k = raw.trim().toLowerCase();
321
+ // Accepts BOTH the raw form and the already-stripped one, because this runs twice:
322
+ // once in the browser reading the query string, and again in the Worker over whatever
323
+ // arrived. Accepting only `utm_source` meant the Worker dropped everything the runtime
324
+ // had correctly shortened to `source`, and only `gclid` survived — it has no prefix to
325
+ // strip. The endpoint is public anyway, so it has to handle either shape regardless of
326
+ // what our own runtime happens to send.
327
+ if (CAMPAIGN_KEYS.includes(k)) {
328
+ return k.startsWith("utm_") ? k.slice(4) : k;
329
+ }
330
+ return CAMPAIGN_KEYS.includes("utm_" + k) ? k : null;
331
+ };
332
+ /** Short keys on the wire, full names in the column. At 452M events a month, field names
333
+ * are a double-digit percentage of a 293-byte event — and the browser pays that upload on
334
+ * mobile data. Plausible does the same for the same reason. The Worker expands them, so
335
+ * nothing downstream ever sees the abbreviation. */
336
+ /** What a minted self-serve key looks like: a prefix and 22 URL-safe characters, the same
337
+ * shape the visitor hash uses.
338
+ *
339
+ * It lives in the CONTRACT rather than in the Worker's config module because it is one:
340
+ * whoever mints keys and whoever reads them have to agree, and those will not be the same
341
+ * codebase (D9). Deliberately NOT a secret — Plausible puts the equivalent in the script's
342
+ * filename, OneDollarStats uses the hostname itself, and a public identifier is the only
343
+ * thing a browser tag can carry. That is exactly why a key-sourced site is recorded as
344
+ * `tag` and never billed from. Checking the shape is a BOUND, not authentication: without
345
+ * it, any string of any length from any visitor becomes a KV read we pay for. */
346
+ export const KEY_SHAPE = /^dq_[A-Za-z0-9_-]{22}$/;
347
+ export const WIRE = {
348
+ event_id: "i",
349
+ /** A stable per-browser identifier, present ONLY on a tier-1 site whose visitor has
350
+ * granted consent. Absent otherwise, which is the whole point: at tier 0 there is
351
+ * nothing to send, and the Worker derives identity from a salt it rotates and forgets
352
+ * daily. Never stored as sent — the Worker hashes it with the site so the same browser
353
+ * is a different identifier on every customer's site. */
354
+ client_id: "ci",
355
+ ts: "t",
356
+ name: "n",
357
+ path: "p",
358
+ referrer: "r",
359
+ exp: "x",
360
+ props: "d",
361
+ value: "v",
362
+ currency: "c",
363
+ items_count: "q",
364
+ item_ids: "s",
365
+ transaction_id: "o",
366
+ error_type: "et",
367
+ error_message: "em",
368
+ error_file: "ef",
369
+ error_line: "el",
370
+ error_stack: "es",
371
+ error_fingerprint: "eg",
372
+ error_count: "ec",
373
+ utm: "u",
374
+ // Core Web Vitals go in typed columns rather than props: they are numbers that get
375
+ // averaged, bucketed and compared against thresholds, and a Map value would have to be
376
+ // parsed on every read. Nullable, because a metric that never fired must be absent
377
+ // rather than zero — a page nobody interacted with has no INP, and recording 0 would
378
+ // put it in the "good" bucket.
379
+ vital_lcp: "vl",
380
+ vital_inp: "vi",
381
+ vital_cls: "vc",
382
+ vital_ttfb: "vt",
383
+ vital_fcp: "vf",
384
+ // The heatmap module's per-view object. Expanded by the Worker into typed `hm_*` columns,
385
+ // never stored as sent. Shape in docs/PAYLOAD_CONTRACT.md.
386
+ heatmap: "hm",
387
+ _trunc: "_",
388
+ };
389
+ const KEY_OK = /^[a-z][a-z0-9_]*$/;
390
+ const EXP_OK = /^[a-z0-9][a-z0-9_-]*$/; // hyphens: `plp-ranking`, `model-b`
391
+ const CONTROL = /[\x00-\x1F\x7F]/g;
392
+ const ISO4217 = /^[A-Z]{3}$/;
393
+ /** snake_case, letter-initial, no spaces. The name becomes a panel label and a grouping
394
+ * key, so case and punctuation fragment one event across variants of itself — and a
395
+ * fragmented name also inflates the `LowCardinality` dictionary it lives in.
396
+ *
397
+ * Normalising is right. Doing it silently is not: two names collapsing into one is
398
+ * something the sender has to be able to see. */
399
+ export function normalizeName(input, flag, reserved = RESERVED_NAMES) {
400
+ const raw = String(input ?? "").trim();
401
+ if (!raw) {
402
+ flag(FLAGS.nameEmpty);
403
+ return "unnamed";
404
+ }
405
+ if (raw.startsWith("$")) {
406
+ if (reserved.includes(raw))
407
+ return raw;
408
+ flag(FLAGS.nameReserved);
409
+ return normalizeName(raw.slice(1), flag, reserved);
410
+ }
411
+ let n = raw
412
+ .toLowerCase()
413
+ .replace(/[^a-z0-9_]/g, "_")
414
+ .replace(/_{2,}/g, "_")
415
+ .replace(/^_+|_+$/g, "");
416
+ if (!n) {
417
+ flag(FLAGS.nameEmpty);
418
+ return "unnamed";
419
+ }
420
+ if (!/^[a-z]/.test(n))
421
+ n = "e_" + n;
422
+ if (n !== raw)
423
+ flag(FLAGS.nameCharset);
424
+ if (n.length > LIMITS.nameLen) {
425
+ n = n.slice(0, LIMITS.nameLen).replace(/_+$/, "");
426
+ flag(FLAGS.nameLen);
427
+ }
428
+ return n;
429
+ }
430
+ function normalizeKey(input, flag) {
431
+ let k = input
432
+ .toLowerCase()
433
+ .replace(/[^a-z0-9_]/g, "_")
434
+ .replace(/_{2,}/g, "_")
435
+ .replace(/^_+|_+$/g, "");
436
+ if (!k)
437
+ return null;
438
+ if (!/^[a-z]/.test(k))
439
+ k = "p_" + k;
440
+ if (k !== input)
441
+ flag(FLAGS.keyCharset);
442
+ if (k.length > LIMITS.keyLen) {
443
+ k = k.slice(0, LIMITS.keyLen).replace(/_+$/, "");
444
+ flag(FLAGS.keyLen);
445
+ }
446
+ return KEY_OK.test(k) ? k : null;
447
+ }
448
+ /** Control characters are replaced rather than truncated around: a newline inside a value
449
+ * breaks line-oriented reads of the same data downstream, and a tab breaks TSV. */
450
+ export function normalizeProps(input, flag, maxKeys = LIMITS.propKeys) {
451
+ const out = {};
452
+ if (!input || typeof input !== "object" || Array.isArray(input))
453
+ return out;
454
+ let n = 0;
455
+ for (const [rawKey, rawValue] of Object.entries(input)) {
456
+ if (n >= maxKeys) {
457
+ flag(FLAGS.propsCount);
458
+ break;
459
+ }
460
+ if (rawValue === null || rawValue === undefined)
461
+ continue;
462
+ const t = typeof rawValue;
463
+ if (t !== "string" && t !== "number" && t !== "boolean") {
464
+ flag(FLAGS.propsType);
465
+ continue;
466
+ }
467
+ const key = normalizeKey(rawKey, flag);
468
+ if (!key) {
469
+ flag(FLAGS.keyCharset);
470
+ continue;
471
+ }
472
+ let v = String(rawValue);
473
+ const stripped = v.replace(CONTROL, " ");
474
+ if (stripped !== v) {
475
+ v = stripped;
476
+ flag(FLAGS.propsControl);
477
+ }
478
+ if (v.length > LIMITS.valueLen) {
479
+ v = v.slice(0, LIMITS.valueLen);
480
+ flag(FLAGS.propsLen);
481
+ }
482
+ out[key] = v;
483
+ n++;
484
+ }
485
+ return out;
486
+ }
487
+ /** Case and hyphens preserved: these keys are a frozen contract owned elsewhere, and
488
+ * rewriting `plp-ranking` into `plp_ranking` would silently break the join they exist
489
+ * for. Invalid keys are dropped rather than coerced, for the same reason. */
490
+ export function normalizeExp(input, flag) {
491
+ const out = {};
492
+ if (!input || typeof input !== "object" || Array.isArray(input))
493
+ return out;
494
+ let n = 0;
495
+ for (const [k, v] of Object.entries(input)) {
496
+ if (n >= LIMITS.expEntries) {
497
+ flag(FLAGS.expCount);
498
+ break;
499
+ }
500
+ const key = String(k).slice(0, LIMITS.expKeyLen);
501
+ const val = String(v ?? "").slice(0, LIMITS.expKeyLen);
502
+ if (!EXP_OK.test(key) || !EXP_OK.test(val)) {
503
+ flag(FLAGS.expCharset);
504
+ continue;
505
+ }
506
+ out[key] = val;
507
+ n++;
508
+ }
509
+ return out;
510
+ }
511
+ /** ISO 4217, three letters. Anything else is emptied and flagged: a half-valid currency on
512
+ * a revenue row is worse than a missing one. */
513
+ export function normalizeCurrency(input, flag) {
514
+ const c = String(input ?? "")
515
+ .trim()
516
+ .toUpperCase();
517
+ if (!c)
518
+ return "";
519
+ if (!ISO4217.test(c)) {
520
+ flag(FLAGS.currencyInvalid);
521
+ return "";
522
+ }
523
+ return c;
524
+ }
525
+ /** Unparseable becomes null and is flagged, never coerced to zero. A silent zero in a
526
+ * revenue report is a wrong number; a null is a missing one, and only one of those gets
527
+ * noticed. */
528
+ export function normalizeAmount(input, flag) {
529
+ if (input === null || input === undefined || input === "")
530
+ return null;
531
+ const n = Number(input);
532
+ if (!Number.isFinite(n)) {
533
+ flag(FLAGS.amountType);
534
+ return null;
535
+ }
536
+ return n;
537
+ }
538
+ /** Opaque and case-sensitive: it comes from the customer's order system, and it is what
539
+ * stops a reloaded confirmation page counting a sale twice. Only control bytes go. */
540
+ /** Canonical UUID form, which is what the `event_id` column accepts. Not a version check:
541
+ * a v4 from the runtime, a v7 from a server-side sender and a caller's own id are all
542
+ * fine, and refusing one of them would be inventing a contract nobody agreed to. */
543
+ const UUID_SHAPE = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
544
+ /** An id that ClickHouse will accept, minted when the sender did not supply a usable one.
545
+ *
546
+ * This closes a hole that cost whole batches. `event_id` is a `UUID` column, and an absent
547
+ * id normalised to `""` -- which fails to parse, and a JSONEachRow INSERT fails as ONE
548
+ * statement. So a single event without an id destroyed every event in the same request,
549
+ * the sender got its 204, and the only trace was `events_lost`. Measured: one event with
550
+ * no `i` field, ClickHouse code 27, `inserted: 0`, `eventsLost: 1`.
551
+ *
552
+ * Our own runtime always sends one, which is exactly why this went unnoticed -- but the
553
+ * endpoint is public, and a server-side sender or a third-party SDK writing the lean
554
+ * version of our contract is not a hypothetical. `sanitize.ts` promises never to "reject a
555
+ * batch because one event is bad", and this is the one place it silently did. */
556
+ export function normalizeEventId(input, flag) {
557
+ const v = normalizeOpaque(input, 36);
558
+ if (UUID_SHAPE.test(v))
559
+ return v;
560
+ flag(FLAGS.eventIdMinted);
561
+ return crypto.randomUUID();
562
+ }
563
+ export function normalizeOpaque(input, max) {
564
+ return String(input ?? "")
565
+ .replace(CONTROL, "")
566
+ .slice(0, max);
567
+ }
568
+ export function normalizeItemIds(input, flag) {
569
+ if (!Array.isArray(input))
570
+ return [];
571
+ if (input.length > LIMITS.itemIds)
572
+ flag(FLAGS.itemIdsCount);
573
+ return input
574
+ .slice(0, LIMITS.itemIds)
575
+ .map((v) => normalizeOpaque(v, LIMITS.itemIdLen))
576
+ .filter(Boolean);
577
+ }
578
+ /** ClickHouse `DateTime64` in JSONEachRow wants `YYYY-MM-DD hh:mm:ss.mmm` — a `T` or a `Z`
579
+ * is a parse error, and a parse error rejects the whole batch rather than the row.
580
+ * Client clocks are wrong often enough that anything more than a day out is treated as
581
+ * skew and replaced, so one bad clock cannot poison a partition. */
582
+ /** The window is ASYMMETRIC, and that is the whole point.
583
+ *
584
+ * A timestamp in the past is ordinary: a beacon queued while the visitor was offline, a
585
+ * tab restored hours later, a phone that reconnects on the train. Up to a day of that is
586
+ * legitimate and gets kept.
587
+ *
588
+ * A timestamp in the FUTURE never is. An event cannot be received before it happened, so
589
+ * a future ts is always a wrong client clock — and browser clocks are wrong constantly.
590
+ * Accepting them symmetrically, as this did, means a visitor whose clock is twenty
591
+ * minutes fast pins their events to the top of the realtime feed and inflates "visitors
592
+ * now" until the world catches up. One skewed device could make the live view useless.
593
+ *
594
+ * Sixty seconds of forward tolerance covers ordinary jitter between the client's clock
595
+ * and ours; past that the event is stamped with receipt time and flagged, because the
596
+ * ORDER of a visitor's events is still worth preserving even when their clock is not.
597
+ */
598
+ const PAST_TOLERANCE_MS = 86_400_000; // a day
599
+ const FUTURE_TOLERANCE_MS = 60_000; // clock jitter, nothing more
600
+ export function normalizeTs(input, flag) {
601
+ const now = Date.now();
602
+ const t = Date.parse(String(input ?? ""));
603
+ if (!Number.isFinite(t) || now - t > PAST_TOLERANCE_MS || t - now > FUTURE_TOLERANCE_MS) {
604
+ flag(FLAGS.tsSkew);
605
+ return new Date(now).toISOString().replace("T", " ").replace("Z", "");
606
+ }
607
+ return new Date(t).toISOString().replace("T", " ").replace("Z", "");
608
+ }
609
+ /** Deduped and sorted, so two events that hit the same limits produce a byte-identical
610
+ * array — which is what lets the column compress instead of merely storing. */
611
+ export function flagSink(initial = []) {
612
+ const set = new Set(initial);
613
+ return {
614
+ flag: ((f) => {
615
+ set.add(f);
616
+ }),
617
+ list: () => [...set].sort(),
618
+ };
619
+ }
620
+ /** The config fields the SERVED BUNDLE is built from — and nothing else.
621
+ *
622
+ * Purging on every config write would throw away the fleet's cache for changes that do not move
623
+ * a single byte of the script. `domains` is only ever read server-side, to cross-check an Origin
624
+ * against a declared key; `schema` drives validation in the Worker; `goals` belongs to the read
625
+ * side. None of them reach the browser.
626
+ *
627
+ * Kept here, next to the wire contract, because it is exactly that: a promise about what the
628
+ * bundle depends on. When `serveScript` starts reading another field, it goes in this list, and
629
+ * the test that compares the two catches it if it does not. */
630
+ export const BUNDLE_FIELDS = [
631
+ "id",
632
+ "sampling",
633
+ "tier",
634
+ "hash",
635
+ "modules",
636
+ "heatmapRate",
637
+ "errorHosts",
638
+ ];
639
+ /** A stable fingerprint of just those fields, for deciding whether a write needs a purge.
640
+ * Key order is fixed rather than whatever `JSON.stringify` produces from an object literal,
641
+ * since two configs equal in content must not differ here by the order someone typed them. */
642
+ export function bundleFingerprint(cfg) {
643
+ if (!cfg)
644
+ return "";
645
+ return JSON.stringify(BUNDLE_FIELDS.map((f) => {
646
+ const v = cfg[f];
647
+ // Module ORDER does not change the bundle -- they are concatenated from a fixed map -- so
648
+ // a reorder must not look like a change.
649
+ return Array.isArray(v) ? [...v].map(String).sort() : (v ?? null);
650
+ }));
651
+ }
652
+ //# sourceMappingURL=contract.js.map