@asstio-dev/storefront 0.46.0 → 0.48.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.
@@ -7,12 +7,16 @@
7
7
  *
8
8
  * Next.js sets cookies only in server actions, route handlers and middleware. A server-component render that meets
9
9
  * `SESSION_INVALID` renders signed-out and leaves clearing the cookie to the next action (`signOutAction` clears it).
10
+ *
11
+ * Node runtime only: importing this module loads `node:crypto` (the consent owner of a shopper token is a sha256 prefix), so it does
12
+ * not run on the Edge runtime. Wrap the shopper actions in the browser with `withShopperLock` from `account/browser`.
10
13
  */
11
14
  // "next/headers.js", not "next/headers": next has no exports map, so plain Node ESM needs the file name; bundlers resolve both.
12
15
  import { cookies, headers } from "next/headers.js";
13
- import { createShopperClient, localFailure, signOut, startSignIn, switchPrincipal, verifySignIn, } from "./index.js";
16
+ import { accountResult, createShopperClient, getMe, localFailure, signOut, startSignIn, switchPrincipal, verifySignIn, } from "./index.js";
17
+ import { accountOwner, consentOwner, tokenOwner } from "../consent/server.js";
14
18
  import { copyBrowserCart, CopyBrowserCartError } from "./cart.js";
15
- import { browserCartCookie, cartCookie, cookieSecurity, readSignInCookie, sessionCookie, signInCookie, } from "./cookies.js";
19
+ import { browserCartCookie, cartCookie, cookieSecurity, readSignInCookie, sessionCookie, shopperCookie, signInCookie, } from "./cookies.js";
16
20
  import { safeReturnPath, shopperIpFrom } from "./security.js";
