@asstio-dev/storefront 0.53.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.
package/README.md CHANGED
@@ -244,6 +244,74 @@ export function buyBox(offer: OfferDto) {
244
244
  freshness, sellability and a complete price, so a partial price can be visible and still not buyable. Never decide it
245
245
  from `stock`: the API sends no public stock quantity, and zero stock is buyable on a backorder site.
246
246
 
247
+ #### Sales, the 30-day price and the RRP
248
+
249
+ While a sale applies, an offer carries `regular`, `sale` (`{ price, validFrom, validTo, label, extendedFrom }`),
250
+ `reference` (the lowest price of the 30 days before the reduction) and, when the shop may say so, a `claim`
251
+ (`{ labelKey, percent, amountOff, since, endsAt, claimEndsAt }`). **Render every price through `priceDisplay`, on the
252
+ request, with the request's time**, instead of reading these fields:
253
+
254
+ ```tsx
255
+ import { priceDisplay } from "@asstio-dev/storefront";
256
+
257
+ const d = priceDisplay(variant.offer, { now: new Date(), locale: "sv" });
258
+ // endsAt is exclusive: show the date of its last second in the site's time zone.
259
+ const lastDay = (endsAt: string) =>
260
+ new Date(Date.parse(endsAt) - 1000).toLocaleDateString("sv-SE", { timeZone: "Europe/Stockholm" });
261
+ <span data-price-part={d.parts.price}>{d.price?.amount}</span>
262
+ {d.struck && <span>{d.struck.label} <s data-price-part={d.parts.struck} title={d.struck.longLabel}>{d.struck.amount}</s></span>}
263
+ {d.badge && <span data-price-part={d.parts.badge}>{d.badge}</span>} {/* "−20 %", a no-break space before % */}
264
+ {d.rrp && <span data-price-part={d.parts.rrp}>Rek. pris {d.rrp.amount}</span>}
265
+ {d.endsAt && <time data-price-part={d.parts["ends-at"]} dateTime={d.endsAt}>t.o.m. {lastDay(d.endsAt)}</time>}
266
+ ```
267
+
268
+ - A page may be served from a cache past a sale's end. `priceDisplay` drops a `sale` whose `validTo` ≤ `now` (it shows
269
+ `regular`) and the offer's `claim` with it, and drops a `claim` whose `endsAt` or `claimEndsAt` ≤ `now`. An open-ended
270
+ sale (`validTo` null) is never dropped by `now`, and `endsAt` is then null: show no end.
271
+ - `endsAt` is the **exclusive** end (the first second the sale no longer applies). Show the date of `endsAt − 1 s` in
272
+ the site's time zone (`lastDay` above), as `productJsonLd` does for `priceValidUntil`; a sale ending at midnight
273
+ ends "t.o.m." the day before.
274
+ - **Only `struck` is struck**: the claim's `reference`, with the claim's label (`priorLowest`: "Tidigare lägsta pris",
275
+ long form "Lägsta pris de senaste 30 dagarna före prissänkningen"; English for other locales; override with
276
+ `texts`). Never strike `regular`, `compareAt` or `unitPriceBeforePromotions`. A `reference` without a `claim` shows
277
+ nothing.
278
+ - **The RRP (`compareAt`) is never shown while a sale applies**, with or without a claim. With no sale and no claim it
279
+ shows as before. It is never struck.
280
+ - Two places can disagree: a listing card whose price segment has two sale owners carries `sale: null`, so its RRP can
281
+ show on the card while the variant page shows a sale and hides it. That is expected; the card has no sale to show.
282
+ - The optional members (`reference`, `claim`, `sale.label`, `sale.extendedFrom`) may be absent from a response: read
283
+ them as `x ?? null`, as `priceDisplay` does.
284
+
285
+ **Lines.** `linePriceDisplay(line, { now, currency })` does the same for a cart, checkout or order line's unit price: a
286
+ line's `claim` strikes its `reference` whether or not the product is on sale (a code that beats the sale still shows a
287
+ true percent). Cart lines are live (a claim past its end drops); checkout and order lines carry the order's evidence and
288
+ are never dropped by `now`. `currency` (the checkout's or order's) is required for checkout and order lines, whose unit
289
+ price is an inc string; without it the line shows no price. An `item` promotion effect in `cart.promotions` (`stage: "item"`) is data: **never render it as a discount
290
+ row**, and never show `subtotalBeforePromotions` while one is present; the struck price comes only from a line's
291
+ `claim`. A code line with no claim shows the code's reduction as a discount row, as before.
292
+
293
+ **Revalidation.** A cached page that shows prices must not outlive the next price change.
294
+ `nextRevalidateSeconds(site, now)` is the seconds until `site.nextPriceBoundary`, at most 60 and at least 1. It is
295
+ **not** a value for Next's `export const revalidate` or `fetch(…, { next: { revalidate } })`: the Data Cache can serve
296
+ an expired entry of any age (C10). Use it for a cache you control, such as the memo below:
297
+
298
+ ```ts
299
+ const { data: site } = await storefront.GET("/v1/site", {});
300
+ const seconds = nextRevalidateSeconds(site!, new Date()); // the lifetime of your own memo entry
301
+ ```
302
+
303
+ Catalog answers of a site with an item promotion carry `X-Price-Valid-Until`. A frontend never shows a catalog answer
304
+ more than 60 s after it fetched it, nor past that header. Next's Data Cache (`fetch` with `revalidate`) can serve an
305
+ entry of any age to the first reader after expiry, so read catalog endpoints with `cache: "no-store"` behind your own
306
+ memo with the lifetime `min(fetchedAt + 60 s, X-Price-Valid-Until)`, and never store a response whose `Cache-Control`
307
+ holds `private` or `no-store`.
308
+
309
+ **JSON-LD.** Pass `now` to `productJsonLd`: each offer's price is then the price charged at `now`, and a live sale with
310
+ an end adds `priceValidUntil` (the date of its last second in `timeZone`, default `Europe/Stockholm`).
311
+
312
+ **Code reasons.** `codeReasonText(code.reason, locale)` gives a default text for a code that does not apply, e.g.
313
+ `superseded` → "Ett bättre erbjudande gäller redan".
314
+
247
315
  ### Variant names
