@asstio-dev/storefront 0.54.0 → 0.55.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.
@@ -0,0 +1,466 @@
1
+ /**
2
+ * The attribution codec (order-attribution spec §4.3, §6.1, §6.3): a port of the storefront's
3
+ * `Storefront.Domain/Attribution` (stage B, the touch rules) plus stage A (URL extraction, SDK-only) and the
4
+ * `__Host-sf_attr` cookie value. Pure: no DOM, no Node, no I/O. The shared vectors are
5
+ * `docs/contracts/attribution/attribution-normalise-vectors.json`; every function here is total (never throws).
6
+ */
7
+ /** The closed click-id list in stage A's precedence order (also the allowed `clickIdKind` values, D20). */
8
+ const CLICK_ID_KINDS = ["gclid", "gbraid", "wbraid", "msclkid", "fbclid", "ttclid"];
9
+ /** Exact hosts of each payment provider's checkout and return flow (rule 6′); the union of `attribution-provider-hosts-v1.json`. */
10
+ export const PROVIDER_HOSTS = [
11
+ "js.live.kustom.co",
12
+ "js.playground.kustom.co",
13
+ "checkout.qliro.com",
14
+ "checkout.staging.qliro.com",
15
+ ];
16
+ export const MAX_TOUCHES = 5;
17
+ export const MAX_ATTR_COOKIE_LENGTH = 2000;
18
+ const MAX_HOST_LENGTH = 253;
19
+ const MINUTE_MS = 60_000;
20
+ const DAY_MS = 24 * 3600 * 1000;
21
+ const FUTURE_TOLERANCE_MS = 5 * MINUTE_MS;
22
+ const FIELDS = ["source", "medium", "campaign", "content", "term", "referrerHost", "landingPath", "clickIdKind"];
23
+ // ---------------------------------------------------------------------------------------------------------------------
24
+ // Stage B, rules 1–9 (per string)
25
+ const CAPS = { source: 64, medium: 32, campaign: 128, content: 128, term: 64, landingPath: 200 };
26
+ const LOWER_FIELDS = new Set(["source", "medium", "referrerHost", "clickIdKind"]);
27
+ const FORMAT_CHAR = /^\p{Cf}$/u;
28
+ const LDH_HOST = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/;
29
+ const WHITESPACE = /\s/;
30
+ function isStripped(cp, ch) {
31
+ return cp <= 0x1f || (cp >= 0x7f && cp <= 0x9f) || cp === 0x2028 || cp === 0x2029 || (cp >= 0xd800 && cp <= 0xdfff) || FORMAT_CHAR.test(ch);
32
+ }
33
+ /** Per-code-point lower-casing: the result counts only when it is one code point; U+0130 → `i` by hand (§4.3 step 2). */
34
+ function lowerCodePoint(ch) {
35
+ if (ch === "İ")
36
+ return "i";
37
+ const lower = ch.toLowerCase();
38
+ return lower !== ch && [...lower].length === 1 ? lower : ch;
39
+ }
40
+ /** The 17 Unicode space separators (category Zs). */
41
+ function isSpaceSeparator(c) {
42
+ return c === " " || c === " " || c === " " || (c >= " " && c <= " ") || c === " " || c === " " || c === " ";
43
+ }
44
+ function collapseSpaces(s) {
45
+ let out = "";
46
+ let pending = false;
47
+ for (const c of s) {
48
+ if (isSpaceSeparator(c)) {
49
+ pending = true;
50
+ continue;
51
+ }
52
+ if (pending && out.length > 0)
53
+ out += " ";
54
+ pending = false;
55
+ out += c;
56
+ }
57
+ return out;
58
+ }
59
+ function isLegal(c) {
60
+ return c !== "@" && c !== "/" && !WHITESPACE.test(c);
61
+ }
62
+ /**
63
+ * Rule 6's pattern `[^\s@/]+@[^\s@/]+\.[^\s@/]{2,}` as an unanchored search, written as a linear scan (a backtracking regex
64
+ * is quadratic on hostile input; the C# side uses a non-backtracking engine).
65
+ */
66
+ function looksLikeEmail(s) {
67
+ for (let at = s.indexOf("@"); at >= 0; at = s.indexOf("@", at + 1)) {
68
+ if (at === 0 || !isLegal(s[at - 1]))
69
+ continue;
70
+ let end = at + 1;
71
+ while (end < s.length && isLegal(s[end]))
72
+ end++;
73
+ // a '.' at k with k >= at + 2 and two more legal characters after it inside the segment
74
+ for (let k = at + 2; k + 2 < end; k++)
75
+ if (s[k] === ".")
76
+ return true;
77
+ }
78
+ return false;
79
+ }
80
+ function takeCodePoints(s, max) {
81
+ let i = 0;
82
+ for (let n = 0; n < max && i < s.length; n++)
83
+ i += s.codePointAt(i) > 0xffff ? 2 : 1;
84
+ return s.slice(0, i);
85
+ }
86
+ function trimEndSpace(s) {
87
+ let end = s.length;
88
+ while (end > 0 && s[end - 1] === " ")
89
+ end--;
90
+ return s.slice(0, end);
91
+ }
92
+ /** Stage B rules 1–9 for one string of `field`; `piiNulled` is true when rule 6 is what nulled it. Null in, null out. */
93
+ function normalise(field, raw) {
94
+ if (typeof raw !== "string" || raw.length === 0)
95
+ return { value: null, piiNulled: false };
96
+ const lower = LOWER_FIELDS.has(field);
97
+ // 1. strip (lone surrogates included), 2. lower-case per code point.
98
+ let s = "";
99
+ for (const ch of raw) {
100
+ const cp = ch.codePointAt(0);
101
+ if (isStripped(cp, ch))
102
+ continue;
103
+ s += lower ? lowerCodePoint(ch) : ch;
104
+ }
105
+ // 3. NFC. 4. collapse spaces, trim. 5. empty → null.
106
+ s = collapseSpaces(s.normalize("NFC"));
107
+ if (s.length === 0)
108
+ return { value: null, piiNulled: false };
109
+ // 6. PII guard.
110
+ if (looksLikeEmail(s) || s.includes("%40"))
111
+ return { value: null, piiNulled: true };
112
+ // 7. caps in code points. 8. trim the end again; empty → null.
113
+ const cap = CAPS[field];
114
+ if (cap !== undefined)
115
+ s = takeCodePoints(s, cap);
116
+ s = trimEndSpace(s);
117
+ if (s.length === 0)
118
+ return { value: null, piiNulled: false };
119
+ // 9. shapes.
120
+ switch (field) {
121
+ case "clickIdKind":
122
+ return { value: CLICK_ID_KINDS.includes(s) ? s : null, piiNulled: false };
123
+ case "referrerHost":
124
+ return { value: s.length <= MAX_HOST_LENGTH && LDH_HOST.test(s) ? s : null, piiNulled: false };
125
+ case "landingPath": {
126
+ if (s[0] !== "/")
127
+ return { value: null, piiNulled: false };
128
+ const cut = s.search(/[?#]/);
129
+ if (cut >= 0)
130
+ s = trimEndSpace(s.slice(0, cut));
131
+ return { value: s.length === 0 ? null : s, piiNulled: false };
132
+ }
133
+ default:
134
+ return { value: s, piiNulled: false };
135
+ }
136
+ }
137
+ /** Stage B rules 1–9 for one string (§4.3). Idempotent; never throws. */
138
+ export function stageBValue(field, value) {
139
+ return normalise(field, value).value;
140
+ }
141
+ // ---------------------------------------------------------------------------------------------------------------------
142
+ // Stage A: URL extraction
143
+ const NO_PARTS = { source: null, medium: null, campaign: null, content: null, term: null, referrerHost: null, landingPath: null, clickIdKind: null };
144
+ const HTTP_URL = /^https?:\/\/[^/?#]*([^?#]*)(?:\?([^#]*))?/i;
145
+ const hexVal = (c) => (/^[0-9a-fA-F]$/.test(c) ? parseInt(c, 16) : -1);
146
+ const UTF8_FATAL = new TextDecoder("utf-8", { fatal: true });
147
+ /** Percent-decodes once; an escape that is not part of valid UTF-8 stays literal. */
148
+ function percentDecode(s) {
149
+ if (!s.includes("%"))
150
+ return s;
151
+ let out = "";
152
+ let i = 0;
153
+ while (i < s.length) {
154
+ const byteAt = (p) => {
155
+ if (s[p] !== "%")
156
+ return -1;
157
+ const hi = hexVal(s[p + 1] ?? "");
158
+ const lo = hexVal(s[p + 2] ?? "");
159
+ return hi < 0 || lo < 0 ? -1 : hi * 16 + lo;
160
+ };
161
+ const lead = byteAt(i);
162
+ if (lead < 0) {
163
+ out += s[i];
164
+ i++;
165
+ continue;
166
+ }
167
+ const len = lead < 0x80 ? 1 : lead >= 0xc2 && lead <= 0xdf ? 2 : lead >= 0xe0 && lead <= 0xef ? 3 : lead >= 0xf0 && lead <= 0xf4 ? 4 : 0;
168
+ const bytes = [lead];
169
+ for (let k = 1; k < len; k++) {
170
+ const b = byteAt(i + 3 * k);
171
+ if (b < 0 || (b & 0xc0) !== 0x80)
172
+ break;
173
+ bytes.push(b);
174
+ }
175
+ try {
176
+ if (len === 0 || bytes.length !== len)
177
+ throw new Error("invalid");
178
+ out += UTF8_FATAL.decode(Uint8Array.from(bytes));
179
+ i += 3 * len;
180
+ }
181
+ catch {
182
+ out += s.slice(i, i + 3);
183
+ i += 3;
184
+ }
185
+ }
186
+ return out;
187
+ }
188
+ const decodeQueryPart = (s) => percentDecode(s.replace(/\+/g, " "));
189
+ function readableUrl(href) {
190
+ if (href.includes("\\"))
191
+ return null;
192
+ try {
193
+ const url = new URL(href);
194
+ return url.protocol === "http:" || url.protocol === "https:" ? url : null;
195
+ }
196
+ catch {
197
+ return null;
198
+ }
199
+ }
200
+ const DERIVED = {
201
+ gclid: { source: "google", medium: "cpc" },
202
+ gbraid: { source: "google", medium: "cpc" },
203
+ wbraid: { source: "google", medium: "cpc" },
204
+ msclkid: { source: "bing", medium: "cpc" },
205
+ fbclid: { source: "facebook", medium: null },
206
+ ttclid: { source: "tiktok", medium: "paid" },
207
+ };
208
+ /**
209
+ * Stage A (§4.3): the eight fields from the landing URL and the referrer. Query values: `+` → space, percent-decoded once; the
210
+ * path decoded once without plus-to-space and without dot-segment resolution. Values are not normalised here (stage B does
211
+ * that); an unreadable landing URL yields no landing fields, an unreadable referrer no `referrerHost`.
212
+ */
213
+ export function stageA(landingUrl, referrerUrl) {
214
+ const parts = { ...NO_PARTS };
215
+ if (typeof referrerUrl === "string") {
216
+ const ref = readableUrl(referrerUrl);
217
+ if (ref !== null && ref.hostname !== "")
218
+ parts.referrerHost = ref.hostname;
219
+ }
220
+ if (typeof landingUrl !== "string" || readableUrl(landingUrl) === null)
221
+ return parts;
222
+ const m = HTTP_URL.exec(landingUrl.trim());
223
+ if (m === null)
224
+ return parts;
225
+ parts.landingPath = percentDecode(m[1] === "" || m[1] === undefined ? "/" : m[1]);
226
+ const query = new Map();
227
+ for (const pair of (m[2] ?? "").split("&")) {
228
+ if (pair === "")
229
+ continue;
230
+ const eq = pair.indexOf("=");
231
+ const name = decodeQueryPart(eq < 0 ? pair : pair.slice(0, eq));
232
+ if (!query.has(name))
233
+ query.set(name, decodeQueryPart(eq < 0 ? "" : pair.slice(eq + 1)));
234
+ }
235
+ const utm = (name) => query.get(name) ?? null;
236
+ parts.source = utm("utm_source");
237
+ parts.medium = utm("utm_medium");
238
+ parts.campaign = utm("utm_campaign");
239
+ parts.content = utm("utm_content");
240
+ parts.term = utm("utm_term");
241
+ const kind = CLICK_ID_KINDS.find((k) => query.has(k));
242
+ if (kind !== undefined) {
243
+ parts.clickIdKind = kind;
244
+ const derived = DERIVED[kind];
245
+ if (parts.source === null || parts.source.trim() === "") {
246
+ parts.source = derived.source;
247
+ if (parts.medium === null || parts.medium.trim() === "")
248
+ parts.medium = derived.medium;
249
+ }
250
+ }
251
+ // An empty value is "absent" for derivation only; a parameter that was never given stays null, an empty one is dropped by stage B.
252
+ for (const f of ["source", "medium", "campaign", "content", "term"])
253
+ if (parts[f] === "")
254
+ parts[f] = null;
255
+ return parts;
256
+ }
257
+ // ---------------------------------------------------------------------------------------------------------------------
258
+ // Rules 6′–12′ (per touch)
259
+ const AT_SHAPE = /^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(\.[0-9]{3})?Z$/;
260
+ /** Rule 8′: exactly the two shapes, then a calendar check; epoch ms or null. */
261
+ function parseAt(at) {
262
+ if (typeof at !== "string")
263
+ return null;
264
+ const m = AT_SHAPE.exec(at);
265
+ if (m === null)
266
+ return null;
267
+ const [y, mo, d, h, mi, s] = [1, 2, 3, 4, 5, 6].map((i) => Number(m[i]));
268
+ const ms = m[7] === undefined ? 0 : Number(m[7].slice(1));
269
+ if (y < 1 || mo < 1 || mo > 12 || d < 1 || h > 23 || mi > 59 || s > 59)
270
+ return null;
271
+ const date = new Date(0);
272
+ date.setUTCFullYear(y, mo - 1, d);
273
+ date.setUTCHours(h, mi, s, ms);
274
+ return date.getUTCDate() === d && date.getUTCMonth() === mo - 1 ? date.getTime() : null;
275
+ }
276
+ function formatAt(ms) {
277
+ return new Date(ms).toISOString().replace(".000Z", "Z");
278
+ }
279
+ const hostSet = (hosts) => new Set(hosts.map((h) => h.toLowerCase()));
280
+ /** "Under" = equal, or the prefix followed by `/` (`/checkoutx` is not under `/checkout`). */
281
+ function isUnder(path, prefix) {
282
+ if (prefix === "")
283
+ return false;
284
+ const p = prefix.length > 1 ? prefix.replace(/\/+$/, "") : prefix;
285
+ return path === p || path.startsWith(p === "/" ? p : p + "/");
286
+ }
287
+ /**
288
+ * Rules 6′–10′, each string through stage B first, checked in rule order per touch. 11′'s 8 KB cut is the server's whole-record
289
+ * rule, not applied here. A touch dropped for an unreadable `at`, or by 9′ when the PII guard nulled its `source`, is a format
290
+ * drop; every other drop is a policy drop.
291
+ */
292
+ export function touches(raw, ctx) {
293
+ const own = hostSet(ctx.ownHosts);
294
+ const ignore = hostSet(ctx.ignoreReferrerHosts);
295
+ const provider = hostSet(ctx.providerHosts);
296
+ let policyDrops = 0;
297
+ let formatDrops = 0;
298
+ const kept = [];
299
+ for (const t of raw) {
300
+ const src = normalise("source", t.source);
301
+ const medium = stageBValue("medium", t.medium ?? null);
302
+ const campaign = stageBValue("campaign", t.campaign ?? null);
303
+ const content = ctx.keepContent ? stageBValue("content", t.content ?? null) : null;
304
+ const term = ctx.keepTerm ? stageBValue("term", t.term ?? null) : null;
305
+ let referrerHost = stageBValue("referrerHost", t.referrerHost ?? null);
306
+ const landingPath = stageBValue("landingPath", t.landingPath ?? null);
307
+ const clickIdKind = stageBValue("clickIdKind", t.clickIdKind ?? null);
308
+ const source = src.value;
309
+ // 6′
310
+ if (referrerHost !== null && own.has(referrerHost)) {
311
+ policyDrops++;
312
+ continue;
313
+ }
314
+ if (referrerHost !== null && (ignore.has(referrerHost) || provider.has(referrerHost)))
315
+ referrerHost = null;
316
+ // 7′
317
+ if (landingPath !== null && ctx.dropPaths.some((p) => isUnder(landingPath, p))) {
318
+ policyDrops++;
319
+ continue;
320
+ }
321
+ if (landingPath !== null && ctx.checkoutPaths.some((p) => isUnder(landingPath, p))) {
322
+ referrerHost = null;
323
+ if (source === null) {
324
+ policyDrops++;
325
+ continue;
326
+ }
327
+ }
328
+ // 8′
329
+ const at = parseAt(t.at);
330
+ if (at === null) {
331
+ formatDrops++;
332
+ continue;
333
+ }
334
+ if (ctx.lookbackDays !== null && at < ctx.nowUtc - ctx.lookbackDays * DAY_MS) {
335
+ policyDrops++;
336
+ continue;
337
+ }
338
+ if (at > ctx.nowUtc + FUTURE_TOLERANCE_MS) {
339
+ policyDrops++;
340
+ continue;
341
+ }
342
+ // 9′
343
+ if (source === null && medium === null && campaign === null && referrerHost === null) {
344
+ if (src.piiNulled)
345
+ formatDrops++;
346
+ else
347
+ policyDrops++;
348
+ continue;
349
+ }
350
+ kept.push({ at: formatAt(Math.floor(at / MINUTE_MS) * MINUTE_MS), source, medium, campaign, content, term, referrerHost, landingPath, clickIdKind });
351
+ }
352
+ // 10′: stable sort on the truncated `at`; at more than five, the first plus the newest four.
353
+ kept.sort((a, b) => Date.parse(a.at) - Date.parse(b.at));
354
+ const out = kept.length > MAX_TOUCHES ? [kept[0], ...kept.slice(kept.length - (MAX_TOUCHES - 1))] : kept;
355
+ return { kept: out, policyDrops, formatDrops };
356
+ }
357
+ // ---------------------------------------------------------------------------------------------------------------------
358
+ // §6.3 rules 3–6: merging a landing into the device's touches
359
+ const sameChannel = (a, b) => a.source === b.source && a.medium === b.medium && a.campaign === b.campaign && a.referrerHost === b.referrerHost && a.clickIdKind === b.clickIdKind;
360
+ /**
361
+ * Merges one stage-B touch into the cookie's state: bind to the grant (a different `grantAt` discards the stored touches), collapse
362
+ * a repeat of the newest touch (its `at` is refreshed whatever its age; when the newest is also the first the repeat is appended so
363
+ * the first touch keeps its time), append (at six drop the oldest non-first), drop touches older than the lookback. Null when no touch survives.
364
+ */
365
+ export function mergeLanding(state, touch, policy, now) {
366
+ let list = state !== null && state.grantAt === policy.grantAt ? state.touches.map((t) => ({ ...t })) : [];
367
+ const newest = list[list.length - 1];
368
+ if (newest !== undefined && list.length > 1 && sameChannel(newest, touch)) {
369
+ newest.at = touch.at;
370
+ }
371
+ else {
372
+ list.push({ ...touch });
373
+ if (list.length > MAX_TOUCHES)
374
+ list.splice(1, 1);
375
+ }
376
+ const floor = now - policy.lookbackDays * DAY_MS;
377
+ list = list.filter((t) => {
378
+ const at = parseAt(t.at);
379
+ return at !== null && at >= floor;
380
+ });
381
+ return list.length === 0 ? null : { grantAt: policy.grantAt, touches: list };
382
+ }
383
+ // ---------------------------------------------------------------------------------------------------------------------
384
+ // §6.1 the cookie value
385
+ const BASE64URL = /^[A-Za-z0-9_-]+$/;
386
+ function encode(text) {
387
+ let binary = "";
388
+ for (const byte of new TextEncoder().encode(text))
389
+ binary += String.fromCharCode(byte);
390
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
391
+ }
392
+ function decode(text) {
393
+ if (!BASE64URL.test(text))
394
+ throw new Error("not base64url");
395
+ const binary = atob(text.replace(/-/g, "+").replace(/_/g, "/"));
396
+ return new TextDecoder("utf-8", { fatal: true }).decode(Uint8Array.from(binary, (c) => c.charCodeAt(0)));
397
+ }
398
+ const pack = (c) => "1." + encode(JSON.stringify({ grantAt: c.grantAt, touches: c.touches }));
399
+ /**
400
+ * `"1." + base64url(JSON {grantAt, touches})`, at most 2,000 characters. Over the cap: drop `content`/`term`, then the oldest
401
+ * middle touch (repeatedly), then keep only the newest touch, then null its `landingPath`. A value that is still over the cap
402
+ * after the last step is returned as is (the stage-B caps make that unreachable for ordinary input).
403
+ */
404
+ export function serializeAttr(c) {
405
+ let cur = { grantAt: c.grantAt, touches: c.touches.map((t) => ({ ...t })) };
406
+ let s = pack(cur);
407
+ if (s.length <= MAX_ATTR_COOKIE_LENGTH)
408
+ return s;
409
+ cur = { ...cur, touches: cur.touches.map((t) => ({ ...t, content: null, term: null })) };
410
+ s = pack(cur);
411
+ while (s.length > MAX_ATTR_COOKIE_LENGTH && cur.touches.length > 2) {
412
+ cur = { ...cur, touches: [cur.touches[0], ...cur.touches.slice(2)] };
413
+ s = pack(cur);
414
+ }
415
+ if (s.length <= MAX_ATTR_COOKIE_LENGTH)
416
+ return s;
417
+ const newest = cur.touches[cur.touches.length - 1];
418
+ if (newest === undefined)
419
+ return s;
420
+ cur = { ...cur, touches: [newest] };
421
+ s = pack(cur);
422
+ if (s.length <= MAX_ATTR_COOKIE_LENGTH)
423
+ return s;
424
+ return pack({ ...cur, touches: [{ ...newest, landingPath: null }] });
425
+ }
426
+ const isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
427
+ function readTouch(v) {
428
+ if (!isRecord(v) || typeof v.at !== "string" || parseAt(v.at) === null)
429
+ return null;
430
+ const out = { at: v.at, source: null, medium: null, campaign: null, content: null, term: null, referrerHost: null, landingPath: null, clickIdKind: null };
431
+ for (const f of FIELDS) {
432
+ const x = v[f];
433
+ if (x === undefined || x === null)
434
+ continue;
435
+ if (typeof x !== "string")
436
+ return null;
437
+ out[f] = x;
438
+ }
439
+ return out;
440
+ }
441
+ /**
442
+ * The cookie's value back, or null for a missing value and for **any** shape error: a non-`1.` prefix (a newer SDK's `"2."` reads
443
+ * as empty), bad base64url, malformed JSON, a known field of the wrong kind. Total; unknown members are ignored.
444
+ */
445
+ export function parseAttr(raw) {
446
+ try {
447
+ if (typeof raw !== "string" || !raw.startsWith("1."))
448
+ return null;
449
+ const value = JSON.parse(decode(raw.slice(2)));
450
+ if (!isRecord(value) || !Number.isSafeInteger(value.grantAt) || value.grantAt <= 0)
451
+ return null;
452
+ if (!Array.isArray(value.touches) || value.touches.length > MAX_TOUCHES)
453
+ return null;
454
+ const list = [];
455
+ for (const item of value.touches) {
456
+ const t = readTouch(item);
457
+ if (t === null)
458
+ return null;
459
+ list.push(t);
460
+ }
461
+ return { grantAt: value.grantAt, touches: list };
462
+ }
463
+ catch {
464
+ return null;
465
+ }
466
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * `@asstio-dev/storefront/attribution` — the client-safe attribution entry (order attribution spec §6.2, §6.6): the browser
3
+ * capture and the codec's pure functions and types. It imports neither `next/headers` nor `node:crypto` and never handles a shopper
4
+ * token. The server helpers (`recordLanding`, the wrappers, `readAttribution`, `attributionForCheckout`) are in
5
+ * `@asstio-dev/storefront/attribution/next`.
6
+ */
7
+ export { createAttributionCapture, type AttributionCapture, type AttributionLanding } from "./browser.js";
8
+ export { MAX_ATTR_COOKIE_LENGTH, MAX_TOUCHES, mergeLanding, parseAttr, PROVIDER_HOSTS, serializeAttr, stageA, stageBValue, touches, type AttrCookie, type RawTouch, type RawTouchParts, type Touch, type TouchContext, type TouchField, } from "./codec.js";
@@ -0,0 +1,8 @@
1
+ /**
2
+ * `@asstio-dev/storefront/attribution` — the client-safe attribution entry (order attribution spec §6.2, §6.6): the browser
3
+ * capture and the codec's pure functions and types. It imports neither `next/headers` nor `node:crypto` and never handles a shopper
4
+ * token. The server helpers (`recordLanding`, the wrappers, `readAttribution`, `attributionForCheckout`) are in
5
+ * `@asstio-dev/storefront/attribution/next`.
6
+ */
7
+ export { createAttributionCapture } from "./browser.js";
8
+ export { MAX_ATTR_COOKIE_LENGTH, MAX_TOUCHES, mergeLanding, parseAttr, PROVIDER_HOSTS, serializeAttr, stageA, stageBValue, touches, } from "./codec.js";
@@ -0,0 +1,76 @@
1
+ import { type CookieSpec } from "../account/cookies.js";
2
+ import type { components } from "../schema";
3
+ import { type Touch } from "./codec.js";
4
+ import type { AttributionLanding } from "./browser.js";
5
+ type SiteDto = components["schemas"]["SiteDto"];
6
+ /**
7
+ * The cookie store the helpers read and write: Next's `cookies()` (in a route handler or a Server Action), or anything with the same
8
+ * `get`/`set`/`delete`. The helpers delete by `set` with `Max-Age=0` and the cookie's own attributes (a `__Host-` cookie is only
9
+ * replaced with `Secure; Path=/`).
10
+ */
11
+ export type AttrCookieStore = {
12
+ get(name: string): {
13
+ value: string;
14
+ } | undefined;
15
+ set(spec: CookieSpec): unknown;
16
+ delete(name: string): unknown;
17
+ };
18
+ /** What `attributionForCheckout` hands `startCheckout`/`syncCheckout`. Never return it to a client component. */
19
+ export type CheckoutAttribution = {
20
+ attribution?: {
21
+ touches: Touch[] | null;
22
+ };
23
+ shopperToken?: string;
24
+ };
25
+ /**
26
+ * Records one landing (§6.2 step 3, §6.3): re-reads the consent cookie, applies the floor, builds the touch (stage A + B with the
27
+ * site's own hosts, ignored hosts and paths, server time) and merges it into `__Host-sf_attr` under the device's current
28
+ * `measurement` grant. A direct landing changes nothing. Without an enabled block, or without a grant at or above the floor, it
29
+ * deletes an existing cookie and writes nothing. `opts.origin` is the frontend's own origin (its host counts as an own host).
30
+ */
31
+ export declare function recordLanding(cookies: AttrCookieStore, landing: AttributionLanding, site: SiteDto, opts: {
32
+ origin: string;
33
+ now?: number;
34
+ }): void;
35
+ /**
36
+ * A `POST` route handler around `recordLanding` (the recommended entry point: setting a cookie in a Server Action re-renders the
37
+ * page). The browser posts `{ href, referrer }` as JSON. `Origin` must be `opts.origin` or one of the site's binding origins (403
38
+ * otherwise); a `Content-Length` above 16,384 is 413, and so is a body that streams past 16,384 bytes (the read stops and the stream is
39
+ * cancelled there); a malformed body is 400; success is 204. `getSite` returns the frontend's
40
+ * cached `/v1/site` answer.
41
+ *
42
+ * ```ts
43
+ * // app/api/attribution/route.ts
44
+ * export const POST = recordLandingRoute(getSite, { origin: process.env.SHOP_ORIGIN! });
45
+ * ```
46
+ */
47
+ export declare function recordLandingRoute(getSite: () => Promise<SiteDto>, opts: {
48
+ origin: string;
49
+ }): (req: Request) => Promise<Response>;
50
+ /**
51
+ * A Server Action body around `recordLanding`: wrap it in your own `"use server"` function. It works, but setting the cookie in an
52
+ * action re-renders the current page (A2 spike); prefer `recordLandingRoute`. A malformed landing is ignored.
53
+ */
54
+ export declare function recordLandingAction(getSite: () => Promise<SiteDto>, opts: {
55
+ origin: string;
56
+ }): (landing: AttributionLanding) => Promise<void>;
57
+ /**
58
+ * The device's touches (§6.5): null without an enabled block or without a `measurement` grant at or above the floor; `[]` when it
59
+ * grants and the cookie is missing, unreadable or collected under another grant; else the cookie's touches.
60
+ */
61
+ export declare function readAttribution(cookies: Pick<AttrCookieStore, "get">, site: SiteDto, opts: {
62
+ origin: string;
63
+ }): Touch[] | null;
64
+ /**
65
+ * What to pass `startCheckout`/`syncCheckout` (§6.4, D30). No `attribution` member without an enabled block. `touches` as
66
+ * `readAttribution` reads them (null when the device does not grant `measurement` at or above the floor). `shopperToken` (the
67
+ * `__Host-sf_shopper` cookie) only without a session, with the block enabled and the device granting above the floor.
68
+ *
69
+ * The token is a credential: hand the result straight to the checkout call in the same server code; never return it (or this
70
+ * object) to a client component.
71
+ */
72
+ export declare function attributionForCheckout(site: SiteDto, opts: {
73
+ origin: string;
74
+ session: boolean;
75
+ }): Promise<CheckoutAttribution>;
76
+ export {};