17
21
  async function context(config) {
18
22
  const jar = await cookies();
@@ -104,8 +108,10 @@ export async function switchPrincipalAction(config, principal) {
104
108
  return transition(r);
105
109
  }
106
110
  /**
107
- * Signs out (`everywhere` ends every session of the account). The session cookie, the sign-in cookie, the cart cookie and the
108
- * browser-cart cookie are cleared whatever the API answered, and also when it cannot be reached (`{ ok: false, status: 0, problem.code: "NETWORK" }`)
111
+ * Signs out (`everywhere` ends every session of the account). The session cookie, the sign-in cookie, the cart cookie, the
112
+ * browser-cart cookie and the guest shopper cookie (`__Host-sf_shopper`) are cleared whatever the API answered; the consent cookies
113
+ * are the browser's and stay (shopper-state spec §7.4: they survive sign-in and sign-out). Replay a pending consent withdrawal for
114
+ * the shopper token before calling this (S36). The cookies are cleared and also when it cannot be reached (`{ ok: false, status: 0, problem.code: "NETWORK" }`)
109
115
  * — a session already gone is still a sign-out for this browser. So every answer says `dropPrivateData: true`.
110
116
  */
111
117
  export async function signOutAction(config, opts = {}) {
@@ -126,6 +132,8 @@ export async function signOutAction(config, opts = {}) {
126
132
  set(jar, cartCookie(config.cartCookie).clear(security));
127
133
  if (read(jar, browserCartCookie.cookieName(security)))
128
134
  set(jar, browserCartCookie.clear(security));
135
+ if (read(jar, shopperCookie.cookieName(security)))
136
+ set(jar, shopperCookie.clear(security));
129
137
  }
130
138
  }
131
139
  /**
@@ -162,3 +170,280 @@ export async function shopperClient(config) {
162
170
  const { jar, security, client } = await context(config);
163
171
  return client(session(jar, security));
164
172
  }
173
+ /** 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
+ const TOKEN_GONE = new Set(["SHOPPER_TOKEN_UNKNOWN", "SHOPPER_TOKEN_ADOPTED"]);
175
+ const OWNER_MISMATCH = { ok: false, local: "owner_mismatch" };
176
+ /** The list a browser without a token has (spec §5.1: the cap is 250 for every site). */
177
+ const EMPTY_LIST = { id: null, kind: "favorites", count: 0, cap: 250, updatedAt: null };
178
+ function voidResult(r) {
179
+ return r.response.ok ? { ok: true, data: undefined } : accountResult({ ...r, data: undefined });
180
+ }
181
+ const tokenHeader = (token) => (token ? { "X-Shopper-Token": token } : {});
182
+ async function shopperContext(config) {
183
+ const ctx = await context(config);
184
+ return { ...ctx, session: session(ctx.jar, ctx.security), token: read(ctx.jar, shopperCookie.cookieName(ctx.security)) };
185
+ }
186
+ /**
187
+ * After a guest-route answer: a minted token is persisted (12 months) and any other successful write re-sets the token it sent
188
+ * (renewal); `SHOPPER_TOKEN_UNKNOWN`/`SHOPPER_TOKEN_ADOPTED` for the token it sent clear the cookie. Returns the token now held.
189
+ */
190
+ function keepToken(ctx, r, write) {
191
+ if (!r.ok) {
192
+ if (ctx.token && TOKEN_GONE.has(r.problem.code)) {
193
+ set(ctx.jar, shopperCookie.clear(ctx.security));
194
+ return null;
195
+ }
196
+ return ctx.token;
197
+ }
198
+ const minted = r.data?.shopper?.token ?? null;
199
+ const held = minted ?? ctx.token;
200
+ if (write && held)
201
+ set(ctx.jar, shopperCookie(held, ctx.security));
202
+ return held;
203
+ }
204
+ /** The guest answer with the token stripped: `shopper` = the owner of the token now held and the mint's expiry. */
205
+ function guestView(ctx, r, write) {
206
+ const held = keepToken(ctx, r, write);
207
+ if (!r.ok)
208
+ return r;
209
+ const shopper = { owner: held ? tokenOwner(held) : "none", expiresAt: r.data.shopper?.expiresAt ?? null };
210
+ return { ok: true, data: { ...r.data, shopper } };
211
+ }
212
+ /**
213
+ * The signed-in answer with `shopper` = the account's owner. When the main call succeeded but the parallel `GET /v1/me` did not, the
214
+ * data still comes back (the write happened) with `owner: null` — unresolved, never a guest or `none` owner invented for account
215
+ * work (review 2 #4); the page keeps its current owner.
216
+ */
217
+ function accountView(r, me) {
218
+ if (!r.ok)
219
+ return r;
220
+ return { ok: true, data: { ...r.data, shopper: { owner: me.ok ? accountOwner(me.data.id) : null, expiresAt: null } } };
221
+ }
222
+ function guestVoid(ctx, r) {
223
+ keepToken(ctx, r, true);
224
+ return r;
225
+ }
226
+ /**
227
+ * 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
+ * from your own `"use server"` actions. Signed in (a session cookie) they use `/v1/me/*`; as a guest the session-less `/v1/shopper/*`
229
+ * relay with the server key and `X-Shopper-Ip`. The guest token lives only in `__Host-sf_shopper` (HttpOnly, 12 months): a minting
230
+ * answer sets it, every other successful guest write renews it, `SHOPPER_TOKEN_UNKNOWN`/`SHOPPER_TOKEN_ADOPTED` clear it, and no
231
+ * result ever carries it. The actions never set a consent cookie: the browser coordinator is its one writer.
232
+ */
233
+ export function shopperActions(config) {
234
+ return {
235
+ favorites: {
236
+ /** `GET /v1/me/favorites` signed in; `GET /v1/shopper/favorites` as a guest (no token: an empty list, no request). */
237
+ async list() {
238
+ const ctx = await shopperContext(config);
239
+ if (ctx.session) {
240
+ const client = ctx.client(ctx.session);
241
+ const [r, me] = await Promise.all([client.GET("/v1/me/favorites"), getMe(client)]);
242
+ return accountView(accountResult(r), me);
243
+ }
244
+ if (!ctx.token)
245
+ return { ok: true, data: { items: [], list: { ...EMPTY_LIST }, shopper: { owner: "none", expiresAt: null } } };
246
+ return guestView(ctx, accountResult(await ctx.client(null).GET("/v1/shopper/favorites", { headers: tokenHeader(ctx.token) })), false);
247
+ },
248
+ /** `POST …/favorites/items`; as a guest without a token this mints one (persisted in the cookie, never returned). */
249
+ async add(body) {
250
+ const ctx = await shopperContext(config);
251
+ if (ctx.session) {
252
+ const client = ctx.client(ctx.session);
253
+ const [r, me] = await Promise.all([client.POST("/v1/me/favorites/items", { body }), getMe(client)]);
254
+ return accountView(accountResult(r), me);
255
+ }
256
+ return guestView(ctx, accountResult(await ctx.client(null).POST("/v1/shopper/favorites/items", { body, headers: tokenHeader(ctx.token) })), true);
257
+ },
258
+ /** `DELETE …/favorites/items/{itemId}`; a guest without a token has nothing to remove (no request). */
259
+ async remove(itemId) {
260
+ const ctx = await shopperContext(config);
261
+ const params = { path: { itemId } };
262
+ if (ctx.session)
263
+ return voidResult(await ctx.client(ctx.session).DELETE("/v1/me/favorites/items/{itemId}", { params }));
264
+ if (!ctx.token)
265
+ return { ok: true, data: undefined };
266
+ return guestVoid(ctx, voidResult(await ctx.client(null).DELETE("/v1/shopper/favorites/items/{itemId}", { params, headers: tokenHeader(ctx.token) })));
267
+ },
268
+ /** `DELETE …/favorites`; a guest without a token has nothing to clear (no request). */
269
+ async clear() {
270
+ const ctx = await shopperContext(config);
271
+ if (ctx.session)
272
+ return voidResult(await ctx.client(ctx.session).DELETE("/v1/me/favorites"));
273
+ if (!ctx.token)
274
+ return { ok: true, data: undefined };
275
+ return guestVoid(ctx, voidResult(await ctx.client(null).DELETE("/v1/shopper/favorites", { headers: tokenHeader(ctx.token) })));
276
+ },
277
+ },
278
+ watches: {
279
+ /**
280
+ * `POST /v1/me/watches` signed in (addressed to the account's own e-mail: `email` is not sent), `POST /v1/shopper/watches` as a
281
+ * guest with `email` (a watch asks for a service, so without a token this mints one: persisted in the cookie, never returned).
282
+ * `201` for a new watch, `200` for the caller's open one; `WATCH_NOT_NEEDED` (`409`) means offer add to cart instead.
283
+ */
284
+ async create(input) {
285
+ const ctx = await shopperContext(config);
286
+ const target = { kind: "variant", productId: input.productId, variantId: input.variantId };
287
+ const common = { kind: "stock", target, language: input.language ?? null, source: input.source ?? null };
288
+ if (ctx.session) {
289
+ const client = ctx.client(ctx.session);
290
+ const [r, me] = await Promise.all([client.POST("/v1/me/watches", { body: common }), getMe(client)]);
291
+ return accountView(accountResult(r), me);
292
+ }
293
+ const body = { ...common, email: input.email ?? null };
294
+ const r = await ctx.client(null).POST("/v1/shopper/watches", { body, headers: tokenHeader(ctx.token) });
295
+ return guestView(ctx, accountResult(r), true);
296
+ },
297
+ /** `GET /v1/me/watches` signed in (recipient or owner projection per watch); `GET /v1/shopper/watches` as a guest (owner
298
+ * projection; no token: an empty list, no request). */
299
+ async list() {
300
+ const ctx = await shopperContext(config);
301
+ if (ctx.session)
302
+ return accountResult(await ctx.client(ctx.session).GET("/v1/me/watches"));
303
+ if (!ctx.token)
304
+ return { ok: true, data: { items: [] } };
305
+ const r = accountResult(await ctx.client(null).GET("/v1/shopper/watches", { headers: tokenHeader(ctx.token) }));
306
+ keepToken(ctx, r, false);
307
+ return r;
308
+ },
309
+ /** `DELETE …/watches/{id}` (`204` whether or not there is such a watch); a guest without a token has nothing to cancel (no request). */
310
+ async cancel(id) {
311
+ const ctx = await shopperContext(config);
312
+ const params = { path: { id } };
313
+ if (ctx.session)
314
+ return voidResult(await ctx.client(ctx.session).DELETE("/v1/me/watches/{id}", { params }));
315
+ if (!ctx.token)
316
+ return { ok: true, data: undefined };
317
+ return guestVoid(ctx, voidResult(await ctx.client(null).DELETE("/v1/shopper/watches/{id}", { params, headers: tokenHeader(ctx.token) })));
318
+ },
319
+ /**
320
+ * `POST /v1/me/watches/stop-all`: stop every watch addressed to the account's own e-mail and watch mail to it for 12 months.
321
+ * Session only (signed out: `SESSION_REQUIRED`, no request). The mail's cancel link is `cancelWatchByToken` in
322
+ * `@asstio-dev/storefront/shopper`, with the publishable key: these actions hold the server key.
323
+ */
324
+ async stopAll() {
325
+ const ctx = await shopperContext(config);
326
+ if (!ctx.session)
327
+ return localFailure("SESSION_REQUIRED", "Stopping all watches needs a signed-in shopper.");
328
+ return voidResult(await ctx.client(ctx.session).POST("/v1/me/watches/stop-all"));
329
+ },
330
+ },
331
+ shopperState: {
332
+ /**
333
+ * `GET /v1/shopper` with the token, **always on the guest route and without the session** (the "keep my list" prompt reads it
334
+ * while signed in). No token: `{ shopper: null }` without a request.
335
+ */
336
+ async read() {
337
+ const ctx = await shopperContext(config);
338
+ if (!ctx.token)
339
+ return { ok: true, data: { shopper: null } };
340
+ const r = accountResult(await ctx.client(null).GET("/v1/shopper", { headers: tokenHeader(ctx.token) }));
341
+ keepToken(ctx, r, false);
342
+ return r;
343
+ },
344
+ /**
345
+ * `DELETE /v1/shopper` with the token, always on the guest route and without the session; then the shopper cookie is cleared.
346
+ * `{ erased: true }` tells the page to call `coordinator.erased()`, which clears the consent cookie.
347
+ */
348
+ async erase() {
349
+ 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;
356
+ }
357
+ set(ctx.jar, shopperCookie.clear(ctx.security));
358
+ return { ok: true, data: { erased: true } };
359
+ },
360
+ },
361
+ consent: {
362
+ /** `GET /v1/me/consents` signed in (feed `coordinator.setAccount(current, true)`), `GET /v1/shopper/consents` as a guest. */
363
+ async read() {
364
+ const ctx = await shopperContext(config);
365
+ if (ctx.session)
366
+ return accountResult(await ctx.client(ctx.session).GET("/v1/me/consents"));
367
+ const r = accountResult(await ctx.client(null).GET("/v1/shopper/consents", { headers: tokenHeader(ctx.token) }));
368
+ keepToken(ctx, r, false);
369
+ return r;
370
+ },
371
+ /** A further history page: `GET /v1/me/consents/history` or `GET /v1/shopper/consents/history`. */
372
+ async history(cursor) {
373
+ const ctx = await shopperContext(config);
374
+ const params = { query: cursor === undefined ? {} : { cursor } };
375
+ if (ctx.session)
376
+ return accountResult(await ctx.client(ctx.session).GET("/v1/me/consents/history", { params }));
377
+ const r = accountResult(await ctx.client(null).GET("/v1/shopper/consents/history", { params, headers: tokenHeader(ctx.token) }));
378
+ keepToken(ctx, r, false);
379
+ return r;
380
+ },
381
+ /**
382
+ * Every consent submission (a decision, a re-send, a replay, a compensation) with the owner the coordinator captured for it; the
383
+ * action writes only for that owner, never for "whoever is signed in now" (PL9):
384
+ * - `a.X`: only under a session whose account (`GET /v1/me`) is X → `PUT /v1/me/consents`, no shopper token;
385
+ * - `t.P`: only when `__Host-sf_shopper` holds the token whose hash prefix is P → `PUT /v1/shopper/consents` with it and no
386
+ * session, also while signed in;
387
+ * - `none`: only with `mayMint: true` (a fresh decision) while there is no session and no shopper cookie → the tokenless guest
388
+ * `PUT`, which mints: the token is persisted and the result's `shopper.owner` is the new `t.` owner that binds this decision.
389
+ * Anything else sends nothing: `{ ok: false, local: "owner_mismatch" }`. The action never sets a consent cookie.
390
+ */
391
+ async put(body, owner, opts = {}) {
392
+ 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);
408
+ }
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);
411
+ }
412
+ return OWNER_MISMATCH;
413
+ },
414
+ },
415
+ /**
416
+ * The "keep my list" action after a sign-in (spec §4.4; never automatic): `POST /v1/me/adopt-shopper-state` with the cookie's token
417
+ * in the body, under the session. `200` clears the shopper cookie (so do `SHOPPER_TOKEN_UNKNOWN`/`SHOPPER_TOKEN_ADOPTED`); the
418
+ * answer's `accountConsent` lets the page ask on the account. No shopper cookie: `null`, no request. Signed out: `SESSION_REQUIRED`.
419
+ */
420
+ async adopt() {
421
+ const ctx = await shopperContext(config);
422
+ if (!ctx.session)
423
+ return localFailure("SESSION_REQUIRED", "Adopting guest state needs a signed-in shopper.");
424
+ if (!ctx.token)
425
+ return { ok: true, data: null };
426
+ const r = accountResult(await ctx.client(ctx.session).POST("/v1/me/adopt-shopper-state", { body: { token: ctx.token } }));
427
+ if (r.ok)
428
+ set(ctx.jar, shopperCookie.clear(ctx.security));
429
+ else
430
+ keepToken(ctx, r, false);
431
+ return r;
432
+ },
433
+ /**
434
+ * The consent owner for the coordinator (PL9): `a.<account>` under a session (read with `GET /v1/me`; a `401` counts as signed
435
+ * out), else `t.<sha256 prefix>` when the shopper cookie exists, else `none`.
436
+ */
437
+ async owner() {
438
+ const ctx = await shopperContext(config);
439
+ if (ctx.session) {
440
+ const me = await getMe(ctx.client(ctx.session));
441
+ if (me.ok)
442
+ return { ok: true, data: accountOwner(me.data.id) };
443
+ if (me.status !== 401)
444
+ return me;
445
+ }
446
+ return { ok: true, data: consentOwner(ctx.jar, null, { origin: config.origin }) };
447
+ },
448
+ };
449
+ }
@@ -2,14 +2,20 @@ import type { Client } from "openapi-fetch";
2
2
  import type { components } from "../schema";
