@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.
@@ -0,0 +1,239 @@
1
+ /**
2
+ * `@asstio-dev/storefront/attribution/next` — the server half of order attribution capture (order attribution spec §6.2–§6.5):
3
+ * `recordLanding` and its two thin entry points (a route handler, the recommended one, and a Server Action, which re-renders the
4
+ * page), `readAttribution` and `attributionForCheckout`. Server code only, Node runtime (`next/headers`; the consent readers load
5
+ * `node:crypto`). The browser half is `createAttributionCapture` in `@asstio-dev/storefront/attribution`.
6
+ *
7
+ * Every helper is inert without an enabled `site.attribution` block: no cookie is written, `recordLanding` deletes an existing
8
+ * `__Host-sf_attr`, and `attributionForCheckout` returns no member and no token. A `measurement` grant whose recorded notice `ref`
9
+ * decodes below `minNoticeVersion` counts as not granted here (for attribution only; the consent state is untouched).
10
+ *
11
+ * `attributionForCheckout`'s `shopperToken` is a credential: hand the result straight to `startCheckout`/`syncCheckout` in the same
12
+ * server code and never return it to a client component.
13
+ */
14
+ // "next/headers.js", not "next/headers": next has no exports map, so plain Node ESM needs the file name; bundlers resolve both.
15
+ import { cookies } from "next/headers.js";
16
+ import { attrCookie, cookieSecurity, shopperCookie } from "../account/cookies.js";
17
+ import { readConsentCookie } from "../consent/server.js";
18
+ import { noticeVersion } from "../consent/notice.js";
19
+ import { mergeLanding, parseAttr, PROVIDER_HOSTS, serializeAttr, stageA, touches } from "./codec.js";
20
+ /** A landing body above this many characters is refused (a URL plus a referrer stay far below it). */
21
+ const MAX_LANDING_BODY = 16_384;
22
+ const int = (v) => {
23
+ const n = typeof v === "string" && v.trim() !== "" ? Number(v) : v;
24
+ return typeof n === "number" && Number.isSafeInteger(n) ? n : null;
25
+ };
26
+ /** The site's enabled block, or null: absent, disabled, or (fail closed, §5.4) enabled without a floor. */
27
+ function enabledBlock(site) {
28
+ const a = site.attribution;
29
+ if (!a || a.enabled !== true)
30
+ return null;
31
+ const floor = int(a.minNoticeVersion);
32
+ const lookbackDays = int(a.lookbackDays);
33
+ if (floor === null || floor < 1 || lookbackDays === null || lookbackDays < 1)
34
+ return null;
35
+ return {
36
+ lookbackDays, floor,
37
+ ignoreReferrerHosts: a.ignoreReferrerHosts ?? [], dropPaths: a.dropPaths ?? [], checkoutPaths: a.checkoutPaths ?? [],
38
+ keepContent: a.touches?.content === true, keepTerm: a.touches?.term === true,
39
+ };
40
+ }
41
+ /**
42
+ * The device's `measurement` decision time when it grants `measurement` with a recorded notice at or above the floor, else null.
43
+ * The cookie keeps one `ref` (its latest applied grant's notice); the server checks the record's own notice version (§5.2).
44
+ */
45
+ function grantAbove(cookies, origin, floor) {
46
+ const reading = readConsentCookie(cookies, { origin });
47
+ const at = reading.decidedAt("measurement");
48
+ if (at === null || reading.ref === null)
49
+ return null;
50
+ const version = noticeVersion(reading.ref);
51
+ return version !== null && version >= floor ? at : null;
52
+ }
53
+ const hostOf = (url) => {
54
+ try {
55
+ return new URL(url).hostname.toLowerCase() || null;
56
+ }
57
+ catch {
58
+ return null;
59
+ }
60
+ };
61
+ // Unlike browser.ts's helper, an opaque origin ("null") maps to null here so an `Origin: null` header never matches an allowed origin.
62
+ const originOf = (url) => {
63
+ try {
64
+ const o = new URL(url).origin;
65
+ return o === "null" ? null : o;
66
+ }
67
+ catch {
68
+ return null;
69
+ }
70
+ };
71
+ /** Own hosts: the hosts of `site.bindings[].origin` plus the frontend's own origin (a dev or preview origin outside the bindings). */
72
+ function ownHosts(site, origin) {
73
+ const hosts = [...(site.bindings ?? []).map((b) => b.origin), origin].map(hostOf).filter((h) => h !== null);
74
+ return [...new Set(hosts)];
75
+ }
76
+ function context(block, site, origin, now) {
77
+ return {
78
+ nowUtc: now, lookbackDays: block.lookbackDays, ownHosts: ownHosts(site, origin), ignoreReferrerHosts: block.ignoreReferrerHosts,
79
+ providerHosts: [...PROVIDER_HOSTS], dropPaths: block.dropPaths, checkoutPaths: block.checkoutPaths,
80
+ keepContent: block.keepContent, keepTerm: block.keepTerm,
81
+ };
82
+ }
83
+ const isLanding = (v) => typeof v === "object" && v !== null && typeof v.href === "string" && typeof v.referrer === "string"
84
+ && v.href.length + v.referrer.length <= MAX_LANDING_BODY;
85
+ /**
86
+ * 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
87
+ * site's own hosts, ignored hosts and paths, server time) and merges it into `__Host-sf_attr` under the device's current
88
+ * `measurement` grant. A direct landing changes nothing. Without an enabled block, or without a grant at or above the floor, it
89
+ * deletes an existing cookie and writes nothing. `opts.origin` is the frontend's own origin (its host counts as an own host).
90
+ */
91
+ export function recordLanding(cookies, landing, site, opts) {
92
+ const security = cookieSecurity(opts.origin);
93
+ const held = cookies.get(attrCookie.cookieName(security))?.value;
94
+ const clear = () => {
95
+ if (held !== undefined)
96
+ cookies.set(attrCookie.clear(security));
97
+ };
98
+ const block = enabledBlock(site);
99
+ if (block === null)
100
+ return clear();
101
+ const grantAt = grantAbove(cookies, opts.origin, block.floor);
102
+ if (grantAt === null)
103
+ return clear();
104
+ if (!isLanding(landing))
105
+ return;
106
+ const now = opts.now ?? Date.now();
107
+ const raw = { ...stageA(landing.href, landing.referrer === "" ? null : landing.referrer), at: new Date(now).toISOString() };
108
+ const state = parseAttr(held);
109
+ const [touch] = touches([raw], context(block, site, opts.origin, now)).kept;
110
+ if (touch === undefined) {
111
+ // Direct, or dropped by the site's rules: no new touch. A cookie collected under another grant, or unreadable, goes now.
112
+ if (held !== undefined && (state === null || state.grantAt !== grantAt))
113
+ clear();
114
+ return;
115
+ }
116
+ const merged = mergeLanding(state, touch, { lookbackDays: block.lookbackDays, grantAt }, now);
117
+ if (merged === null)
118
+ return clear();
119
+ cookies.set(attrCookie(serializeAttr(merged), { ...security, lookbackDays: block.lookbackDays }));
120
+ }
121
+ /**
122
+ * The body as text, read chunk by chunk up to `limit` bytes in all; null as soon as it exceeds them, with the stream cancelled at
123
+ * that point (a chunked body without `Content-Length` is never buffered whole). A read error throws.
124
+ */
125
+ async function readCapped(req, limit) {
126
+ if (req.body === null)
127
+ return "";
128
+ const reader = req.body.getReader();
129
+ const chunks = [];
130
+ let total = 0;
131
+ for (;;) {
132
+ const { done, value } = await reader.read();
133
+ if (done)
134
+ break;
135
+ total += value.byteLength;
136
+ if (total > limit) {
137
+ // Not awaited: the source's cancel runs now, and a slow one must not hold the 413.
138
+ reader.cancel().catch(() => { });
139
+ return null;
140
+ }
141
+ chunks.push(value);
142
+ }
143
+ const bytes = new Uint8Array(total);
144
+ let at = 0;
145
+ for (const c of chunks) {
146
+ bytes.set(c, at);
147
+ at += c.byteLength;
148
+ }
149
+ return new TextDecoder().decode(bytes);
150
+ }
151
+ /**
152
+ * A `POST` route handler around `recordLanding` (the recommended entry point: setting a cookie in a Server Action re-renders the
153
+ * page). The browser posts `{ href, referrer }` as JSON. `Origin` must be `opts.origin` or one of the site's binding origins (403
154
+ * 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
155
+ * cancelled there); a malformed body is 400; success is 204. `getSite` returns the frontend's
156
+ * cached `/v1/site` answer.
157
+ *
158
+ * ```ts
159
+ * // app/api/attribution/route.ts
160
+ * export const POST = recordLandingRoute(getSite, { origin: process.env.SHOP_ORIGIN! });
161
+ * ```
162
+ */
163
+ export function recordLandingRoute(getSite, opts) {
164
+ return async (req) => {
165
+ if (req.method !== "POST")
166
+ return new Response(null, { status: 405, headers: { Allow: "POST" } });
167
+ const from = req.headers.get("Origin");
168
+ const caller = from === null ? null : originOf(from);
169
+ if (caller === null)
170
+ return new Response(null, { status: 403 });
171
+ // The frontend's own origin first; the site (for its binding origins) only when that does not match.
172
+ let site = null;
173
+ if (caller !== originOf(opts.origin)) {
174
+ site = await getSite();
175
+ if (!(site.bindings ?? []).some((b) => originOf(b.origin) === caller))
176
+ return new Response(null, { status: 403 });
177
+ }
178
+ if (Number(req.headers.get("Content-Length") ?? 0) > MAX_LANDING_BODY)
179
+ return new Response(null, { status: 413 });
180
+ let landing;
181
+ try {
182
+ const text = await readCapped(req, MAX_LANDING_BODY);
183
+ if (text === null)
184
+ return new Response(null, { status: 413 });
185
+ landing = JSON.parse(text);
186
+ }
187
+ catch {
188
+ landing = null;
189
+ }
190
+ if (!isLanding(landing))
191
+ return new Response(null, { status: 400 });
192
+ recordLanding(await cookies(), landing, site ?? (await getSite()), { origin: opts.origin });
193
+ return new Response(null, { status: 204 });
194
+ };
195
+ }
196
+ /**
197
+ * A Server Action body around `recordLanding`: wrap it in your own `"use server"` function. It works, but setting the cookie in an
198
+ * action re-renders the current page (A2 spike); prefer `recordLandingRoute`. A malformed landing is ignored.
199
+ */
200
+ export function recordLandingAction(getSite, opts) {
201
+ return async (landing) => {
202
+ if (!isLanding(landing))
203
+ return;
204
+ const site = await getSite();
205
+ recordLanding(await cookies(), landing, site, { origin: opts.origin });
206
+ };
207
+ }
208
+ /**
209
+ * The device's touches (§6.5): null without an enabled block or without a `measurement` grant at or above the floor; `[]` when it
210
+ * grants and the cookie is missing, unreadable or collected under another grant; else the cookie's touches.
211
+ */
212
+ export function readAttribution(cookies, site, opts) {
213
+ const block = enabledBlock(site);
214
+ if (block === null)
215
+ return null;
216
+ const grantAt = grantAbove(cookies, opts.origin, block.floor);
217
+ if (grantAt === null)
218
+ return null;
219
+ const state = parseAttr(cookies.get(attrCookie.cookieName(cookieSecurity(opts.origin)))?.value);
220
+ return state !== null && state.grantAt === grantAt ? state.touches : [];
221
+ }
222
+ /**
223
+ * What to pass `startCheckout`/`syncCheckout` (§6.4, D30). No `attribution` member without an enabled block. `touches` as
224
+ * `readAttribution` reads them (null when the device does not grant `measurement` at or above the floor). `shopperToken` (the
225
+ * `__Host-sf_shopper` cookie) only without a session, with the block enabled and the device granting above the floor.
226
+ *
227
+ * The token is a credential: hand the result straight to the checkout call in the same server code; never return it (or this
228
+ * object) to a client component.
229
+ */
230
+ export async function attributionForCheckout(site, opts) {
231
+ if (enabledBlock(site) === null)
232
+ return {};
233
+ const jar = await cookies();
234
+ const found = readAttribution(jar, site, { origin: opts.origin });
235
+ if (found === null)
236
+ return { attribution: { touches: null } };
237
+ const token = opts.session ? null : jar.get(shopperCookie.cookieName(cookieSecurity(opts.origin)))?.value || null;
238
+ return token ? { attribution: { touches: found }, shopperToken: token } : { attribution: { touches: found } };
239
+ }
@@ -36,3 +36,6 @@ export type LineUnitPrices = {
36
36
  };