248
316
 
249
317
  `variant.name` (on `VariantDto`, cart lines' `variant` and checkout/order lines' `variant`) is the variant's own name from
@@ -827,6 +895,113 @@ Guest favorites, stock watches and the device's consent live in five entries (sh
827
895
  rate limit is the shopper's and never one bucket for everyone behind your server. It never sends a session or shopper
828
896
  token, and the API answers `204` whatever the token is, so show a fixed text.
829
897
 
898
+ ### Order attribution
899
+
900
+ Records where a shopper came from (UTM parameters, click ids, a cross-origin referrer) and sends it with the checkout, only for a
901
+ device that grants `measurement`. Nothing happens on a site whose `attribution` block is absent or not `enabled`. Two entries:
902
+ `@asstio-dev/storefront/attribution` (browser-safe: `createAttributionCapture`, the cookie codec) and
903
+ `@asstio-dev/storefront/attribution/next` (server: `recordLanding`, `recordLandingRoute`, `recordLandingAction`,
904
+ `readAttribution`, `attributionForCheckout`).
905
+
906
+ **Mounting**
907
+
908
+ 1. Add a route handler, the recommended wrapper: `export const POST = recordLandingRoute(getSite, { origin })` in
909
+ `app/api/attribution/route.ts`. It takes `{ href, referrer }` as JSON, accepts only your own origin or a binding origin
910
+ (otherwise 403), refuses a body above 16 KB with 413 (it stops reading there, with or without `Content-Length`), and answers
911
+ 204. `recordLandingAction` is a Server Action body and works too, but setting a cookie from an
912
+ action re-renders the current page.
913
+ 2. In a client component in the root layout create the capture once with `createAttributionCapture({ send })`, where `send`
914
+ posts the landing to that route (`keepalive: true`). The capture holds nothing in memory: at `flush` it reads the landing from
915
+ the browser's navigation entry and `document.referrer` and sends only a landing that can be a touch (a `utm_*` or click-id
916
+ parameter, or a cross-origin referrer): at most once per page, and nothing where the entry is unavailable (an under-count,
917
+ never a wrong landing). A plain page load posts nothing.
918
+ 3. Call `capture.flush(...)` after mount, and again after `coordinator.set()` resolves with `measurement` granted, passing
919
+ `{ ...coordinator.effective(), measurement: coordinator.effective().measurement && !belowFloor }`. `belowFloor` is true when the
920
+ device's recorded notice `ref` decodes (`noticeVersion`) below `site.attribution.minNoticeVersion`, or when there is no `ref`
921
+ while the block is enabled (see "The notice floor"). The gate matters: the capture sends at most once per page, and the server
922
+ refuses a landing under an older notice, so an ungated flush before the re-ask would spend the page's one send and lose the
923
+ landing. On a refusal call `capture.discard()`: every later `flush` of the page does nothing. Call both only from effects or
924
+ event handlers, never during render.
925
+
926
+ The server writes `__Host-sf_attr` (`HttpOnly`, at most five touches, kept for `lookbackDays`). It never writes the consent
927
+ cookies. A landing without a `measurement` grant, or on a site without an enabled block, deletes the attribution cookie.
928
+
929
+ **Checkout.** At every `startCheckout`/`syncCheckout` call site spread `await attributionForCheckout(site, { origin, session })`
930
+ into the options. `session` is true when a shopper is signed in; then also pass the request-scoped shopper client
931
+ (`shopper: await shopperClient(config)`), so the call carries the session: `session: true` drops the guest token, and without
932
+ `shopper` a saved (owned) cart cannot check out. Take both from the same session cookie. It returns no `attribution` member without an enabled block,
933
+ `{ touches: null }` when the device does not grant `measurement` above the floor, else the touches. Without a session it also
934
+ carries the guest shopper token. That is a credential: hand the result straight to the checkout call in the same server code,
935
+ never return it (or the token) to a client component. A frontend that sends no `attribution` member changes nothing.
936
+
937
+ **The notice floor.** `site.attribution.minNoticeVersion` is the oldest consent notice that may back attribution. The consent
938
+ cookie keeps one `ref`, the latest decision's, not one per purpose, so the device-side floor check uses that `ref` and the server
939
+ re-checks the floor against its own consent record before it stores any touch. A grant whose `ref` decodes below the floor
940
+ counts as not granted for attribution only; consent itself is untouched. Ask again when
941
+ `noticeVersion(ref) < site.attribution.minNoticeVersion`, or when there is no `ref` while the block is enabled; gate the capture's
942
+ `flush` on the same test (mounting step 3). `noticeVersion` is exported from `@asstio-dev/storefront/consent`. On the server
943
+ `readConsentCookie(cookies, { origin }).ref` gives the `ref`. In the browser the consent cookie is script-readable: read
944
+ `consentCookieNames(location.origin).consent` from `document.cookie`, parse it with `parseConsent`, and take its `ref` unless
945
+ `isFallback` (all from `@asstio-dev/storefront/consent`).
946
+
947
+ **Withdrawal and erase.** Every `measurement` withdrawal (a decision, a re-send, a replay) through
948
+ `shopperActions(config).consent.put`, and `shopperState.erase()`, delete `__Host-sf_attr` and clear the cart's checkout
949
+ attribution (`DELETE /v1/checkout/attribution`, up to three calls). That clear needs `cartCookie` in the config; without it
950
+ nothing is cleared and `checkoutCleared` is absent. When it ran, the result carries `checkoutCleared`: log a `false` (no values).
951
+ The consent answer is returned unchanged either way. If the `PUT` throws and a clear ran, `ConsentPutFailed` is thrown with the
952
+ original `cause` and `checkoutCleared`; without a cart cookie no clear runs and the original error is rethrown unchanged. If the erase call itself throws, the clear still runs and the original error is
953
+ rethrown unchanged, so `checkoutCleared` is not reported then.
954
+
955
+ **Lock time.** The clear runs inside the action, so `withShopperLock` now holds `sf-shopper` up to about 5.5 s longer on a
956
+ withdrawal (three 1.5 s attempts and two pauses of 0.2 s and 0.8 s). The coordinator's 30 s `PUT` cap counts that time.
957
+
958
+ ```ts
959
+ import { createAttributionCapture } from "@asstio-dev/storefront/attribution";
960
+ import { attributionForCheckout, recordLandingRoute } from "@asstio-dev/storefront/attribution/next";
961
+ import { consentCookieNames, isFallback, noticeVersion, parseConsent } from "@asstio-dev/storefront/consent";
962
+ import { cookieSecurity, sessionCookie } from "@asstio-dev/storefront/account";
963
+ import { shopperClient } from "@asstio-dev/storefront/account/next";
964
+
965
+ // app/api/attribution/route.ts
966
+ export const POST = recordLandingRoute(getSite, { origin: "https://shop.example" });
967
+
968
+ // The notice floor: the recorded `ref` decodes below `minNoticeVersion`, or is missing while the block is enabled.
969
+ function belowFloor(block: SiteDto["attribution"], ref: string | null): boolean {
970
+ if (block?.enabled !== true) return false;
971
+ const version = ref === null ? null : noticeVersion(ref);
972
+ return version === null || version < Number(block.minNoticeVersion);
973
+ }
974
+ // In the browser: the consent cookie is script-readable.
975
+ function recordedRef(): string | null {
976
+ const name = consentCookieNames(location.origin).consent;
977
+ const pair = document.cookie.split(";").map((c) => c.trim()).find((c) => c.startsWith(name + "="));
978
+ const cookie = parseConsent(pair?.slice(name.length + 1));
979
+ return cookie && !isFallback(cookie) ? cookie.ref : null;
980
+ }
981
+
982
+ // Client component in the root layout; `block` is `site.attribution`, passed down from a server component.
983
+ const locked = withShopperLock(actions); // your "use server" shopper actions
984
+ const coordinator = createConsentCoordinator({
985
+ site: siteKey, owner,
986
+ transport: { put: async (body, owner, opts) => locked.consent.put(body, owner, opts) },
987
+ });
988
+ const capture = createAttributionCapture({
989
+ send: async (landing) => { await fetch("/api/attribution", { method: "POST", body: JSON.stringify(landing), keepalive: true }); },
990
+ });
991
+ const gated = (effective: Record<Purpose, boolean>) =>
992
+ ({ ...effective, measurement: effective.measurement && !belowFloor(block, recordedRef()) });
993
+ capture.flush(gated(coordinator.effective())); // after mount
994
+ // belowFloor(block, recordedRef()): ask again with the current notice
995
+ // after `await coordinator.set(...)` saved a measurement grant: capture.flush(gated(coordinator.effective()));
996
+ // on a refusal: capture.discard();
997
+
998
+ // Server, at every checkout call site: the session flag and the shopper client come from the same session cookie.
999
+ const session = Boolean((await cookies()).get(sessionCookie.cookieName(cookieSecurity("https://shop.example")))?.value);
1000
+ const shopper = session ? await shopperClient(config) : null;
1001
+ const attribution = await attributionForCheckout(site, { origin: "https://shop.example", session });
1002
+ await syncCheckout(storefront, cartToken, { returnOrigin: "https://shop.example", shopper, ...attribution }, { retries: 0 });
1003
+ ```
1004
+
830
1005
  ## Headers