3
3
  import type { StorefrontPaths } from "../index.js";
4
4
  type Schemas = components["schemas"];
5
- /** One search event. `eventId` may be left out: `trackSearchEvents` writes a UUID into the object. */
5
+ /**
6
+ * One search event. `eventId` may be left out: `trackSearchEvents` writes a UUID into the object. A rendered recommendation row
7
+ * (`type: "recommendation_exposure"`, shopper-state spec §9.2) carries `resultId` (32 hex), `productIds` and `placement`
8
+ * (`pdp.similar`, `cart.complements`; trimmed and lower-cased by `trackSearchEvents`, the server wants 1–64 of `[a-z0-9_.-]`).
9
+ */
6
10
  export type SearchEvent = Omit<Schemas["SearchEventDto"], "eventId"> & {
7
11
  eventId?: string | null;
8
12
  };
9
13
  export type SearchEventsResponse = Schemas["SearchEventsResponse"];
10
14
  /**
11
15
  * `POST /v1/events` (spec 2026-10-13 §9.2). A no-op unless `consent` is exactly `true`: the storefront cannot verify
12
- * consent, so the caller decides (and sends `sessionId` only under the same consent). An event without `eventId` gets
16
+ * consent, so the caller decides — pass the coordinator's `effective().measurement` (shopper-state spec §7.4). `sessionId`
17
+ * is **deprecated**: the API accepts it within its bounds and stores nothing (shopper-state spec S31), and the SDK issues
18
+ * none; send nothing. An event without `eventId` gets
13
19
  * a UUID written into the object, so retrying the same objects after an uncertain response reuses the ids and the
14
20
  * server counts them as duplicates. Throws a `RangeError` for more than 50 events (split the batch) and an `Error` on any
15
21
  * non-2xx answer (a problem body or none). Build `occurredAt` with `new Date().toISOString()`: the server wants UTC.
@@ -2,7 +2,9 @@
2
2
  const MAX_EVENTS_PER_REQUEST = 50;
3
3
  /**
4
4
  * `POST /v1/events` (spec 2026-10-13 §9.2). A no-op unless `consent` is exactly `true`: the storefront cannot verify
5
- * consent, so the caller decides (and sends `sessionId` only under the same consent). An event without `eventId` gets
5
+ * consent, so the caller decides — pass the coordinator's `effective().measurement` (shopper-state spec §7.4). `sessionId`
6
+ * is **deprecated**: the API accepts it within its bounds and stores nothing (shopper-state spec S31), and the SDK issues
7
+ * none; send nothing. An event without `eventId` gets
6
8
  * a UUID written into the object, so retrying the same objects after an uncertain response reuses the ids and the
7
9
  * server counts them as duplicates. Throws a `RangeError` for more than 50 events (split the batch) and an `Error` on any
8
10
  * non-2xx answer (a problem body or none). Build `occurredAt` with `new Date().toISOString()`: the server wants UTC.
@@ -12,9 +14,12 @@ export async function trackSearchEvents(client, events, options) {
12
14
  return null;
13
15
  if (events.length > MAX_EVENTS_PER_REQUEST)
14
16
  throw new RangeError(`trackSearchEvents takes at most ${MAX_EVENTS_PER_REQUEST} events per call, got ${events.length}`);
15
- for (const e of events)
17
+ for (const e of events) {
16
18
  if (!e.eventId)
17
19
  e.eventId = crypto.randomUUID();
20
+ if (e.type === "recommendation_exposure" && typeof e.placement === "string")
21
+ e.placement = e.placement.trim().toLowerCase();
22
+ }
18
23
  const { data, error, response } = await client.POST("/v1/events", { body: { events: events } });
19
24
  // `error` is undefined for an empty-body 5xx (openapi-fetch parses nothing), so the status decides: a non-2xx always throws.
20
25
  if (!response.ok)
@@ -0,0 +1,38 @@
1
+ import type { Client } from "openapi-fetch";
2
+ import type { StorefrontPaths } from "./index.js";
3
+ import type { components } from "./schema";
4
+ import { type StorefrontProblem } from "./checkout/types.js";
5
+ export type CartDto = components["schemas"]["CartDto"];
6
+ export type CartLineDto = components["schemas"]["CartLineDto"];
7
+ export type CartLineSegmentDto = components["schemas"]["CartLineSegmentDto"];
8
+ export type PricePairDto = components["schemas"]["PricePairDto"];
9
+ export type CartCodeResult = {
10
+ ok: true;
11
+ data: CartDto;
12
+ } | {
13
+ ok: false;
14
+ status: number;
15
+ problem: StorefrontProblem;
16
+ retryAfter?: number;
17
+ };
18
+ export interface CartCodeOptions {
19
+ /** The cart version (ETag); a stale one is rejected with 409 CART_CONFLICT. */
20
+ ifMatch?: number;
21
+ /** Default: a fresh `crypto.randomUUID()` per call. */
22
+ idempotencyKey?: string;
23
+ /** A signed-in frontend's request-scoped shopper client; the call goes through it instead of `client`. */
24
+ shopper?: Client<StorefrontPaths> | null;
25
+ }
26
+ /** `POST /v1/cart/codes`: applies a discount code. A transport failure rejects the promise, like the checkout helpers. */
27
+ export declare function applyCode(client: Client<StorefrontPaths>, cartToken: string, code: string, opts?: CartCodeOptions): Promise<CartCodeResult>;
28
+ /** `DELETE /v1/cart/codes/{code}`: removes a discount code (the path segment is URL-encoded). */
29
+ export declare function removeCode(client: Client<StorefrontPaths>, cartToken: string, code: string, opts?: CartCodeOptions): Promise<CartCodeResult>;
30
+ export type LineUnitPrices = {
31
+ kind: "single";
32
+ unitPrice: PricePairDto;
33
+ } | {
34
+ kind: "segments";
35
+ segments: CartLineSegmentDto[];
36
+ };
37
+ /** The unit prices of a cart line: `single` when every unit costs the same (no segments, or one), else the segments. Cart lines only. */
38
+ export declare function lineUnitPrices(line: CartLineDto): LineUnitPrices;
@@ -0,0 +1,28 @@
1
+ import { localProblem, retryAfterSeconds } from "./checkout/types.js";
2
+ function headers(cartToken, opts) {
3
+ const h = { "X-Cart-Token": cartToken, "Idempotency-Key": opts.idempotencyKey ?? crypto.randomUUID() };
4
+ if (opts.ifMatch !== undefined)
5
+ h["If-Match"] = String(opts.ifMatch);
6
+ return h;
7
+ }
8
+ /** `POST /v1/cart/codes`: applies a discount code. A transport failure rejects the promise, like the checkout helpers. */
9
+ export async function applyCode(client, cartToken, code, opts = {}) {
10
+ const { data, error, response } = await (opts.shopper ?? client).POST("/v1/cart/codes", { body: { code }, headers: headers(cartToken, opts) });
11
+ if (error || !data)
12
+ return { ok: false, status: response.status, problem: (error ?? localProblem("SDK_EMPTY_ANSWER", "no body")), retryAfter: retryAfterSeconds(response) };
13
+ return { ok: true, data };
14
+ }
15
+ /** `DELETE /v1/cart/codes/{code}`: removes a discount code (the path segment is URL-encoded). */
16
+ export async function removeCode(client, cartToken, code, opts = {}) {
17
+ const { data, error, response } = await (opts.shopper ?? client).DELETE("/v1/cart/codes/{code}", { params: { path: { code } }, headers: headers(cartToken, opts) });
18
+ if (error || !data)
19
+ return { ok: false, status: response.status, problem: (error ?? localProblem("SDK_EMPTY_ANSWER", "no body")), retryAfter: retryAfterSeconds(response) };
20
+ return { ok: true, data };
21
+ }
22
+ /** The unit prices of a cart line: `single` when every unit costs the same (no segments, or one), else the segments. Cart lines only. */
23
+ export function lineUnitPrices(line) {
24
+ const segments = line.segments;
25
+ if (!segments || segments.length <= 1)
26
+ return { kind: "single", unitPrice: line.unitPrice };
27
+ return { kind: "segments", segments };
28
+ }
@@ -0,0 +1,141 @@
1
+ export type Purpose = "measurement" | "personalization";
2
+ export declare const PURPOSES: readonly Purpose[];
3
+ /** At most this many `unsynced` entries; a further key is not stored (`withEntry`). */
4
+ export declare const MAX_UNSYNCED = 8;
5
+ /** The coordinator's transport timeout: an `AbortSignal` on every `put`; a timed-out `put` is `not_saved`. */
6
+ export declare const PUT_TIMEOUT_MS = 30000;
7
+ /** A `pending` marker is abandoned once `now - startedAt > PENDING_TTL_MS` (twice `PUT_TIMEOUT_MS`). */
8
+ export declare const PENDING_TTL_MS: number;
9
+ /** The encoded main cookie's upper bound; with its name and attributes it stays below 4096. */
10
+ export declare const MAX_CONSENT_COOKIE_LENGTH = 3000;
11
+ /** The locked shape's sequence range is `[0, 2^40 - 1]`; a fallback `fence` is `S + 2^40` (PL6, S36). */
12
+ export declare const SEQ_LIMIT: number;
13
+ /** The main cookie's base name (the `__Host-` prefix is dropped on http://localhost, as for every SDK cookie). */
14
+ export declare const CONSENT_COOKIE = "sf_consent";
15
+ /** The refusal-time cookie's base name. */
16
+ export declare const CONSENT_OFF_COOKIE = "sf_consent_off";
17
+ /** The main cookie lives 12 months. */
18
+ export declare const CONSENT_COOKIE_SECONDS: number;
19
+ /** The refusal cookie lives 400 days, the browser maximum (PL6). */
20
+ export declare const CONSENT_OFF_COOKIE_SECONDS: number;
21
+ /** The two consent cookie names for the frontend's origin. */
22
+ export declare function consentCookieNames(origin?: string | URL): {
23
+ consent: string;
24
+ off: string;
25
+ };
26
+ export type PurposeState = {
27
+ state: "granted" | "withdrawn" | "unset";
28
+ seq: number;
29
+ /** The decision time, set when the decision is allocated; never refreshed by answers, retries or recovery. */
30
+ at: number;
31
+ /**
32
+ * A `granted` state only: the refusal mark the grant observed when it was decided; absent when there was no refusal cookie then.
33
+ * The grant counts only while the current refusal cookie carries the same mark (absent ↔ absent).
34
+ */
35
+ off?: string;
36
+ /**
37
+ * A grant submitted and not yet answered: its allocated `seq`, its decision time, the owner it was submitted for, the time the
38
+ * request was handed to the transport and the refusal mark it observed when it was decided (absent: none). The state stays what it
39
+ * was until the answer.
40
+ */
41
+ pending?: {
42
+ seq: number;
43
+ at: number;
44
+ owner: string;
45
+ startedAt: number;
46
+ off?: string;
47
+ };
48
+ };
49
+ /** A withdrawal not yet acknowledged by the server. Its key is `(site, purpose, owner)`. */
50
+ export type UnsyncedEntry = {
51
+ site: string;
52
+ purpose: Purpose;
53
+ owner: string;
54
+ device: string;
55
+ seq: number;
56
+ };
57
+ export type LockedConsentCookie = {
58
+ v: 1;
59
+ device: string;
60
+ seq: number;
61
+ purposes: Partial<Record<Purpose, PurposeState>>;
62
+ ref: string | null;
63
+ at: number;
64
+ unsynced: UnsyncedEntry[];
65
+ overflow: number;
66
+ };
67
+ export type FallbackConsentCookie = {
68
+ v: 1;
69
+ fallback: true;
70
+ device: string;
71
+ fence: number;
72
+ fencedAt: number;
73
+ unsynced: UnsyncedEntry[];
74
+ overflow: number;
75
+ };
76
+ export type ConsentCookie = LockedConsentCookie | FallbackConsentCookie;
77
+ /** What `parseRefusal` gives: the latest refusal's time and mark, `"malformed"` (deny every grant), or null (no refusal cookie). */
78
+ export type Refusal = {
79
+ at: number;
80
+ mark: string;
81
+ } | "malformed" | null;
82
+ export declare class ConsentCookieTooLarge extends Error {
83
+ readonly length: number;
84
+ constructor(length: number);
85
+ }
86
+ export declare const isFallback: (c: ConsentCookie) => c is FallbackConsentCookie;
87
+ /**
88
+ * The main cookie's value back, or null for a missing value and for **any** shape error: a missing `"1."` prefix, bad base64url or
89
+ * JSON, an unknown `v`, a device that is not 32 lowercase hex, a sequence outside `[0, 2^40 - 1]` (locked shape) or a fence outside
90
+ * `[2^40, 2^41 - 1]` (fallback), a time that is not a positive integer, an unknown purpose, a bad site, an `unsynced` owner that is
91
+ * not `t.<16 hex>`/`a.<32 hex>`, a `pending.owner` that is not one of those or `none`, an `off` mark that is not 16 lowercase hex
92
+ * (or one on a state that is not `granted`), more than `MAX_UNSYNCED` entries.
93
+ */
94
+ export declare function parseConsent(raw: string | undefined): ConsentCookie | null;
95
+ /**
96
+ * The refusal cookie's value back: `{ at, mark }`, `"malformed"` for a present value that is not
97
+ * `"1." + <positive integer ms> + "." + <16 lowercase hex>`, null when absent.
98
+ */
99
+ export declare function parseRefusal(raw: string | undefined): Refusal;
100
+ /** The refusal cookie's value for a refusal. Every refusal passes a fresh random `mark` (16 lowercase hex), never a reused one. */
101
+ export declare function serializeRefusal(r: {
102
+ at: number;
103
+ mark: string;
104
+ }): string;
105
+ /** The mark of a refusal cookie, or undefined when there is none (null) — and for a malformed one, which blocks every grant anyway. */
106
+ export declare function refusalMark(off: Refusal): string | undefined;
107
+ /**
108
+ * True when the refusal cookie blocks a grant decided at `at` that observed refusal mark `mark` (undefined: no refusal cookie then):
109
+ * a malformed refusal; a current mark other than the observed one (absent ↔ absent); or a decision not later than the refusal time.
110
+ */
111
+ export declare function refusalBlocks(off: Refusal, at: number, mark: string | undefined): boolean;
112
+ /** The main cookie's value. Throws `ConsentCookieTooLarge` above `MAX_CONSENT_COOKIE_LENGTH` characters. */
113
+ export declare function serializeConsent(c: ConsentCookie): string;
114
+ /**
115
+ * Stores a withdrawal's `unsynced` entry. The same `(site, purpose, owner)` key replaces the old entry (a newer decision supersedes
116
+ * it); a new key is appended while fewer than `MAX_UNSYNCED` exist. At capacity nothing is dropped: the cookie comes back with
117
+ * `overflow + 1` and `stored: false` (the refusal itself is already in `purposes`; the caller reports `not_saved`).
118
+ */
119
+ export declare function withEntry<C extends ConsentCookie>(c: C, entry: UnsyncedEntry): {
120
+ cookie: C;
121
+ stored: boolean;
122
+ };
123
+ /**
124
+ * Removes the entries `pred` selects — only for the spec's reasons: an acknowledgement (match the full identity), a grant of the same
125
+ * `(site, purpose, owner)` when it is allocated, the adoption of that token, `404 SHOPPER_TOKEN_UNKNOWN` for that token. Freeing
126
+ * room resets `overflow` to 0.
127
+ */
128
+ export declare function withoutEntries<C extends ConsentCookie>(c: C, pred: (e: UnsyncedEntry) => boolean): C;
129
+ /**
130
+ * The one comparison (S30, S36): granted iff the cookie is the locked shape, the purpose is `granted`, the refusal mark it observed
131
+ * is still the current one (no refusal cookie then and now, or the same mark), and its decision time is later than the refusal time.
132
+ * A fallback value, a missing or unparsable cookie, a malformed refusal, another mark → false.
133
+ */
134
+ export declare function grantedFor(c: ConsentCookie | null, off: Refusal, purpose: Purpose): boolean;
135
+ /**
136
+ * Folds the refusal into the main cookie (round-11 notes 1, 2; review #1): every `granted` purpose the refusal blocks
137
+ * (`refusalBlocks`: decided at or before it, or under another mark; every one when the refusal is malformed) becomes `withdrawn`,
138
+ * keeping its `seq` and `at` (its mark is dropped); a `pending` grant the refusal blocks loses its `pending`. Nothing else changes,
139
+ * so a later loss of the refusal cookie cannot revive a grant.
140
+ */
141
+ export declare function fold<C extends ConsentCookie>(c: C, off: Refusal): C;