37
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
38
  export declare function lineUnitPrices(line: CartLineDto): LineUnitPrices;
39
+ /** The default text of a discount code's reason (`PromotionCodeReasonDto`): `sv` or English. An unknown reason reads as
40
+ * `unavailable`. */
41
+ export declare function codeReasonText(reason: string, locale: string): string;
@@ -1,4 +1,5 @@
1
1
  import { localProblem, retryAfterSeconds } from "./checkout/types.js";
2
+ import { language } from "./price-display.js";
2
3
  function headers(cartToken, opts) {
3
4
  const h = { "X-Cart-Token": cartToken, "Idempotency-Key": opts.idempotencyKey ?? crypto.randomUUID() };
4
5
  if (opts.ifMatch !== undefined)
@@ -26,3 +27,27 @@ export function lineUnitPrices(line) {
26
27
  return { kind: "single", unitPrice: line.unitPrice };
27
28
  return { kind: "segments", segments };
28
29
  }
30
+ const CODE_REASONS = {
31
+ sv: {
32
+ expired: "Koden har gått ut",
33
+ notForAccount: "Koden gäller inte för ditt konto",
34
+ notInMarket: "Koden gäller inte här",
35
+ notStarted: "Koden gäller inte än",
36
+ superseded: "Ett bättre erbjudande gäller redan",
37
+ unavailable: "Koden kan inte användas",
38
+ },
39
+ en: {
40
+ expired: "The code has expired",
41
+ notForAccount: "The code is not valid for your account",
42
+ notInMarket: "The code is not valid here",
43
+ notStarted: "The code is not valid yet",
44
+ superseded: "A better offer already applies",
45
+ unavailable: "The code cannot be used",
46
+ },
47
+ };
48
+ /** The default text of a discount code's reason (`PromotionCodeReasonDto`): `sv` or English. An unknown reason reads as
49
+ * `unavailable`. */
50
+ export function codeReasonText(reason, locale) {
51
+ const texts = CODE_REASONS[language(locale)];
52
+ return Object.hasOwn(texts, reason) ? texts[reason] : texts.unavailable;
53
+ }
@@ -11,11 +11,16 @@ export type CheckoutClient = Client<StorefrontPaths>;
11
11
  export interface ShopperOption {
12
12
  shopper?: CheckoutClient | null;
13
13
  }
14
+ type CheckoutRequest = NonNullable<StorefrontPaths["/v1/checkout"]["post"]["requestBody"]>["content"]["application/json"];
14
15
  export interface StartCheckoutOptions extends ShopperOption {
15
16
  /** One of `GET /v1/site` → `markets[].checkout.options[].key`; omit for the market's default. */
16
17
  option?: string;
17
18
  /** Replaces the market's origin in the URLs handed to the provider; must be one of the site's allowed origins. */
18
19
  returnOrigin?: string;
20
+ /** Order attribution capture (spec §6.5): spread `attributionForCheckout(...)` from `@asstio-dev/storefront/attribution/next`. Sent as the body member only when given; omitted = "no change". */
21
+ attribution?: NonNullable<CheckoutRequest>["attribution"];
22
+ /** The guest shopper token for the attribution grant check. Sent as `X-Shopper-Token` only when `shopper` is absent or null (a session never carries it). A credential: server code only. */
23
+ shopperToken?: string;
19
24
  }
20
25
  export interface SyncRetryOptions {
21
26
  sleep?: (ms: number) => Promise<void>;
@@ -48,3 +53,4 @@ export interface AwaitCompletionOptions {
48
53
  }
49
54
  /** Polls `complete` with doubling backoff until the attempt has an order or is closed, or the timeout passes (the last answer is returned either way). */
50
55
  export declare function awaitCompletion(complete: () => Promise<StatusResult>, opts?: AwaitCompletionOptions): Promise<StatusResult>;
56
+ export {};
@@ -4,8 +4,8 @@ const defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
4
4
  /** `POST /v1/checkout`: creates the cart's attempt or converges on the live one (spec §5.3). Call it from a Server Action or route handler, never during render. */
5
5
  export async function startCheckout(client, cartToken, opts = {}) {
6
6
  const { data, error, response } = await via(client, opts).POST("/v1/checkout", {
7
- body: { option: opts.option ?? null, returnOrigin: opts.returnOrigin ?? null },
8
- headers: { "X-Cart-Token": cartToken },
7
+ body: { option: opts.option ?? null, returnOrigin: opts.returnOrigin ?? null, ...(opts.attribution !== undefined ? { attribution: opts.attribution } : {}) },
8
+ headers: { "X-Cart-Token": cartToken, ...(opts.shopperToken && !opts.shopper ? { "X-Shopper-Token": opts.shopperToken } : {}) },
9
9
  });
10
10
  const retryAfter = retryAfterSeconds(response);
11
11
  if (error || !data)
@@ -4,5 +4,5 @@
4
4
  * `createConsentCoordinator` throws without `window`. The server readers are in `@asstio-dev/storefront/consent/server`.
5
5
  */
6
6
  export { CONSENT_COOKIE, CONSENT_COOKIE_SECONDS, CONSENT_OFF_COOKIE, CONSENT_OFF_COOKIE_SECONDS, ConsentCookieTooLarge, consentCookieNames, fold, grantedFor, isFallback, MAX_CONSENT_COOKIE_LENGTH, MAX_UNSYNCED, MAX_UNSYNCED_READ, parseConsent, parseRefusal, PENDING_TTL_MS, PURPOSES, refusalBlocks, refusalMark, PUT_TIMEOUT_MS, SEQ_LIMIT, serializeConsent, serializeRefusal, withEntry, withoutEntries, withoutOwner, type ConsentCookie, type FallbackConsentCookie, type LockedConsentCookie, type Purpose, type PurposeState, type Refusal, type UnsyncedEntry, } from "./codec.js";
7
- export { consentNotice, type ConsentNoticeDto } from "./notice.js";
7
+ export { consentNotice, noticeVersion, type ConsentNoticeDto } from "./notice.js";
8
8
  export { createConsentCoordinator, type AccountConsentRecord, type ConsentCoordinator, type ConsentCoordinatorOptions, type ConsentDecision, type ConsentPutBody, type ConsentTransport, type CookieJar, type SetResult, type SetStatus, type TransportAnswer, } from "./coordinator.js";
@@ -4,5 +4,5 @@
4
4
  * `createConsentCoordinator` throws without `window`. The server readers are in `@asstio-dev/storefront/consent/server`.
5
5
  */
6
6
  export { CONSENT_COOKIE, CONSENT_COOKIE_SECONDS, CONSENT_OFF_COOKIE, CONSENT_OFF_COOKIE_SECONDS, ConsentCookieTooLarge, consentCookieNames, fold, grantedFor, isFallback, MAX_CONSENT_COOKIE_LENGTH, MAX_UNSYNCED, MAX_UNSYNCED_READ, parseConsent, parseRefusal, PENDING_TTL_MS, PURPOSES, refusalBlocks, refusalMark, PUT_TIMEOUT_MS, SEQ_LIMIT, serializeConsent, serializeRefusal, withEntry, withoutEntries, withoutOwner, } from "./codec.js";
7
- export { consentNotice } from "./notice.js";
7
+ export { consentNotice, noticeVersion } from "./notice.js";
8
8
  export { createConsentCoordinator, } from "./coordinator.js";
@@ -7,4 +7,11 @@ type SiteDto = components["schemas"]["SiteDto"];
7
7
  * Fetch `/v1/site` with the page's own `Accept-Language`, render the notice's text exactly, and send its `ref` with every grant.
8
8
  */
9
9
  export declare function consentNotice(site: SiteDto, language?: string): ConsentNoticeDto | null;
10
+ /**
11
+ * The config version a notice `ref` names (`base64url(UTF-8 "{configVersion}:{language}")`, shopper-state spec §7), or null for
12
+ * anything that is not a canonical ref: a positive int32 version without leading zeros, a colon and a lower-case language key. The
13
+ * same strings as the storefront's `ConsentNoticeRef.TryDecode` (pinned against it in the tests). A frontend re-asks a shopper whose recorded `ref` decodes below
14
+ * `site.attribution.minNoticeVersion` (order attribution spec §5.4).
15
+ */
16
+ export declare function noticeVersion(ref: string): number | null;
10
17
  export {};
@@ -9,3 +9,39 @@ export function consentNotice(site, language) {
9
9
  return null;
10
10
  return language === undefined || notice.language === language ? notice : null;
11
11
  }
12
+ const BASE64URL = /^[A-Za-z0-9_-]+$/;
13
+ // `\n?` mirrors .NET's `$`, which also matches before one final newline: `ConsentNoticeRef.TryDecode` accepts "17:sv\n" (it re-encodes
14
+ // to the same ref), so this decoder accepts exactly the strings the storefront accepts.
15
+ const LANGUAGE = /^[a-z]{2,3}(-[a-z0-9]{2,8})*\n?$/;
16
+ const INT32_MAX = 2_147_483_647;
17
+ /**
18
+ * The config version a notice `ref` names (`base64url(UTF-8 "{configVersion}:{language}")`, shopper-state spec §7), or null for
19
+ * anything that is not a canonical ref: a positive int32 version without leading zeros, a colon and a lower-case language key. The
20
+ * same strings as the storefront's `ConsentNoticeRef.TryDecode` (pinned against it in the tests). A frontend re-asks a shopper whose recorded `ref` decodes below
21
+ * `site.attribution.minNoticeVersion` (order attribution spec §5.4).
22
+ */
23
+ export function noticeVersion(ref) {
24
+ try {
25
+ if (typeof ref !== "string" || !BASE64URL.test(ref))
26
+ return null;
27
+ const binary = atob(ref.replace(/-/g, "+").replace(/_/g, "/"));
28
+ const text = new TextDecoder("utf-8", { fatal: true }).decode(Uint8Array.from(binary, (c) => c.charCodeAt(0)));
29
+ const colon = text.indexOf(":");
30
+ if (colon <= 0)
31
+ return null;
32
+ const digits = text.slice(0, colon);
33
+ if (!/^[1-9][0-9]*$/.test(digits))
34
+ return null;
35
+ const version = Number(digits);
36
+ if (version > INT32_MAX || !LANGUAGE.test(text.slice(colon + 1)))
37
+ return null;
38
+ // Canonical only: the ref re-encodes to itself (no padding, no stray bits in the last character).
39
+ let reencoded = "";
40
+ for (const byte of new TextEncoder().encode(text))
41
+ reencoded += String.fromCharCode(byte);
42
+ return btoa(reencoded).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "") === ref ? version : null;
43
+ }
44
+ catch {
45
+ return null;
46
+ }
47
+ }
@@ -10,8 +10,16 @@ export interface ConsentReading {
10
10
  granted(purpose: Purpose): boolean;
11
11
  /** The device key of a parsable cookie (locked or fallback), else null. */
12
12
  device: string | null;
13
- /** The notice reference the device recorded, else null. */
13
+ /**
14
+ * The notice reference the device recorded, else null. The cookie keeps one `ref`: the notice of its latest applied grant (of any
15
+ * purpose), so for a purpose granted earlier it can name a newer notice than that grant saw.
16
+ */
14
17
  ref: string | null;
18
+ /**
19
+ * The decision time (`PurposeState.at`) of a purpose `granted` reads true for, else null: the device binding of the attribution
20
+ * cookie (order attribution spec §6.5) compares it with the cookie's `grantAt`.
21
+ */
22
+ decidedAt(purpose: Purpose): number | null;
15
23
  }
16
24
  /**
17
25
  * The device state for SSR from `__Host-sf_consent` and `__Host-sf_consent_off`. A missing, unparsable or fallback cookie is not
@@ -19,6 +19,7 @@ export function readConsentCookie(cookies, opts = {}) {
19
19
  granted: (purpose) => grantedFor(cookie, off, purpose),
20
20
  device: cookie?.device ?? null,
21
21
  ref: cookie && !isFallback(cookie) ? cookie.ref : null,
22
+ decidedAt: (purpose) => (cookie && !isFallback(cookie) && grantedFor(cookie, off, purpose) ? cookie.purposes[purpose].at : null),
22
23
  };
23
24
  }
24
25
  /** `t.` + the first 16 hex of `sha256(token)`: the owner key of a guest shopper token (PL9, S36 owner binding). */
package/dist/index.d.ts CHANGED
@@ -51,6 +51,8 @@ export { isCheckoutContextMismatch, retryAfterSeconds, type CheckoutContextMisma
51
51
  export { mountCheckout, type CheckoutHandle, type MountOptions, type MinimalDocument, type MinimalElement, type MinimalScript } from "./checkout/browser.js";
52
52
  export { controllers, type CheckoutController, type ProviderWindow } from "./checkout/controllers.js";
53
53
  export { displayPrice, isBuyable, isPriceVisible, type DisplayPrice, type OfferDto } from "./offer.js";
54
+ export { linePriceDisplay, priceDisplay, type LinePriceDisplayOptions, type PriceDisplay, type PriceDisplayOptions, type PriceLabel, type PricePart, type PriceTexts, } from "./price-display.js";
55
+ export { nextRevalidateSeconds } from "./site.js";
54
56
  export { breadcrumbJsonLd } from "./seo/breadcrumb.js";
55
57
  export { brandHead, collectionHead, productHead, toNextMetadata } from "./seo/head.js";
56
58
  export { gtinJsonLd } from "./gtin.js";
@@ -68,4 +70,4 @@ export { AnalyticsError, type Ga4Ecommerce, type Ga4Item, type Ga4ItemOptions, t
68
70
  export { SeoError, type BreadcrumbLink, type CollectionHeadOptions, type HeadOptions, type JsonLd, type NextMetadataLike, type ProductJsonLdOptions, type SchemaProperty, type SeoContext, type SeoHead, type SeoMeta, type VariantAvailability, } from "./seo/types.js";
69
71
  export { readVariantParam, redirectTarget, VARIANT_PARAM, variantQueryForApi, variantUrl, type QueryInput, type VariantParam, } from "./variant.js";
70
72
  export { sortOptions, type SortOption } from "./sort.js";
71
- export { applyCode, removeCode, lineUnitPrices, type CartCodeOptions, type CartCodeResult, type LineUnitPrices } from "./cart-codes.js";
73
+ export { applyCode, codeReasonText, removeCode, lineUnitPrices, type CartCodeOptions, type CartCodeResult, type LineUnitPrices } from "./cart-codes.js";
package/dist/index.js CHANGED
@@ -44,6 +44,8 @@ export { isCheckoutContextMismatch, retryAfterSeconds } from "./checkout/types.j
44
44
  export { mountCheckout } from "./checkout/browser.js";
45
45
  export { controllers } from "./checkout/controllers.js";
46
46
  export { displayPrice, isBuyable, isPriceVisible } from "./offer.js";
47
+ export { linePriceDisplay, priceDisplay, } from "./price-display.js";
48
+ export { nextRevalidateSeconds } from "./site.js";
47
49
  export { breadcrumbJsonLd } from "./seo/breadcrumb.js";
48
50
  export { brandHead, collectionHead, productHead, toNextMetadata } from "./seo/head.js";
49
51
  export { gtinJsonLd } from "./gtin.js";
@@ -60,4 +62,4 @@ export { AnalyticsError, } from "./analytics/types.js";
60
62
  export { SeoError, } from "./seo/types.js";
61
63
  export { readVariantParam, redirectTarget, VARIANT_PARAM, variantQueryForApi, variantUrl, } from "./variant.js";
62
64
  export { sortOptions } from "./sort.js";
63
- export { applyCode, removeCode, lineUnitPrices } from "./cart-codes.js";
65
+ export { applyCode, codeReasonText, removeCode, lineUnitPrices } from "./cart-codes.js";
@@ -0,0 +1,87 @@
1
+ import type { components } from "./schema";
2
+ type OfferDto = components["schemas"]["OfferDto"];
3
+ type PricePairDto = components["schemas"]["PricePairDto"];
4
+ type SalePriceDto = components["schemas"]["SalePriceDto"];
5
+ type CartLineDto = components["schemas"]["CartLineDto"];
6
+ type CheckoutCartLineDto = components["schemas"]["CheckoutCartLineDto"];
7
+ type OrderLineDto = components["schemas"]["OrderLineDto"];
8
+ /** One amount to show, on one side of a pair. */
9
+ export type PricePart = {
10
+ amount: string;
11
+ basis: "inc" | "ex";
12
+ currency: string;
13
+ };
14
+ /** The parts of a price, never markup (site campaigns spec §9.6, contract C8). Every part except `price` is null when it must not
15
+ * show; render exactly what is here. */
16
+ export type PriceDisplay = {
17
+ /** What is charged now; null when the offer shows no price. */
18
+ price: PricePart | null;
19
+ /** The legal reference (the lowest price of the 30 days before the reduction), only with a live claim. Never `regular`, never the RRP. */
20
+ struck: (PricePart & {
21
+ label: string;
22
+ labelKey: string;
23
+ longLabel: string;
24
+ }) | null;
25
+ /** "−20 %", only with a live claim. */
26
+ badge: string | null;
27
+ /** The claim's amount off, only with a live claim. */
28
+ saving: PricePart | null;
29
+ /** The recommended price (`compareAt`): only with no live sale and no claim shown (Kristoffer 2026-11-13). Never struck. */
30
+ rrp: PricePart | null;
31
+ /** The live sale's exclusive end (RFC 3339); null for an open-ended sale and for no sale. */
32
+ endsAt: string | null;
33
+ /** The live sale was extended (`sale.extendedFrom` set and passed). */
34
+ extended: boolean;
35
+ /** The `data-price-part` attribute value of each part. */
36
+ parts: Record<"price" | "struck" | "badge" | "saving" | "rrp" | "ends-at", string>;
37
+ };
38
+ /** The wording of a claim label key. */
39
+ export type PriceLabel = {
40
+ label: string;
41
+ longLabel: string;
42
+ };
43
+ export type PriceTexts = {
44
+ /** Per claim `labelKey`. A claim whose key has no text here is not shown. */
45
+ labels: Record<string, PriceLabel>;
46
+ /** The badge for a claim's percent. */
47
+ badge: (percent: number) => string;
48
+ };
49
+ export type PriceDisplayOptions = {
50
+ /** The request's instant: a sale or claim that has ended by then is not shown (a page may be served from a cache). */
51
+ now: Date;
52
+ /** BCP 47; the language picks the default texts (`sv`, else English). Default `sv`. */
53
+ locale?: string;
54
+ texts?: Partial<PriceTexts>;
55
+ };
56
+ export type LinePriceDisplayOptions = PriceDisplayOptions & {
57
+ /** The side of a cart line's pairs to show. Default `inc`. Checkout and order lines are always `inc`. */
58
+ basis?: "inc" | "ex";
59
+ /** The cart's or order's currency: required for checkout and order lines, which carry none of their own. */
60
+ currency?: string;
61
+ };
62
+ /** The language of the default texts: `sv`, else English. */
63
+ export declare const language: (locale: string | undefined) => "sv" | "en";
64
+ /** The sale that applies at `now`, or null: a sale whose exclusive `validTo` has passed is dropped (C8). */
65
+ export declare function liveSale(offer: OfferDto, now: Date): SalePriceDto | null;
66
+ /** The pair charged at `now`: the offer's price, or `regular` once its sale has ended (a page served from a cache past the
67
+ * end). Null when the offer is not `available`. */
68
+ export declare function currentPair(offer: OfferDto, now: Date): PricePairDto | null;
69
+ /**
70
+ * The price of an offer as parts (C8). Render every price through this on the request, with the request's `now`:
71
+ * - a `sale` whose `validTo` ≤ now is dropped, and with it the offer's `claim`: `price` is then `regular`;
72
+ * - a `claim` whose `endsAt` or `claimEndsAt` ≤ now is dropped; a live claim strikes `reference`, sale or not;
73
+ * - `rrp` (`compareAt`) shows only with no live sale and no claim shown: never beside a sale, claim or not
74
+ * (Kristoffer 2026-11-13).
75
+ * - `endsAt` is the exclusive end: show the date of `endsAt − 1 s` in the site's time zone.
76
+ */
77
+ export declare function priceDisplay(offer: OfferDto, opts: PriceDisplayOptions): PriceDisplay;
78
+ /**
79
+ * A line's unit price as parts (C8): the unit price charged, and its `claim` striking its `reference` (never
80
+ * `unitPriceBeforePromotions`). A cart line is live: its claim drops once `endsAt` or `claimEndsAt` ≤ now. A checkout or
81
+ * order line carries frozen evidence and is never dropped by `now`. Lines have no RRP and no sale end.
82
+ */
83
+ export declare function linePriceDisplay(line: CartLineDto, opts: LinePriceDisplayOptions): PriceDisplay;
84
+ export declare function linePriceDisplay(line: CheckoutCartLineDto | OrderLineDto, opts: LinePriceDisplayOptions & {
85
+ currency: string;
86
+ }): PriceDisplay;
87
+ export {};
@@ -0,0 +1,102 @@
1
+ const PARTS = { price: "price", struck: "struck", badge: "badge", saving: "saving", rrp: "rrp", "ends-at": "ends-at" };
2
+ const DEFAULT_TEXTS = {
3
+ sv: {
4
+ labels: { priorLowest: { label: "Tidigare lägsta pris", longLabel: "Lägsta pris de senaste 30 dagarna före prissänkningen" } },
5
+ badge: (p) => `−${p}\u00a0%`, // a no-break space: the badge never wraps
6
+ },
7
+ en: {
8
+ labels: { priorLowest: { label: "Previous lowest price", longLabel: "Lowest price in the 30 days before the reduction" } },
9
+ badge: (p) => `−${p}%`,
10
+ },
11
+ };
12
+ /** The language of the default texts: `sv`, else English. */
13
+ export const language = (locale) => ((locale ?? "sv").toLowerCase().split(/[-_]/)[0] === "sv" ? "sv" : "en");
14
+ function textsFor(opts) {
15
+ const base = DEFAULT_TEXTS[language(opts.locale)];
16
+ return { labels: { ...base.labels, ...opts.texts?.labels }, badge: opts.texts?.badge ?? base.badge };
17
+ }
18
+ /** Whether an exclusive end has not passed; null = no end. */
19
+ const before = (end, now) => end == null || now.getTime() < Date.parse(end);
20
+ const part = (pair, basis) => {
21
+ const amount = pair?.[basis];
22
+ return amount ? { amount, basis, currency: pair.currency } : null;
23
+ };
24
+ /** The sale that applies at `now`, or null: a sale whose exclusive `validTo` has passed is dropped (C8). */
25
+ export function liveSale(offer, now) {
26
+ const sale = offer.sale ?? null;
27
+ return sale !== null && before(sale.validTo, now) ? sale : null;
28
+ }
29
+ /** The pair charged at `now`: the offer's price, or `regular` once its sale has ended (a page served from a cache past the
30
+ * end). Null when the offer is not `available`. */
31
+ export function currentPair(offer, now) {
32
+ if (offer.offerStatus !== "available")
33
+ return null;
34
+ if (offer.sale != null && liveSale(offer, now) === null)
35
+ return offer.regular ?? null;
36
+ return offer.price ?? null;
37
+ }
38
+ const NO_CLAIM = { struck: null, badge: null, saving: null };
39
+ /** A claim strikes its `reference`, never anything else; without the reference amount or a label text it shows nothing. */
40
+ function claimParts(claim, reference, basis, texts) {
41
+ if (claim === null)
42
+ return NO_CLAIM;
43
+ const struck = part(reference, basis);
44
+ const label = Object.hasOwn(texts.labels, claim.labelKey) ? texts.labels[claim.labelKey] : undefined;
45
+ if (struck === null || label === undefined)
46
+ return NO_CLAIM;
47
+ return {
48
+ struck: { ...struck, labelKey: claim.labelKey, label: label.label, longLabel: label.longLabel },
49
+ badge: texts.badge(claim.percent),
50
+ saving: part(claim.amountOff, basis),
51
+ };
52
+ }
53
+ const empty = () => ({ price: null, ...NO_CLAIM, rrp: null, endsAt: null, extended: false, parts: { ...PARTS } });
54
+ /**
55
+ * The price of an offer as parts (C8). Render every price through this on the request, with the request's `now`:
56
+ * - a `sale` whose `validTo` ≤ now is dropped, and with it the offer's `claim`: `price` is then `regular`;
57
+ * - a `claim` whose `endsAt` or `claimEndsAt` ≤ now is dropped; a live claim strikes `reference`, sale or not;
58
+ * - `rrp` (`compareAt`) shows only with no live sale and no claim shown: never beside a sale, claim or not
59
+ * (Kristoffer 2026-11-13).
60
+ * - `endsAt` is the exclusive end: show the date of `endsAt − 1 s` in the site's time zone.
61
+ */
62
+ export function priceDisplay(offer, opts) {
63
+ const out = empty();
64
+ const basis = offer.displayBasis;
65
+ out.price = part(currentPair(offer, opts.now), basis);
66
+ if (out.price === null)
67
+ return out;
68
+ const sale = liveSale(offer, opts.now);
69
+ const saleEnded = offer.sale != null && sale === null;
70
+ const rawClaim = offer.claim ?? null;
71
+ const claim = rawClaim !== null && !saleEnded && before(rawClaim.endsAt, opts.now) && before(rawClaim.claimEndsAt, opts.now) ? rawClaim : null;
72
+ Object.assign(out, claimParts(claim, offer.reference ?? null, basis, textsFor(opts)));
73
+ if (sale === null && out.struck === null)
74
+ out.rrp = part(offer.compareAt, basis);
75
+ if (sale !== null) {
76
+ out.endsAt = sale.validTo ?? null;
77
+ const from = sale.extendedFrom ?? null;
78
+ out.extended = from !== null && opts.now.getTime() >= Date.parse(from);
79
+ }
80
+ return out;
81
+ }
82
+ const isCartLine = (line) => line.unitPrice !== undefined;
83
+ export function linePriceDisplay(line, opts) {
84
+ const out = empty();
85
+ const texts = textsFor(opts);
86
+ const reference = line.reference ?? null;
87
+ const rawClaim = line.claim ?? null;
88
+ if (isCartLine(line)) {
89
+ const basis = opts.basis ?? "inc";
90
+ out.price = part(line.unitPrice, basis);
91
+ if (out.price === null)
92
+ return out;
93
+ const claim = rawClaim !== null && before(rawClaim.endsAt, opts.now) && before(rawClaim.claimEndsAt, opts.now) ? rawClaim : null;
94
+ return Object.assign(out, claimParts(claim, reference, basis, texts));
95
+ }
96
+ // No currency known (a caller outside TypeScript's overloads): show no price rather than an unformattable one.
97
+ const currency = opts.currency ?? "";
98
+ out.price = line.unitPriceInc && currency !== "" ? { amount: line.unitPriceInc, basis: "inc", currency } : null;
99
+ if (out.price === null)
100
+ return out;
101
+ return Object.assign(out, claimParts(rawClaim, reference, "inc", texts));
102
+ }