831
1006
 
832
1007
  The client sets `X-Site-Key` and the context it was built with: `X-Market`, `X-Country` and `X-Locale`, from `market`,
@@ -69,6 +69,18 @@ interface ShopperCookie {
69
69
  cookieName(opts: CookieSecurity): string;
70
70
  }
71
71
  export declare const shopperCookie: ShopperCookie;
72
+ interface AttrCookieDescriptor {
73
+ /**
74
+ * The device's attribution touches (order attribution spec §6.1): `"1." + base64url(JSON)`, HttpOnly, written only by
75
+ * `recordLanding` (`attribution/next`). `Max-Age` runs `lookbackDays` from the last write.
76
+ */
77
+ (value: string, opts: CookieSecurity & {
78
+ lookbackDays: number;
79
+ }): CookieSpec;
80
+ clear(opts: CookieSecurity): CookieSpec;
81
+ cookieName(opts: CookieSecurity): string;
82
+ }
83
+ export declare const attrCookie: AttrCookieDescriptor;
72
84
  /** A `Set-Cookie` header value for a route handler or middleware. */
73
85
  export declare function serializeCookie(c: CookieSpec): string;
74
86
  export {};
@@ -15,6 +15,8 @@ const CART_SECONDS = 30 * 24 * 3600;
15
15
  const SHOPPER = "sf_shopper";
16
16
  /** Shopper-state spec §4.2: the guest shopper token lives 12 months after its last write. */
17
17
  const SHOPPER_SECONDS = 365 * 24 * 3600;
18
+ const ATTR = "sf_attr";
19
+ const DAY_SECONDS = 24 * 3600;
18
20
  const LOCAL_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]"]);
19
21
  /** The cookie security of the frontend's own origin: `{ secure: false }` only for `http://localhost` (and its loopback forms). */
20
22
  export function cookieSecurity(origin) {
@@ -57,6 +59,10 @@ export const shopperCookie = Object.assign((token, opts) => spec(named(SHOPPER,
57
59
  clear: (opts) => spec(named(SHOPPER, opts), "", 0, opts),
58
60
  cookieName: (opts) => named(SHOPPER, opts),
59
61
  });
62
+ export const attrCookie = Object.assign((value, opts) => spec(named(ATTR, opts), value, opts.lookbackDays * DAY_SECONDS, opts), {
63
+ clear: (opts) => spec(named(ATTR, opts), "", 0, opts),
64
+ cookieName: (opts) => named(ATTR, opts),
65
+ });
60
66
  /** A `Set-Cookie` header value for a route handler or middleware. */
61
67
  export function serializeCookie(c) {
62
68
  return `${c.name}=${encodeURIComponent(c.value)}; Path=${c.path}; Max-Age=${c.maxAge}; HttpOnly${c.secure ? "; Secure" : ""}; SameSite=Lax`;
@@ -99,5 +99,5 @@ export declare function accountResult<T>(r: {
99
99
  response: Response;
100
100
  }): AccountResult<T>;
101
101
  export { cartTotals, copyBrowserCart, copyKey, CopyBrowserCartError, type CartTotals, type CopyBrowserCartResult } from "./cart.js";
102
- export { browserCartCookie, cartCookie, cookieSecurity, readSignInCookie, serializeCookie, sessionCookie, shopperCookie, signInCookie, type CookieSecurity, type CookieSpec, type SignInCookieValue, } from "./cookies.js";
102
+ export { attrCookie, browserCartCookie, cartCookie, cookieSecurity, readSignInCookie, serializeCookie, sessionCookie, shopperCookie, signInCookie, type CookieSecurity, type CookieSpec, type SignInCookieValue, } from "./cookies.js";
103
103
  export { assertSameOrigin, CrossOriginError, safeReturnPath, shopperIpFrom, type HeadersLike } from "./security.js";
@@ -114,5 +114,5 @@ function isProblem(value) {
114
114
  return typeof value === "object" && value !== null && typeof value.code === "string";
115
115
  }
116
116
  export { cartTotals, copyBrowserCart, copyKey, CopyBrowserCartError } from "./cart.js";
117
- export { browserCartCookie, cartCookie, cookieSecurity, readSignInCookie, serializeCookie, sessionCookie, shopperCookie, signInCookie, } from "./cookies.js";
117
+ export { attrCookie, browserCartCookie, cartCookie, cookieSecurity, readSignInCookie, serializeCookie, sessionCookie, shopperCookie, signInCookie, } from "./cookies.js";
118
118
  export { assertSameOrigin, CrossOriginError, safeReturnPath, shopperIpFrom } from "./security.js";
@@ -130,7 +130,30 @@ export type OwnerMismatch = {
130
130
  ok: false;
131
131
  local: "owner_mismatch";
132
132
  };
133
- export type ConsentPutResult = ShopperActionResult<ConsentAnswerDto> | OwnerMismatch;
133
+ /**
134
+ * Order attribution D42 (spec §6.5): after a body that withdraws `measurement`, `checkoutCleared` says whether
135
+ * `DELETE /v1/checkout/attribution` cleared the cart's checkouts (`true`) or not after three calls (`false`). Present only when a clear
136
+ * was attempted (a cart cookie was present); the consent answer is otherwise unchanged. Log a `false` (no values).
137
+ */
138
+ export type CheckoutCleared = {
139
+ checkoutCleared?: boolean;
140
+ };
141
+ export type ConsentPutResult = (ShopperActionResult<ConsentAnswerDto> | OwnerMismatch) & CheckoutCleared;
142
+ /** What `shopperState.erase()` answers: `checkoutCleared` as on `ConsentPutResult`. */
143
+ export type EraseResult = AccountResult<{
144
+ erased: true;
145
+ }> & CheckoutCleared;
146
+ /**
147
+ * A consent `PUT` (or its `GET /v1/me`) that threw after a `measurement` withdrawal whose checkout clear was attempted (D42): the clear
148
+ * ran, and `checkoutCleared` reports it; `cause` is the original error. Log a `false` (no values), then rethrow: the consent
149
+ * coordinator treats it as any thrown transport. Without an attempted clear (no cart cookie) the original error is thrown unchanged.
150
+ */
151
+ export declare class ConsentPutFailed extends Error {
152
+ readonly cause: unknown;
153
+ /** Present (an own property) only when a clear was attempted; `declare` keeps the class from defining it as `undefined`. */
154
+ readonly checkoutCleared?: boolean;
155
+ constructor(cause: unknown, checkoutCleared?: boolean);
156
+ }
134
157
  /** `GET /v1/shopper`, or `{ shopper: null }` when this browser holds no shopper token (no request is made). */
135
158
  export type ShopperStateView = ShopperStateDto | {
136
159
  shopper: null;
@@ -181,10 +204,12 @@ export declare function shopperActions(config: AccountActionConfig): {
181
204
  /**
182
205
  * `DELETE /v1/shopper` with the token, always on the guest route and without the session; then the shopper cookie is cleared.
183
206
  * `{ erased: true }` tells the page to call `coordinator.erased()`, which clears the consent cookie.
207
+ *
208
+ * Order attribution (D42): `__Host-sf_attr` is deleted, and with a cart cookie the cart's checkout attribution is cleared
209
+ * afterwards (`DELETE /v1/checkout/attribution`), with or without a shopper token and whatever the erase answered; the result
210
+ * then carries `checkoutCleared`. A thrown erase still runs the clear, then rethrows its error unchanged.
184
211
  */
185
- erase(): Promise<AccountResult<{
186
- erased: true;
187
- }>>;
212
+ erase(): Promise<EraseResult>;
188
213
  };
189
214
  consent: {
190
215
  /** `GET /v1/me/consents` signed in (feed `coordinator.setAccount(current, true)`), `GET /v1/shopper/consents` as a guest. */
@@ -200,6 +225,11 @@ export declare function shopperActions(config: AccountActionConfig): {
200
225
  * - `none`: only with `mayMint: true` (a fresh decision) while there is no session and no shopper cookie → the tokenless guest
201
226
  * `PUT`, which mints: the token is persisted and the result's `shopper.owner` is the new `t.` owner that binds this decision.
202
227
  * Anything else sends nothing: `{ ok: false, local: "owner_mismatch" }`. The action never sets a consent cookie.
228
+ *
229
+ * Order attribution (D42, spec §6.5): a body that withdraws `measurement` (every one: a decision, a re-send, a replay, a
230
+ * compensation) deletes `__Host-sf_attr` before the owner check and, when the cart cookie is present, clears the cart's checkout
231
+ * attribution after the `PUT` on every outcome (applied, unapplied, failed, `owner_mismatch`): the result then carries
232
+ * `checkoutCleared`. A `PUT` that throws throws `ConsentPutFailed` after the clear (its original error when none was attempted).
203
233
  */
204
234
  put(body: ConsentPutRequest, owner: string, opts?: {
205
235
  mayMint?: boolean;
@@ -16,7 +16,7 @@ import { cookies, headers } from "next/headers.js";
16
16
  import { accountResult, createShopperClient, getMe, localFailure, signOut, startSignIn, switchPrincipal, verifySignIn, } from "./index.js";
17
17
  import { accountOwner, consentOwner, tokenOwner } from "../consent/server.js";
18
18
  import { copyBrowserCart, CopyBrowserCartError } from "./cart.js";
19
- import { browserCartCookie, cartCookie, cookieSecurity, readSignInCookie, sessionCookie, shopperCookie, signInCookie, } from "./cookies.js";
19
+ import { attrCookie, browserCartCookie, cartCookie, cookieSecurity, readSignInCookie, sessionCookie, shopperCookie, signInCookie, } from "./cookies.js";
20
20
  import { safeReturnPath, shopperIpFrom } from "./security.js";
21
21
  async function context(config) {
22
22
  const jar = await cookies();
@@ -170,6 +170,21 @@ export async function shopperClient(config) {
170
170
  const { jar, security, client } = await context(config);
171
171
  return client(session(jar, security));
172
172
  }
173
+ /**
174
+ * A consent `PUT` (or its `GET /v1/me`) that threw after a `measurement` withdrawal whose checkout clear was attempted (D42): the clear
175
+ * ran, and `checkoutCleared` reports it; `cause` is the original error. Log a `false` (no values), then rethrow: the consent
176
+ * coordinator treats it as any thrown transport. Without an attempted clear (no cart cookie) the original error is thrown unchanged.
177
+ */
178
+ export class ConsentPutFailed extends Error {
179
+ cause;
180
+ constructor(cause, checkoutCleared) {
181
+ super("The consent PUT failed.", { cause });
182
+ this.name = "ConsentPutFailed";
183
+ this.cause = cause;
184
+ if (checkoutCleared !== undefined)
185
+ this.checkoutCleared = checkoutCleared;
186
+ }
187
+ }
173
188
  /** Spec §4.2: only these two codes mean the token is gone. Never a bare 404/409: `LIST_FULL` and `PRODUCT_NOT_FOUND` share them. */
174
189
  const TOKEN_GONE = new Set(["SHOPPER_TOKEN_UNKNOWN", "SHOPPER_TOKEN_ADOPTED"]);
175
190
  const OWNER_MISMATCH = { ok: false, local: "owner_mismatch" };
@@ -181,7 +196,10 @@ function voidResult(r) {
181
196
  const tokenHeader = (token) => (token ? { "X-Shopper-Token": token } : {});
182
197
  async function shopperContext(config) {
183
198
  const ctx = await context(config);
184
- return { ...ctx, session: session(ctx.jar, ctx.security), token: read(ctx.jar, shopperCookie.cookieName(ctx.security)) };
199
+ return {
200
+ ...ctx, session: session(ctx.jar, ctx.security), token: read(ctx.jar, shopperCookie.cookieName(ctx.security)),
201
+ cart: config.cartCookie ? read(ctx.jar, config.cartCookie) : null,
202
+ };
185
203
  }
186
204
  /**
187
205
  * After a guest-route answer: a minted token is persisted (12 months) and any other successful write re-sets the token it sent
@@ -223,6 +241,112 @@ function guestVoid(ctx, r) {
223
241
  keepToken(ctx, r, true);
224
242
  return r;
225
243
  }
244
+ /** D42: whether a consent body withdraws `measurement` (alone or among other purposes). Every such body clears, replays included. */
245
+ const withdrawsMeasurement = (body) => body.purposes?.measurement === "withdrawn";
246
+ /** Deletes `__Host-sf_attr` when present, with its own attributes (`Secure; Path=/`): a deletion without `Secure` is ignored. */
247
+ function dropAttr(ctx) {
248
+ if (read(ctx.jar, attrCookie.cookieName(ctx.security)))
249
+ set(ctx.jar, attrCookie.clear(ctx.security));
250
+ }
251
+ const CLEAR_TIMEOUT_MS = 1500;
252
+ /** The waits before the second and the third call. */
253
+ const CLEAR_RETRY_DELAYS_MS = [200, 800];
254
+ /** An order-scope route: the commerce context plays no part in it, so the clear sends none. */
255
+ const withoutCommerceContext = {
256
+ onRequest({ request }) {
257
+ for (const name of ["X-Market", "X-Country", "X-Locale"])
258
+ request.headers.delete(name);
259
+ return request;
260
+ },
261
+ };
262
+ /**
263
+ * The clear is classified by its status alone: the body is cancelled unread and the call sees an empty answer with the same status,
264
+ * so no body (a proxy's HTML page on a 200, say) can turn a status that is not retried into a parse error that is.
265
+ */
266
+ const statusOnly = {
267
+ onResponse({ response }) {
268
+ response.body?.cancel().catch(() => { });
269
+ return new Response(null, { status: response.status });
270
+ },
271
+ };
272
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
273
+ /**
274
+ * One `DELETE /v1/checkout/attribution` (1.5 s timeout), classified by status before any body is read: `cleared` on 204, `retry` on
275
+ * 503, a network error or a timeout, else `stop` (any other 2xx included).
276
+ */
277
+ async function clearOnce(client, cart) {
278
+ // AbortSignal.timeout(1500), with a timer that is cleared once the call is done.
279
+ const controller = new AbortController();
280
+ const timer = setTimeout(() => controller.abort(new DOMException("The checkout attribution clear timed out.", "TimeoutError")), CLEAR_TIMEOUT_MS);
281
+ try {
282
+ const { response } = await client.DELETE("/v1/checkout/attribution", {
283
+ headers: { "X-Cart-Token": cart }, signal: controller.signal, middleware: [withoutCommerceContext, statusOnly], parseAs: "stream",
284
+ });
285
+ if (response.status === 204)
286
+ return "cleared";
287
+ return response.status === 503 ? "retry" : "stop";
288
+ }
289
+ catch {
290
+ return "retry";
291
+ }
292
+ finally {
293
+ clearTimeout(timer);
294
+ }
295
+ }
296
+ /**
297
+ * D42 (spec §6.5, §7.11): clears the cart's checkout attribution with `DELETE /v1/checkout/attribution`, the cart token, the server key
298
+ * and no session (the API resolves the cart by its token alone). `undefined` = no cart cookie, nothing attempted; `true` = 204;
299
+ * `false` = a status other than 204 and 503, or three calls that met 503, a network error or a timeout. It never throws.
300
+ */
301
+ async function clearCheckoutAttribution(ctx) {
302
+ if (!ctx.cart)
303
+ return undefined;
304
+ const client = ctx.client(null);
305
+ for (let attempt = 0;; attempt++) {
306
+ const outcome = await clearOnce(client, ctx.cart);
307
+ if (outcome !== "retry")
308
+ return outcome === "cleared";
309
+ if (attempt >= CLEAR_RETRY_DELAYS_MS.length)
310
+ return false;
311
+ await sleep(CLEAR_RETRY_DELAYS_MS[attempt]);
312
+ }
313
+ }
314
+ /** The consent `PUT` for the owner the coordinator captured (PL9); see `shopperActions(config).consent.put`. */
315
+ async function putConsent(ctx, body, owner, opts) {
316
+ if (owner.startsWith("a.")) {
317
+ if (!ctx.session)
318
+ return OWNER_MISMATCH;
319
+ const client = ctx.client(ctx.session);
320
+ const me = await getMe(client);
321
+ if (!me.ok)
322
+ return me.status === 401 ? OWNER_MISMATCH : me;
323
+ if (accountOwner(me.data.id) !== owner)
324
+ return OWNER_MISMATCH;
325
+ return accountView(accountResult(await client.PUT("/v1/me/consents", { body })), me);
326
+ }
327
+ if (owner.startsWith("t.")) {
328
+ if (!ctx.token || tokenOwner(ctx.token) !== owner)
329
+ return OWNER_MISMATCH;
330
+ return guestView(ctx, accountResult(await ctx.client(null).PUT("/v1/shopper/consents", { body, headers: tokenHeader(ctx.token) })), true);
331
+ }
332
+ if (owner === "none" && opts.mayMint === true && !ctx.session && !ctx.token) {
333
+ return guestView(ctx, accountResult(await ctx.client(null).PUT("/v1/shopper/consents", { body })), true);
334
+ }
335
+ return OWNER_MISMATCH;
336
+ }
337
+ /** `DELETE /v1/shopper` with the token; see `shopperActions(config).shopperState.erase`. */
338
+ async function eraseShopper(ctx) {
339
+ if (!ctx.token)
340
+ return { ok: true, data: { erased: true } };
341
+ const r = voidResult(await ctx.client(null).DELETE("/v1/shopper", { headers: tokenHeader(ctx.token) }));
342
+ if (!r.ok) {
343
+ keepToken(ctx, r, false);
344
+ return r;
345
+ }
346
+ set(ctx.jar, shopperCookie.clear(ctx.security));
347
+ return { ok: true, data: { erased: true } };
348
+ }
349
+ const withCleared = (result, cleared) => cleared === undefined ? result : { ...result, checkoutCleared: cleared };
226
350
  /**
227
351
  * Server actions for favorites, stock watches, the shopper's own state and consent (shopper-state spec §4.2, §5, §6, §7.4, §9.4; PL8, PL9). Call them
228
352
  * from your own `"use server"` actions. Signed in (a session cookie) they use `/v1/me/*`; as a guest the session-less `/v1/shopper/*`
@@ -344,18 +468,23 @@ export function shopperActions(config) {
344
468
  /**
345
469
  * `DELETE /v1/shopper` with the token, always on the guest route and without the session; then the shopper cookie is cleared.
346
470
  * `{ erased: true }` tells the page to call `coordinator.erased()`, which clears the consent cookie.
471
+ *
472
+ * Order attribution (D42): `__Host-sf_attr` is deleted, and with a cart cookie the cart's checkout attribution is cleared
473
+ * afterwards (`DELETE /v1/checkout/attribution`), with or without a shopper token and whatever the erase answered; the result
474
+ * then carries `checkoutCleared`. A thrown erase still runs the clear, then rethrows its error unchanged.
347
475
  */
348
476
  async erase() {
349
477
  const ctx = await shopperContext(config);
350
- if (!ctx.token)
351
- return { ok: true, data: { erased: true } };
352
- const r = voidResult(await ctx.client(null).DELETE("/v1/shopper", { headers: tokenHeader(ctx.token) }));
353
- if (!r.ok) {
354
- keepToken(ctx, r, false);
355
- return r;
478
+ dropAttr(ctx);
479
+ let r;
480
+ try {
481
+ r = await eraseShopper(ctx);
356
482
  }
357
- set(ctx.jar, shopperCookie.clear(ctx.security));
358
- return { ok: true, data: { erased: true } };
483
+ catch (error) {
484
+ await clearCheckoutAttribution(ctx);
485
+ throw error;
486
+ }
487
+ return withCleared(r, await clearCheckoutAttribution(ctx));
359
488
  },
360
489
  },
361
490
  consent: {
@@ -387,29 +516,26 @@ export function shopperActions(config) {
387
516
  * - `none`: only with `mayMint: true` (a fresh decision) while there is no session and no shopper cookie → the tokenless guest
388
517
  * `PUT`, which mints: the token is persisted and the result's `shopper.owner` is the new `t.` owner that binds this decision.
389
518
  * Anything else sends nothing: `{ ok: false, local: "owner_mismatch" }`. The action never sets a consent cookie.
519
+ *
520
+ * Order attribution (D42, spec §6.5): a body that withdraws `measurement` (every one: a decision, a re-send, a replay, a
521
+ * compensation) deletes `__Host-sf_attr` before the owner check and, when the cart cookie is present, clears the cart's checkout
522
+ * attribution after the `PUT` on every outcome (applied, unapplied, failed, `owner_mismatch`): the result then carries
523
+ * `checkoutCleared`. A `PUT` that throws throws `ConsentPutFailed` after the clear (its original error when none was attempted).
390
524
  */
391
525
  async put(body, owner, opts = {}) {
392
526
  const ctx = await shopperContext(config);
393
- if (owner.startsWith("a.")) {
394
- if (!ctx.session)
395
- return OWNER_MISMATCH;
396
- const client = ctx.client(ctx.session);
397
- const me = await getMe(client);
398
- if (!me.ok)
399
- return me.status === 401 ? OWNER_MISMATCH : me;
400
- if (accountOwner(me.data.id) !== owner)
401
- return OWNER_MISMATCH;
402
- return accountView(accountResult(await client.PUT("/v1/me/consents", { body })), me);
403
- }
404
- if (owner.startsWith("t.")) {
405
- if (!ctx.token || tokenOwner(ctx.token) !== owner)
406
- return OWNER_MISMATCH;
407
- return guestView(ctx, accountResult(await ctx.client(null).PUT("/v1/shopper/consents", { body, headers: tokenHeader(ctx.token) })), true);
527
+ if (!withdrawsMeasurement(body))
528
+ return putConsent(ctx, body, owner, opts);
529
+ dropAttr(ctx);
530
+ let result;
531
+ try {
532
+ result = await putConsent(ctx, body, owner, opts);
408
533
  }
409
- if (owner === "none" && opts.mayMint === true && !ctx.session && !ctx.token) {
410
- return guestView(ctx, accountResult(await ctx.client(null).PUT("/v1/shopper/consents", { body })), true);
534
+ catch (error) {
535
+ const cleared = await clearCheckoutAttribution(ctx);
536
+ throw cleared === undefined ? error : new ConsentPutFailed(error, cleared);
411
537
  }
412
- return OWNER_MISMATCH;
538
+ return withCleared(result, await clearCheckoutAttribution(ctx));
413
539
  },
414
540
  },
415
541
  /**
@@ -0,0 +1,35 @@
1
+ /**
2
+ * The browser half of order attribution capture (order attribution spec §6.2): one client component in the root layout creates
3
+ * the capture once and calls `flush(coordinator.effective())` after mount and after every `coordinator.set()` that resolves with
4
+ * `measurement` granted, with `measurement` forced to false while the recorded notice `ref` is below `minNoticeVersion` (or missing
5
+ * with the block enabled): the page sends at most once and the server refuses a landing under an older notice, so the frontend holds
6
+ * it back until the re-ask's grant (README, mounting step 3). On an explicit refusal it calls `discard()`.
7
+ *
8
+ * The capture holds nothing in memory (§6.2 step 4, A2 spike): at `flush` it reads the document's original URL from the
9
+ * `navigation` performance entry and `document.referrer`, which keep the landing through App Router client navigations. Without a
10
+ * navigation entry it sends nothing (an under-count, never a wrong landing). Stage A runs on the server (`recordLanding`); the wire
11
+ * is `{ href, referrer }`. Client-safe: no `next/headers`, no `node:crypto`, no shopper token.
12
+ */
13
+ import type { Purpose } from "../consent/codec.js";
14
+ /** What the frontend's server entry point receives: the landing URL and the referrer as the browser saw them. */
15
+ export type AttributionLanding = {
16
+ href: string;
17
+ referrer: string;
18
+ };
19
+ export interface AttributionCapture {
20
+ /**
21
+ * Sends the landing at most once per page lifetime, only when `effective.measurement` is true and the landing can be a touch (a
22
+ * `utm_*` or click-id parameter, or a non-empty cross-origin referrer). With `measurement` false it does nothing and stays able to
23
+ * send on a later `flush` (undecided). A rejected `send` is swallowed and never retried.
24
+ */
25
+ flush(effective: Record<Purpose, boolean>): void;
26
+ /** On an explicit refusal (§6.2): every later `flush` of this page does nothing; the navigation entry is never read again. */
27
+ discard(): void;
28
+ }
29
+ /**
30
+ * The capture; `send` is the frontend's own transport to its server entry point (`recordLandingRoute` or `recordLandingAction`).
31
+ * Call `flush`/`discard` only from effects or event handlers, never during render.
32
+ */
33
+ export declare function createAttributionCapture({ send }: {
34
+ send: (landing: AttributionLanding) => Promise<void>;
35
+ }): AttributionCapture;
@@ -0,0 +1,63 @@
1
+ import { stageA } from "./codec.js";
2
+ // Page lifetime = this module's lifetime: a second capture (a remount, React's double effects) shares the flags.
3
+ let sent = false;
4
+ let discarded = false;
5
+ /** The landing from the navigation entry and `document.referrer`, or null when the entry (or the API) is unavailable. */
6
+ function readLanding() {
7
+ try {
8
+ const entry = globalThis.performance?.getEntriesByType?.("navigation")?.[0];
9
+ if (entry === undefined || typeof entry.name !== "string" || entry.name === "")
10
+ return null;
11
+ const referrer = globalThis.document?.referrer;
12
+ return { href: entry.name, referrer: typeof referrer === "string" ? referrer : "" };
13
+ }
14
+ catch {
15
+ return null;
16
+ }
17
+ }
18
+ // Comparing two URLs' origins: an opaque "null" on both sides only means neither is a readable http(s) URL (stage A then gives no host).
19
+ function originOf(url) {
20
+ try {
21
+ return new URL(url).origin;
22
+ }
23
+ catch {
24
+ return null;
25
+ }
26
+ }
27
+ /**
28
+ * The send filter: the landing can be a touch. Built on stage A so it reads the URL exactly as the server will: a known `utm_*`
29
+ * value or a click-id parameter, or a readable http(s) referrer whose origin is not the landing's own.
30
+ */
31
+ function canBeTouch(landing) {
32
+ const parts = stageA(landing.href, landing.referrer === "" ? null : landing.referrer);
33
+ if (parts.source !== null || parts.medium !== null || parts.campaign !== null || parts.content !== null || parts.term !== null)
34
+ return true;
35
+ if (parts.clickIdKind !== null)
36
+ return true;
37
+ return parts.referrerHost !== null && originOf(landing.referrer) !== originOf(landing.href);
38
+ }
39
+ /**
40
+ * The capture; `send` is the frontend's own transport to its server entry point (`recordLandingRoute` or `recordLandingAction`).
41
+ * Call `flush`/`discard` only from effects or event handlers, never during render.
42
+ */
43
+ export function createAttributionCapture({ send }) {
44
+ return {
45
+ flush(effective) {
46
+ if (sent || discarded || effective?.measurement !== true)
47
+ return;
48
+ const landing = readLanding();
49
+ if (landing === null || !canBeTouch(landing))
50
+ return;
51
+ sent = true;
52
+ try {
53
+ void Promise.resolve(send(landing)).catch(() => { });
54
+ }
55
+ catch {
56
+ // A transport that throws synchronously changes nothing; the landing is not retried.
57
+ }
58
+ },
59
+ discard() {
60
+ discarded = true;
61
+ },
62
+ };
63
+ }