@vio-live/web-sdk 0.28.0 → 0.32.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/CHANGELOG.md +243 -2
- package/README.md +175 -13
- package/dist/{chunk-Q2NALS7P.js → chunk-C5Q6W4B2.js} +1453 -199
- package/dist/chunk-C5Q6W4B2.js.map +1 -0
- package/dist/{chunk-AFJ5M53F.js → chunk-IR4XYTZL.js} +707 -92
- package/dist/chunk-IR4XYTZL.js.map +1 -0
- package/dist/chunk-QGJUBVH3.js +3 -0
- package/dist/{chunk-67QESEV2.js.map → chunk-QGJUBVH3.js.map} +1 -1
- package/dist/core/index.d.ts +226 -6
- package/dist/core/index.js +2 -2
- package/dist/index.d.ts +1 -1
- package/dist/index.js +2 -2
- package/dist/react/index.d.ts +2 -2
- package/dist/react/index.js +3 -3
- package/dist/{tokens-y0KzN7bP.d.ts → tokens-D1DCVzOf.d.ts} +331 -13
- package/dist/ui/index.d.ts +1 -1
- package/dist/ui/index.js +3 -3
- package/package.json +1 -1
- package/dist/chunk-67QESEV2.js +0 -3
- package/dist/chunk-AFJ5M53F.js.map +0 -1
- package/dist/chunk-Q2NALS7P.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/slots.ts","../src/core/configuration.ts","../src/core/api/vio.ts","../src/core/types.ts","../src/core/api/commerce.ts","../src/core/content.ts","../src/core/cart/origin-wire.ts","../src/core/buyer-ref.ts","../src/core/api/gateway-features.ts","../src/core/api/cart-queries.ts","../src/core/checkout/payments/vipps.ts","../src/core/cart/cart-manager.ts","../src/core/sponsor-identity.ts","../src/core/checkout/payments/apple-pay.ts","../src/core/version.ts","../src/core/checkout/payments/stripe-embedded.ts","../src/core/checkout/payments/klarna.ts","../src/core/checkout/payments/klarna-payments.ts","../src/core/checkout/payments/kustom.ts","../src/core/checkout/payments/qliro.ts","../src/core/checkout/payments/qliro-sync.ts","../src/core/checkout/payments/walley.ts","../src/core/checkout/payments/nexi.ts","../src/core/checkout/payments/adyen.ts","../src/core/checkout/checkout-manager.ts","../src/core/analytics/client-context.ts","../src/core/cart/slices.ts","../src/core/analytics/analytics-manager.ts","../src/core/checkout/attribution.ts","../src/core/client.ts","../src/core/checkout/payments/vipps-button.ts"],"names":["location","cut","text","attr","pending","storage","landingUrl"],"mappings":";;;;;;;;;;;;;;AAuBO,IAAM,kBAAA,GAAqB,GAAA;AAG3B,IAAM,uBAAA,GAA0B,EAAA,GAAK,EAAA,GAAK,EAAA,GAAK,GAAA;AAE/C,IAAM,+BAAA,GAAkC,KAAK,EAAA,GAAK,GAAA;AAElD,IAAM,6BAAA,GAAgC,GAAA;AAEtC,IAAM,yBAAA,GAA4B,CAAA;AAalC,IAAM,oBAAA,GAAuB,EAAA;AAa7B,SAAS,eAAA,CAAgB,YAAqB,IAAA,EAAoC;AACvF,EAAA,MAAM,IAAA,GAAO,OAAO,UAAA,KAAe,QAAA,GAAW,WAAW,IAAA,EAAK,CAAE,aAAY,GAAI,EAAA;AAChF,EAAA,IAAI,IAAA,EAAM,OAAO,IAAA,CAAK,OAAA,CAAQ,iBAAA,EAAmB,EAAE,CAAA,CAAE,KAAA,CAAM,CAAA,EAAG,oBAAoB,CAAA,IAAK,MAAA;AACvF,EAAA,MAAM,KAAK,OAAO,IAAA,KAAS,QAAA,GAAW,IAAA,CAAK,aAAY,GAAI,EAAA;AAC3D,EAAA,MAAM,CAAA,GAAI,EAAA,CAAG,KAAA,CAAM,oEAAoE,CAAA;AACvF,EAAA,OAAO,IAAI,CAAC,CAAA;AACd;AAGO,SAAS,kBAAkB,KAAA,EAAoC;AACpE,EAAA,IAAI,OAAO,KAAA,KAAU,QAAA,EAAU,OAAO,MAAA;AACtC,EAAA,MAAM,IAAA,GAAO,KAAA,CAAM,IAAA,EAAK,CAAE,WAAA,GAAc,KAAA,CAAM,CAAA,EAAG,oBAAoB,CAAA,CAAE,IAAA,EAAK;AAC5E,EAAA,OAAO,IAAA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,GAAQ,OAAA,GAAU,MAAA;AAAA,IAChD,GAAI,IAAA,CAAK,OAAA,GAAU,EAAE,OAAA,EAAS,MAAA,KAAW;AAAC,GAC5C;AACF","file":"chunk-AFJ5M53F.js","sourcesContent":["/**\n * Slots — the pure half of ADR-0027 / ADR-0034 on the web.\n *\n * A slot is a NAME for a place on a page. The page declares its slots to the\n * campaigns service (`Vio.declareSlots()` / `Vio.registerSlot()` in client.ts),\n * the dashboard assigns a campaign to each one, optionally with a date window,\n * and `GET /v2/mobile/config` answers with `campaigns[].slots[]` — only the\n * assignments whose window is open NOW. Whatever no slot names shows the\n * surface's default campaign (`campaign`).\n *\n * Everything here is side-effect free and never throws on a malformed\n * bootstrap: a broken `campaigns[]` must never blank a product block or break\n * `track()`.\n */\n\nimport type {\n BootstrapCampaignEntry,\n BootstrapResponse,\n BootstrapSlot,\n ManifestLocation,\n} from './types.js'\n\n/** The server caps slot ids at 100 characters; longer ones are cut, not dropped. */\nexport const SLOT_ID_MAX_LENGTH = 100\n\n/** A declared set is not re-posted from the same browser for this long. */\nexport const SLOT_DECLARATION_TTL_MS = 24 * 60 * 60 * 1000\n/** After a failure (or a server that ignored `merge`) the same set is not retried for this long. */\nexport const SLOT_DECLARATION_FAILURE_TTL_MS = 60 * 60 * 1000\n/** The server takes at most this many locations per manifest. */\nexport const MAX_LOCATIONS_PER_DECLARATION = 100\n/** Declarations a page load may POST (a `force` call bypasses it). */\nexport const MAX_DECLARATIONS_PER_LOAD = 3\n\n/** What `Vio.declareSlots()` accepts per slot. */\nexport type SlotInput = string | { id: string; displayName?: string; campaignId?: number; kind?: string }\n\n/** The third argument of `Vio.registerSlot(id, displayName, …)`: the element's own campaign and what kind of element it is. */\nexport interface RegisterSlotOptions {\n campaignId?: number | string | null\n /** `card` | `carousel` | `detail` for the SDK's elements; a host may name its own kind. */\n kind?: string\n}\n\n/** A kind is a short word (the micro stores it from 2026-10 on; before, it ignored the key). */\nexport const SLOT_KIND_MAX_LENGTH = 32\n\n/**\n * The kind of component some units were sold from, as Commerce keeps it on\n * the order line (`order_item.component_kind`, ≤ 32) — the SAME rule the\n * collector applies for `breakdown?by=component_kind` (vio-analytics\n * `componentKind`), so the order and the events agree: what the element says\n * it is (`component_template_id`: `product-card`, `product-carousel`,\n * `product-detail`, a Vev block's `vev-card`) lower-cased and without its\n * `product-` / `vev-` prefix, else the kind word in the slot id the page\n * declared (`card-<key>`, `<scope>-carousel-2`, `detail-1`); `undefined` when\n * neither says.\n */\nexport function componentKindOf(templateId: unknown, slot?: unknown): string | undefined {\n const hint = typeof templateId === 'string' ? templateId.trim().toLowerCase() : ''\n if (hint) return hint.replace(/^(product|vev)-/, '').slice(0, SLOT_KIND_MAX_LENGTH) || undefined\n const id = typeof slot === 'string' ? slot.toLowerCase() : ''\n const m = id.match(/(?:^|-)(card|carousel|grid|detail|banner|list|hero|stepper)(?:-|$)/)\n return m?.[1]\n}\n\n/** The kind as the manifest carries it: trimmed, lower-case, cut at 32 chars; `undefined` for nothing. */\nexport function normalizeSlotKind(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined\n const kind = value.trim().toLowerCase().slice(0, SLOT_KIND_MAX_LENGTH).trim()\n return kind || undefined\n}\n\ntype BootLike = Pick<\n BootstrapResponse,\n 'campaign' | 'campaigns' | 'primarySponsor' | 'secondarySponsors'\n>\n\n// ── Resolution ──────────────────────────────────────────────────────────────\n\n/**\n * The campaign a slot shows right now. Among the `status === 'active'`\n * entries of `campaigns[]`, the one with an assignment named `slot` for this\n * platform (`platform` null on the assignment, or equal to `platform`) whose\n * window contains `now` (`startDate <= now < endDate`, null = open). When\n * several qualify, the surface's default campaign wins, else the first the\n * backend lists.\n *\n * No assignment → the PAGE's campaign (`pageCampaignId`: the element's own\n * `vio-campaign`, an ancestor's `data-vio-campaign`, or `Vio.init({ campaignId })`)\n * when `campaigns[]` lists it as active — an editorial page resolves to its\n * campaign before (and regardless of) the manifest round-trip. Else the\n * default campaign: the `campaigns[]` entry whose id is `campaign.id`, or a\n * minimal entry built from `campaign` (+ the top-level sponsors) when the\n * list does not carry it. No bootstrap → null.\n */\nexport function resolveSlotCampaign(\n boot: BootLike | null | undefined,\n slot: string | null | undefined,\n now: number = Date.now(),\n platform?: string | null,\n pageCampaignId?: CampaignHint,\n sponsorId?: number | null,\n): BootstrapCampaignEntry | null {\n if (!boot) return null\n const page = activeCampaignEntry(boot, pageCampaignId)\n const assignment = findSlotAssignmentDetail(boot, slot, now, platform)\n const sponsor = toNumber(sponsorId)\n if (assignment && assignmentApplies(assignment, page, sponsor)) return assignment.campaign\n return (\n activeCampaignEntry(boot, pageCampaignId, sponsor) ??\n (sponsor !== undefined ? sponsorCampaignEntry(boot, sponsor) : null) ??\n defaultCampaignEntry(boot)\n )\n}\n\n/**\n * The sponsor rule: the active campaign of `campaigns[]` the sponsor takes\n * part in, as its primary or one of its secondaries — when it is in several,\n * the surface's default campaign if it is one of them, else the first one\n * the backend lists. Null when none (or on a malformed list).\n */\nexport function sponsorCampaignEntry(\n boot: BootLike | null | undefined,\n sponsorId: number | null | undefined,\n): BootstrapCampaignEntry | null {\n const id = toNumber(sponsorId)\n if (!boot || id === undefined) return null\n try {\n const matches = activeCampaigns(boot).filter((c) => campaignSponsorIds(c).includes(id))\n if (matches.length === 0) return null\n const defaultId = toNumber(boot.campaign?.id)\n return matches.find((c) => toNumber(c.id) === defaultId) ?? matches[0] ?? null\n } catch {\n return null\n }\n}\n\n/**\n * Whether a slot assignment decides the campaign. A dashboard assignment (or\n * one without `source`, an older micro) always does. One this page made\n * itself (`source: 'page'`) is treated like the page campaign: it does not\n * when the page now declares a different active campaign (it is about to be\n * re-declared), nor — with a known sponsor — when that sponsor takes no part\n * in it (the sponsor rule then says where the sponsor's campaign is).\n */\nexport function assignmentApplies(\n assignment: { campaign: BootstrapCampaignEntry; slot: BootstrapSlot },\n page: BootstrapCampaignEntry | null,\n sponsorId?: number,\n): boolean {\n if (assignment.slot.source !== 'page') return true\n if (isStalePageAssignment(assignment, page)) return false\n return sponsorId === undefined || campaignSponsorIds(assignment.campaign).includes(sponsorId)\n}\n\n/** A page-sourced assignment that disagrees with the page's current (active) campaign. */\nexport function isStalePageAssignment(\n assignment: { campaign: BootstrapCampaignEntry; slot: BootstrapSlot },\n page: BootstrapCampaignEntry | null,\n): boolean {\n return !!page && assignment.slot.source === 'page' && toNumber(page.id) !== toNumber(assignment.campaign.id)\n}\n\n/**\n * A page campaign as the callers give it: one id, or the candidates in\n * precedence order (the element's `vio-campaign`, an ancestor's\n * `data-vio-campaign`, `Vio.init`'s). An unusable level (invalid, paused,\n * unknown) falls through to the next one; `0`, `null`, `''` mean unset.\n */\nexport type CampaignHint = number | string | null | undefined | ReadonlyArray<number | string | null | undefined>\n\n/**\n * A campaign id as the SDK accepts it: a positive safe integer, given as a\n * number or as a string of decimal digits (an attribute). Anything else —\n * `true`, `'0x10'`, `'1e3'`, an array, a float — is \"absent\".\n */\nexport function toCampaignId(value: unknown): number | undefined {\n let n: number\n if (typeof value === 'number') n = value\n else if (typeof value === 'string' && /^\\s*\\d+\\s*$/.test(value)) n = Number(value)\n else return undefined\n return Number.isSafeInteger(n) && n > 0 ? n : undefined\n}\n\n/** The usable ids of a hint, in order, without duplicates. */\nexport function campaignCandidates(hint: CampaignHint): number[] {\n const raw = Array.isArray(hint) ? hint : [hint]\n const out: number[] = []\n for (const v of raw) {\n const id = toCampaignId(v)\n if (id !== undefined && !out.includes(id)) out.push(id)\n }\n return out\n}\n\n/**\n * The first candidate of `hint` that `campaigns[]` lists as ACTIVE (and, when\n * `sponsorId` is given, that the sponsor takes part in — primary or\n * secondary); null when none — a paused, ended or unknown page campaign is\n * ignored and the resolution moves on.\n */\nexport function activeCampaignEntry(\n boot: BootLike | null | undefined,\n hint: CampaignHint,\n sponsorId?: number,\n): BootstrapCampaignEntry | null {\n if (!boot) return null\n try {\n const active = activeCampaigns(boot)\n for (const id of campaignCandidates(hint)) {\n const entry = active.find((c) => toNumber(c.id) === id)\n if (!entry) continue\n if (sponsorId !== undefined && !campaignSponsorIds(entry).includes(sponsorId)) continue\n return entry\n }\n } catch {\n /* malformed campaigns[] */\n }\n return null\n}\n\n/** The sponsor ids of a campaign: its primary and its secondaries. */\nexport function campaignSponsorIds(campaign: BootstrapCampaignEntry): number[] {\n const ids: number[] = []\n const primary = toNumber(campaign.primarySponsor?.id)\n if (primary !== undefined) ids.push(primary)\n const secondaries = Array.isArray(campaign.secondarySponsors) ? campaign.secondarySponsors : []\n for (const s of secondaries) {\n const id = toNumber(s?.id)\n if (id !== undefined) ids.push(id)\n }\n return ids\n}\n\n/**\n * Only the ASSIGNED campaign of `slot` (see `resolveSlotCampaign`), without the\n * default fallback — attribution needs to tell \"this slot has a campaign\" from\n * \"nothing assigned, use the sponsor rule\".\n */\nexport function findSlotAssignment(\n boot: BootLike | null | undefined,\n slot: string | null | undefined,\n now: number = Date.now(),\n platform?: string | null,\n): BootstrapCampaignEntry | null {\n return findSlotAssignmentDetail(boot, slot, now, platform)?.campaign ?? null\n}\n\n/** Like `findSlotAssignment`, with the matching assignment itself (its `source` decides against a page campaign). */\nexport function findSlotAssignmentDetail(\n boot: BootLike | null | undefined,\n slot: string | null | undefined,\n now: number = Date.now(),\n platform?: string | null,\n): { campaign: BootstrapCampaignEntry; slot: BootstrapSlot } | null {\n const name = typeof slot === 'string' ? slot.trim() : ''\n if (!boot || !name) return null\n try {\n const matches: Array<{ campaign: BootstrapCampaignEntry; slot: BootstrapSlot }> = []\n for (const campaign of activeCampaigns(boot)) {\n const match = slotsOf(campaign).find((s) => assignmentMatches(s, name, now, platform))\n if (match) matches.push({ campaign, slot: match })\n }\n if (matches.length === 0) return null\n const defaultId = toNumber(boot.campaign?.id)\n return matches.find((m) => toNumber(m.campaign.id) === defaultId) ?? matches[0] ?? null\n } catch {\n return null\n }\n}\n\n/** The surface's default campaign as a `campaigns[]` entry (see above). */\nexport function defaultCampaignEntry(boot: BootLike | null | undefined): BootstrapCampaignEntry | null {\n if (!boot?.campaign || typeof boot.campaign !== 'object') return null\n const defaultId = toNumber(boot.campaign.id)\n if (defaultId === undefined) return null\n try {\n const listed = wellFormedCampaigns(boot).find((c) => toNumber(c.id) === defaultId)\n if (listed) return listed\n } catch {\n /* fall through to the minimal entry */\n }\n return {\n ...boot.campaign,\n isDefault: true,\n primarySponsor: boot.primarySponsor ?? null,\n secondarySponsors: Array.isArray(boot.secondarySponsors) ? boot.secondarySponsors : [],\n slots: [],\n }\n}\n\nfunction wellFormedCampaigns(boot: BootLike): BootstrapCampaignEntry[] {\n const list = Array.isArray(boot.campaigns) ? boot.campaigns : []\n return list.filter((c): c is BootstrapCampaignEntry => !!c && typeof c === 'object')\n}\n\nfunction activeCampaigns(boot: BootLike): BootstrapCampaignEntry[] {\n return wellFormedCampaigns(boot).filter((c) => c.status === 'active')\n}\n\nfunction slotsOf(campaign: BootstrapCampaignEntry): BootstrapSlot[] {\n const slots = Array.isArray(campaign.slots) ? campaign.slots : []\n return slots.filter((s): s is BootstrapSlot => !!s && typeof s === 'object')\n}\n\nfunction assignmentMatches(\n s: BootstrapSlot,\n name: string,\n now: number,\n platform?: string | null,\n): boolean {\n if (typeof s.name !== 'string' || s.name.trim() !== name) return false\n if (platform && s.platform != null && s.platform !== platform) return false\n const start = parseTime(s.startDate)\n if (start !== undefined && start > now) return false\n const end = parseTime(s.endDate)\n if (end !== undefined && now >= end) return false\n return true\n}\n\n/** Epoch ms of an ISO date; `undefined` (= open) for null or unparsable. */\nfunction parseTime(value: string | null | undefined): number | undefined {\n if (value == null || value === '') return undefined\n const t = Date.parse(String(value))\n return Number.isFinite(t) ? t : undefined\n}\n\n/** A finite number from a number or numeric string; `undefined` otherwise. */\nexport function toNumber(value: unknown): number | undefined {\n if (value === undefined || value === null || value === '') return undefined\n const n = Number(value)\n return Number.isFinite(n) ? n : undefined\n}\n\n// ── Declaration helpers ─────────────────────────────────────────────────────\n\n/**\n * THE normalization of a slot id — trimmed, cut at the server's 100 chars,\n * trimmed again (a space at position 100 must not survive the cut). Used by\n * the elements' identity, `registerSlot`, `declareSlots` and `attribution`,\n * so every copy of an id is the same string.\n */\nexport function normalizeSlotId(value: unknown): string {\n if (typeof value !== 'string') return ''\n return value.trim().slice(0, SLOT_ID_MAX_LENGTH).trim()\n}\n\n/**\n * `Vio.declareSlots()` input → manifest `locations`: ids trimmed, cut at 100\n * chars, empties dropped, duplicates collapsed (the first displayName wins),\n * original order kept.\n */\nexport function normalizeSlotLocations(slots: ReadonlyArray<SlotInput> | null | undefined): ManifestLocation[] {\n const out: ManifestLocation[] = []\n const seen = new Set<string>()\n if (!Array.isArray(slots)) return out\n for (const raw of slots) {\n const id = normalizeSlotId(typeof raw === 'string' ? raw : raw?.id)\n if (!id || seen.has(id)) continue\n seen.add(id)\n const displayName =\n raw && typeof raw === 'object' && typeof raw.displayName === 'string'\n ? raw.displayName.trim()\n : ''\n const campaignId = raw && typeof raw === 'object' ? toCampaignId(raw.campaignId) : undefined\n const kind = raw && typeof raw === 'object' ? normalizeSlotKind(raw.kind) : undefined\n const location: ManifestLocation = { id }\n if (displayName) location.displayName = displayName\n if (campaignId !== undefined) location.campaignId = campaignId\n if (kind) location.kind = kind\n out.push(location)\n }\n return out\n}\n\n// ── Auto identity (ADR-0034 refinement: the editor types nothing) ───────────\n\n/** The kinds of Vio element that register themselves. */\nexport type SlotKind = 'card' | 'carousel' | 'detail'\n\n/**\n * The id an element gets when the host set no `vio-slot`:\n * `${scope ? scope + '-' : ''}${kind}-${ordinal + 1}` (`carousel-1`, `card-3`,\n * `article-123-carousel-1`), `ordinal` being the element's index among the\n * same-kind Vio elements WITH THE SAME SCOPE, in document order at connect\n * time. The scope is inherited from the DOM (`vio-scope` on the element, else\n * the nearest `data-vio-scope` ancestor): a Vev page or a Replit article\n * (`<body data-vio-scope=\"article-123\">`) gets per-page slots with one line\n * and no per-element naming; a template that wants slots shared across\n * articles simply sets no scope. On purpose there is NO page path in the id:\n * the article goes to analytics as `content_id`, not into the slot. Stable\n * across reloads while the layout is; a layout change leaves a stale entry,\n * which ADR-0034 accepts.\n */\nexport function autoSlotId(kind: SlotKind, ordinal: number, scope?: string | null): string {\n const tail = `${kind}-${ordinal + 1}`\n let prefix = normalizeScope(scope)\n // The whole id must fit the server's 100 chars: a long scope is cut, the\n // kind + number never are (they are what keeps the id unique).\n const room = SLOT_ID_MAX_LENGTH - tail.length - 1\n if (prefix.length > room) prefix = prefix.slice(0, Math.max(0, room)).replace(/-+$/, '')\n return `${prefix ? `${prefix}-` : ''}${tail}`\n}\n\n/** `\"Carousel 1\"`, `\"Card 3\"` — with ` · ${scopeName}` when the scope has a human label. */\nexport function autoSlotDisplayName(kind: SlotKind, ordinal: number, scopeName?: string | null): string {\n const label = `${kind.charAt(0).toUpperCase()}${kind.slice(1)} ${ordinal + 1}`\n const name = typeof scopeName === 'string' ? scopeName.trim() : ''\n return name ? `${label} · ${name}` : label\n}\n\n/** A scope value fit for an id: trimmed, inner whitespace → `-`. */\nexport function normalizeScope(scope: string | null | undefined): string {\n if (typeof scope !== 'string') return ''\n return scope.trim().replace(/\\s+/g, '-')\n}\n\n// ── Declaration memory ──────────────────────────────────────────────────────\n\n/**\n * What the browser remembers per (platform, key): for each declared location\n * key — `id`, `\\u001f<displayName>` when it has one, `\\u001e<campaignId>` when\n * it was declared with a campaign (its own, else the page's); see\n * `slotDeclarationKey` — the epoch ms it was declared. Per id — not per set —\n * because a multi-page site (Vev: one page per article, lazy blocks) makes a\n * new set on every navigation; only the ids not declared in the last 24 h go\n * out, and an id keeps ONE state (a new name or campaign forgets the old key).\n * A failed attempt is stored as if declared\n * `SLOT_DECLARATION_TTL_MS − SLOT_DECLARATION_FAILURE_TTL_MS` ago, so it is\n * retried after an hour, not on every view.\n */\nexport type SlotDeclarationMemory = Record<string, number>\n\n/** The memory keeps at most this many ids (oldest dropped). */\nexport const SLOT_DECLARATION_MEMORY_CAP = 500\n\n/**\n * The sortable key of one location: id, display name, the campaign it is\n * declared with (its own, else the page's) and its kind — a renamed block, a\n * page that changed campaign, or an id whose kind became known, is a new key\n * and declares again.\n */\nexport function slotDeclarationKey(location: ManifestLocation, pageCampaignId?: number | null): string {\n const campaignId = toCampaignId(location.campaignId) ?? toCampaignId(pageCampaignId)\n const kind = normalizeSlotKind(location.kind)\n return (\n location.id +\n (location.displayName ? `\\u001f${location.displayName}` : '') +\n (campaignId !== undefined ? `\\u001e${campaignId}` : '') +\n (kind !== undefined ? `\\u001d${kind}` : '')\n )\n}\n\n/** Sorted keys of a set of locations (see `slotDeclarationKey`). */\nexport function slotDeclarationKeys(\n locations: ReadonlyArray<ManifestLocation>,\n pageCampaignId?: number | null,\n): string[] {\n return locations.map((l) => slotDeclarationKey(l, pageCampaignId)).sort()\n}\n\n/** The keys not remembered within `ttl` (or remembered in the future — a clock that went back). */\nexport function pendingSlotKeys(\n memory: SlotDeclarationMemory | null | undefined,\n keys: ReadonlyArray<string>,\n now: number = Date.now(),\n ttl: number = SLOT_DECLARATION_TTL_MS,\n): string[] {\n return keys.filter((key) => {\n const at = memory?.[key]\n if (typeof at !== 'number' || !Number.isFinite(at)) return true\n return now - at >= ttl || now < at\n })\n}\n\n/** The id part of a memory key (before the display name / campaign / kind separators). */\nexport function slotKeyId(key: string): string {\n const cut = key.search(/[\\u001f\\u001e\\u001d]/)\n return cut >= 0 ? key.slice(0, cut) : key\n}\n\n/**\n * The memory with `keys` remembered at `at`, pruned to the newest `cap`\n * entries. ONE state per id: remembering `hero` under campaign B forgets\n * `hero` under campaign A (or another name), so A → B → A declares A again.\n */\nexport function rememberSlotKeys(\n memory: SlotDeclarationMemory | null | undefined,\n keys: ReadonlyArray<string>,\n at: number,\n cap: number = SLOT_DECLARATION_MEMORY_CAP,\n): SlotDeclarationMemory {\n const next: SlotDeclarationMemory = { ...(memory ?? {}) }\n const ids = new Set(keys.map(slotKeyId))\n for (const existing of Object.keys(next)) {\n if (ids.has(slotKeyId(existing)) && !keys.includes(existing)) delete next[existing]\n }\n for (const key of keys) next[key] = at\n const entries = Object.entries(next)\n if (entries.length <= cap) return next\n entries.sort((a, b) => b[1] - a[1])\n return Object.fromEntries(entries.slice(0, cap))\n}\n\n/**\n * localStorage key of the declaration memory. The API key itself never lands\n * in storage — only a short non-reversible hash of it, so two keys on the same\n * origin (Vev's remembered key, then the page's own) do not share a memory.\n */\nexport function slotDeclarationStorageKey(platform: string, apiKey: string): string {\n return `vio.slots.${platform}.${fnv1a(apiKey)}`\n}\n\n/** 32-bit FNV-1a, hex. Not cryptographic — it only has to be stable. */\nexport function fnv1a(input: string): string {\n let hash = 0x811c9dc5\n for (let i = 0; i < input.length; i++) {\n hash ^= input.charCodeAt(i)\n hash = Math.imul(hash, 0x01000193) >>> 0\n }\n return hash.toString(16).padStart(8, '0')\n}\n\n/** The remembered map, or `{}` (missing, malformed, no storage, old shape). */\nexport function readSlotDeclaration(storageKey: string): SlotDeclarationMemory {\n try {\n // Even `typeof localStorage` can throw (sandboxed iframes, cookies off).\n if (typeof localStorage === 'undefined') return {}\n const raw = localStorage.getItem(storageKey)\n if (!raw) return {}\n const parsed = JSON.parse(raw) as unknown\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {}\n // The 0.23.0 shape (`{ keys: [...], at }`) is not a map: forget it, declare once more.\n if (Array.isArray((parsed as { keys?: unknown }).keys)) return {}\n const out: SlotDeclarationMemory = {}\n for (const [key, at] of Object.entries(parsed as Record<string, unknown>)) {\n if (typeof at === 'number' && Number.isFinite(at)) out[key] = at\n }\n return out\n } catch {\n return {} // private mode, quota, corrupted JSON — all \"nothing remembered\"\n }\n}\n\n/** Persist the map; silently does nothing without storage. */\nexport function writeSlotDeclaration(storageKey: string, memory: SlotDeclarationMemory): void {\n try {\n if (typeof localStorage === 'undefined') return\n localStorage.setItem(storageKey, JSON.stringify(memory))\n } catch {\n /* private mode / quota — we just post again next time */\n }\n}\n","/**\n * Vio Configuration — singleton holding apiKey, environment, base URLs,\n * and optional payment-vendor publishable keys.\n *\n * Mirrors `VioConfiguration.shared` in the iOS SDK. Initialised once via\n * `Vio.init({ apiKey, ... })`; consumed via `Configuration.get()`.\n *\n * Secrets (apiKey) never come from inside the SDK — the consumer reads\n * them from env vars / their config and passes them to `Vio.init`.\n */\n\nimport { toCampaignId } from './slots.js'\n\nexport type Environment = 'development' | 'testing' | 'production'\n\n/**\n * Platform type of the surface this page belongs to (ADR-0027). It travels\n * with every slot declaration and as `?platform=` on the bootstrap, so the\n * campaigns service only answers with the slot assignments of this platform.\n */\nexport type VioPlatform = 'web' | 'custom-web' | 'vev'\n\nexport interface VioConfig {\n /** Vio API key for this client app (from the Vio dashboard). */\n apiKey: string\n /** Target environment. Defaults to 'development'. */\n environment?: Environment\n /**\n * Platform type of this surface: `web` (the no-code snippet), `custom-web`\n * (the SDK integrated by code) or `vev`. Defaults to `web`.\n */\n platform?: VioPlatform\n /**\n * The host's own id for the content (article, page) this SDK instance is\n * rendered in — the first choice of `Vio.content()`, ahead of the URL query,\n * the `vio:content-id` meta, the canonical URL and the pathname. Goes on\n * every analytics event as `content_id`.\n */\n contentId?: string | number\n /** Human-readable title of that content (`content_title`); see `contentId`. */\n contentTitle?: string\n /**\n * The campaign this PAGE belongs to (ADR-0034, amendment 3) — an editorial\n * page (a Vev article, a Replit article) that is part of one campaign. Its\n * slots are declared with it (the micro assigns them unless the dashboard\n * already did) and, until that round-trips, the elements already resolve to\n * it: assignment → page campaign → default. DOM alternative, inheritable:\n * `data-vio-campaign` on any ancestor, or `vio-campaign` on the element.\n */\n campaignId?: number\n /** Log the SDK's slot/attribution decisions at `console.debug` (manifest assignments per slot). */\n debug?: boolean\n /**\n * The surface's privacy mode, when the host knows it (ADR-0035): `minimal`\n * keeps the entry context (referrer, utm, landing page) off the order\n * attribution. Without it the SDK asks the surface itself\n * (`GET /v2/mobile/surface`), once per page load; a host-set `minimal`\n * always wins.\n */\n privacyMode?: 'standard' | 'minimal'\n /** Override REST API base. Defaults are env-aware. */\n apiBase?: string\n /** Override GraphQL base. Defaults are env-aware. */\n graphQLBase?: string\n /**\n * Override the analytics collector base (vio-analytics service).\n * Defaults are env-aware (`events-dev`/`events-staging`/`events.vio.live`).\n */\n eventsBase?: string\n /**\n * Stripe **publishable** key (`pk_test_xxx` or `pk_live_xxx`). Used for\n * Apple Pay (via Payment Request) and Card flows. Public-safe — fine\n * to expose in client bundles.\n */\n stripePublishableKey?: string\n /**\n * Klarna **Client Identifier** for Express Checkout (KEC). Public-safe.\n * From Merchant Portal → Payment settings → Client Identifiers. When set,\n * the checkout shows the Klarna Express button; when absent it degrades\n * to the plain method selector. Must match `klarnaEnvironment`.\n */\n klarnaClientId?: string\n /**\n * Klarna environment for the Express button. `playground` = sandbox\n * (test orders, no real money), `production` = live. Defaults to\n * `playground` so dev/test never hits live Klarna by accident.\n */\n klarnaEnvironment?: 'playground' | 'production'\n}\n\nexport interface ResolvedConfig {\n apiKey: string\n environment: Environment\n platform: VioPlatform\n contentId?: string | number\n contentTitle?: string\n campaignId?: number\n debug: boolean\n privacyMode?: 'standard' | 'minimal'\n apiBase: string\n graphQLBase: string\n eventsBase: string\n stripePublishableKey?: string\n klarnaClientId?: string\n klarnaEnvironment: 'playground' | 'production'\n}\n\nconst DEFAULT_URLS: Record<\n Environment,\n { apiBase: string; graphQLBase: string; eventsBase: string }\n> = {\n // The Vio Backend development environment was removed on 2026-09-16; its REST\n // and events hosts now point at staging (Commerce GraphQL dev is unaffected).\n development: {\n apiBase: 'https://api-staging.vio.live',\n graphQLBase: 'https://graph-ql-dev.vio.live',\n eventsBase: 'https://events-staging.vio.live',\n },\n // No separate staging GraphQL deployment yet — shares dev's.\n testing: {\n apiBase: 'https://api-staging.vio.live',\n graphQLBase: 'https://graph-ql-dev.vio.live',\n eventsBase: 'https://events-staging.vio.live',\n },\n production: {\n apiBase: 'https://api.vio.live',\n graphQLBase: 'https://graph-ql.vio.live',\n eventsBase: 'https://events.vio.live',\n },\n}\n\nclass ConfigurationSingleton {\n private resolved: ResolvedConfig | null = null\n private readyWaiters: Array<() => void> = []\n\n init(input: VioConfig): void {\n if (!input.apiKey || typeof input.apiKey !== 'string') {\n throw new Error('[Vio] apiKey is required in Vio.init({ apiKey })')\n }\n const env: Environment = input.environment ?? 'development'\n const defaults = DEFAULT_URLS[env]\n this.resolved = {\n apiKey: input.apiKey,\n environment: env,\n platform: input.platform ?? 'web',\n contentId: input.contentId,\n contentTitle: input.contentTitle,\n campaignId: toCampaignId(input.campaignId),\n debug: input.debug === true,\n // Only the two words the backend knows; anything else is \"not said\".\n privacyMode:\n input.privacyMode === 'minimal' || input.privacyMode === 'standard' ? input.privacyMode : undefined,\n apiBase: input.apiBase ?? defaults.apiBase,\n graphQLBase: input.graphQLBase ?? defaults.graphQLBase,\n eventsBase: input.eventsBase ?? defaults.eventsBase,\n stripePublishableKey: input.stripePublishableKey,\n klarnaClientId: input.klarnaClientId,\n // Sandbox by default — live Klarna must be opted into explicitly.\n klarnaEnvironment: input.klarnaEnvironment ?? 'playground',\n }\n if (typeof console !== 'undefined') {\n const masked =\n input.apiKey.length > 4\n ? '*'.repeat(Math.max(0, input.apiKey.length - 4)) + input.apiKey.slice(-4)\n : '****'\n console.info('[Vio] Initialized', {\n environment: env,\n platform: this.resolved.platform,\n apiBase: this.resolved.apiBase,\n apiKey: masked,\n stripeConfigured: !!input.stripePublishableKey,\n klarnaConfigured: !!input.klarnaClientId,\n klarnaEnvironment: this.resolved.klarnaEnvironment,\n })\n }\n const waiters = this.readyWaiters\n this.readyWaiters = []\n for (const waiter of waiters) waiter()\n }\n\n get(): ResolvedConfig {\n if (!this.resolved) {\n throw new Error(\n '[Vio] Not initialized. Call Vio.init({ apiKey }) before using the SDK.',\n )\n }\n return this.resolved\n }\n\n get isInitialized(): boolean {\n return this.resolved !== null\n }\n\n /**\n * Resolves once `Vio.init()` has run, or after `timeoutMs` — whichever\n * comes first. Hosts that mount several independent components (e.g. Vev\n * blocks, which mount in no guaranteed order) may have one fire a GraphQL\n * call before another has called `Vio.init()`. Awaiting this briefly lets\n * that race resolve instead of silently sending an unauthenticated\n * request. Resolves `true` if init happened in time, `false` on timeout —\n * callers should still degrade gracefully either way.\n */\n whenReady(timeoutMs = 2000): Promise<boolean> {\n if (this.resolved) return Promise.resolve(true)\n return new Promise<boolean>((resolve) => {\n const timer = setTimeout(() => resolve(false), timeoutMs)\n this.readyWaiters.push(() => {\n clearTimeout(timer)\n resolve(true)\n })\n })\n }\n\n /** For tests only. */\n reset(): void {\n this.resolved = null\n this.readyWaiters = []\n }\n}\n\nexport const Configuration = /* @__PURE__ */ new ConfigurationSingleton()\n","/**\n * Vio REST API client — talks to `api-staging.vio.live` (or override).\n *\n * Endpoints (mirrors the iOS SDK's surface):\n * GET /v2/mobile/config bootstrap (sponsors + market)\n * GET /v2/mobile/campaigns/:id/components placement components (TBD)\n * POST /v2/mobile/campaigns/:id/cart-intent cross-device cart-intent (TBD)\n *\n * Auth: `X-API-Key: <apiKey>` header (the top-level Vio apiKey).\n *\n * Note: until the backend exposes a dedicated `/v2/web/*` surface we\n * reuse the `/v2/mobile/*` paths — the apiKey identifies the client_app\n * and the response shape is platform-agnostic enough.\n */\n\nimport type {\n BootstrapResponse,\n ManifestRequest,\n ManifestResult,\n PlacementComponent,\n SurfaceResponse,\n} from '../types.js'\n\nexport interface VioApiOptions {\n /** REST API base URL, e.g. `https://api-staging.vio.live`. */\n apiBase: string\n /** Top-level Vio apiKey for this client app. */\n apiKey: string\n}\n\nexport class VioApi {\n private readonly apiBase: string\n private readonly apiKey: string\n\n constructor(options: VioApiOptions) {\n if (!options.apiBase) throw new Error('[VioApi] apiBase is required')\n if (!options.apiKey) throw new Error('[VioApi] apiKey is required')\n this.apiBase = options.apiBase.replace(/\\/+$/, '')\n this.apiKey = options.apiKey\n }\n\n /**\n * Bootstrap — fetches client app config (sponsors with commerce keys,\n * default market, campaign id). Called once at SDK init.\n *\n * With `platform`, `campaigns[].slots[]` only lists the assignments of that\n * platform (plus the ones with no platform) — see ADR-0027.\n */\n async bootstrap(platform?: string): Promise<BootstrapResponse> {\n const query = platform ? `?platform=${encodeURIComponent(platform)}` : ''\n return this.get<BootstrapResponse>(`/v2/mobile/config${query}`)\n }\n\n /**\n * Declare the slots of this page to the campaigns service\n * (`POST /v2/mobile/components/manifest`, ADR-0034). The web SDK always\n * sends `mode: 'merge'`; see `Vio.declareSlots()` for the dedupe on top.\n */\n async declareManifest(body: ManifestRequest): Promise<ManifestResult> {\n return this.post<ManifestResult>('/v2/mobile/components/manifest', body)\n }\n\n /**\n * The surface of the key (`GET /v2/mobile/surface`): its id, name, status\n * and `privacyMode` — what decides whether the order attribution may carry\n * the entry context (ADR-0035). A 404 means a service that predates it.\n */\n async surface(): Promise<SurfaceResponse> {\n return this.get<SurfaceResponse>('/v2/mobile/surface')\n }\n\n /**\n * Get placement components for a campaign. Used by the carousel auto-fetch\n * mode (`<vio-product-carousel campaign-id=\"36\" location=\"news-favorites\">`).\n */\n async getComponents(campaignId: number | string): Promise<PlacementComponent[]> {\n const path = `/v2/mobile/campaigns/${encodeURIComponent(String(campaignId))}/components`\n const res = await this.get<{ components: PlacementComponent[] } | PlacementComponent[]>(path)\n return Array.isArray(res) ? res : (res?.components ?? [])\n }\n\n // MARK: - HTTP plumbing\n\n private async get<T>(path: string): Promise<T> {\n const url = `${this.apiBase}${path}`\n const res = await fetch(url, {\n method: 'GET',\n headers: {\n 'X-API-Key': this.apiKey,\n Accept: 'application/json',\n },\n })\n if (!res.ok) {\n throw new VioApiError(res.status, await safeText(res), `GET ${path}`)\n }\n return (await res.json()) as T\n }\n\n private async post<T>(path: string, body: unknown): Promise<T> {\n const url = `${this.apiBase}${path}`\n const res = await fetch(url, {\n method: 'POST',\n headers: {\n 'X-API-Key': this.apiKey,\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(body),\n })\n if (!res.ok) {\n throw new VioApiError(res.status, await safeText(res), `POST ${path}`)\n }\n return (await res.json()) as T\n }\n}\n\nexport class VioApiError extends Error {\n constructor(\n public readonly status: number,\n public readonly body: string,\n public readonly endpoint: string,\n ) {\n super(`[VioApi] ${endpoint} → HTTP ${status}: ${body.slice(0, 200)}`)\n this.name = 'VioApiError'\n }\n}\n\nasync function safeText(res: Response): Promise<string> {\n try {\n return await res.text()\n } catch {\n return ''\n }\n}\n\nexport function createVioApi(options: VioApiOptions): VioApi {\n return new VioApi(options)\n}\n","/**\n * Vio types — Product / Sponsor / Bootstrap shapes.\n *\n * Product types mirror the Vio Commerce GraphQL schema.\n * Sponsor / Bootstrap shapes mirror the iOS SDK's bootstrap response so\n * we stay aligned cross-platform.\n */\n\nexport type ImageSize = 'thumbnail' | 'small' | 'medium' | 'large' | 'full'\n\nexport interface ProductPrice {\n amount: number\n currency_code: string\n compare_at?: number | null\n amount_incl_taxes?: number | null\n compare_at_incl_taxes?: number | null\n tax_amount?: number | null\n tax_rate?: number | null\n}\n\nexport interface ProductImage {\n id: string\n url: string\n width?: number | null\n height?: number | null\n order?: number | null\n}\n\nexport interface ProductOption {\n id: number\n name: string\n order: number\n values: string[]\n}\n\nexport interface ProductCategory {\n id: number\n name: string\n}\n\nexport interface ProductVariant {\n id: number\n barcode?: string | null\n quantity?: number | null\n sku?: string | null\n title?: string | null\n price: ProductPrice\n images: ProductImage[]\n}\n\nexport interface Product {\n id: number\n brand?: string | null\n title: string\n description?: string | null\n tags?: string | null\n sku: string\n quantity?: number | null\n price: ProductPrice\n variants: ProductVariant[]\n barcode?: string | null\n options: ProductOption[]\n categories?: ProductCategory[] | null\n images: ProductImage[]\n}\n\n/** Per-sponsor commerce config sourced from Vio bootstrap. */\nexport interface SponsorCommerceBlock {\n apiKey: string\n channelId?: string | null\n paymentMethods?: string[]\n}\n\nexport interface Sponsor {\n id: number\n name: string\n description?: string | null\n avatarUrl?: string | null\n logoUrl?: string | null\n primaryColor?: string | null\n secondaryColor?: string | null\n /** The brand's purchase terms (its own page, e.g. its shop's terms of service). */\n termsUrl?: string | null\n /** The brand's returns / refund policy page. */\n refundPolicyUrl?: string | null\n commerce: SponsorCommerceBlock\n}\n\n/**\n * `campaign` of `GET /v2/mobile/config`: the head of the surface's default\n * campaign (the one `primarySponsor` / `secondarySponsors` belong to).\n */\nexport interface BootstrapCampaign {\n id: number\n name: string\n logo?: string | null\n isActive?: boolean\n isPaused?: boolean\n startDate?: string | null\n endDate?: string | null\n}\n\n/** Campaign status as the backend computes it (`[startsAt, endsAt)`). */\nexport type BootstrapCampaignStatus = 'scheduled' | 'active' | 'paused' | 'ended'\n\n/** A slot assignment of a campaign on this surface (`campaigns[].slots[]`). */\nexport interface BootstrapSlot {\n name: string\n platform?: string | null\n startDate?: string | null\n endDate?: string | null\n /** Who assigned it: the dashboard (always wins) or a page's own campaign (campaigns micro PR #16). */\n source?: 'dashboard' | 'page' | null\n}\n\n/**\n * One entry of `campaigns[]`: every active campaign of the surface, with its\n * own sponsors — a sponsor may live only in a non-default campaign.\n */\nexport interface BootstrapCampaignEntry extends BootstrapCampaign {\n isDefault?: boolean\n status?: BootstrapCampaignStatus\n primarySponsor?: Sponsor | null\n secondarySponsors?: Sponsor[]\n slots?: BootstrapSlot[]\n}\n\n/**\n * Response shape of `GET /v2/mobile/config` (and likely future `/v2/web/config`).\n * Matches the iOS SDK's `SdkBootstrapResponse` model.\n *\n * `campaign` + `primarySponsor` + `secondarySponsors` describe the surface's\n * default campaign; `campaigns[]` lists every active one. There is no\n * top-level `campaignId` — the id lives in `campaign.id`.\n */\nexport interface BootstrapResponse {\n endpoints?: {\n webSocketBase?: string\n commerceGraphQL?: string\n }\n /**\n * `null` when the surface has no active campaign: a web, custom-web or Vev\n * page then keeps selling with the sponsors of the surface's channels\n * (`noActiveCampaign: true`, `campaigns: []`), and nothing it sells carries\n * a campaign. Native apps get a 404 instead.\n */\n campaign?: BootstrapCampaign | null\n /** True when `campaign` is null on purpose: no campaign is active on the surface. */\n noActiveCampaign?: boolean\n primarySponsor?: Sponsor\n secondarySponsors?: Sponsor[]\n features?: {\n shoppable?: boolean\n lineup?: boolean\n }\n campaigns?: BootstrapCampaignEntry[]\n market?: {\n countryCode: string\n currencyCode: string\n }\n /**\n * The surface of the key, when the bootstrap says it (the campaigns\n * service answers it on `/v2/mobile/surface` today; here when it adds it).\n * Its `privacyMode` decides what the order attribution may carry.\n */\n surface?: SurfaceResponse['surface']\n}\n\n/**\n * A slot this page declares to the campaigns service (ADR-0027 / ADR-0034):\n * `id` is the slot name (≤ 100 chars, what `vio-slot` carries and what the\n * dashboard assigns a campaign to); `displayName` is only for the dashboard.\n */\nexport interface ManifestLocation {\n id: string\n displayName?: string\n /** The campaign this location belongs to when it differs from the page's (`ManifestRequest.campaignId`). */\n campaignId?: number\n /** The kind of element the slot holds — `card` | `carousel` | `detail` for the SDK's, a host's own word otherwise. For the dashboard. */\n kind?: string\n}\n\n/**\n * Where something happened, as `Vio.attribution(slot)` answers it — the ONE\n * attribution shape the SDK elements, Vev and Replit all use: the place\n * (`slot`), the campaign that place shows right now and its primary sponsor,\n * and the content (article) the page is. Everything optional: `{}` before the\n * bootstrap, except the content.\n */\nexport interface Attribution {\n slot?: string\n campaignId?: number\n sponsorId?: number\n contentId?: string\n contentTitle?: string\n /** The page's URL within the 2 048 cap (`content_url`) — what Commerce keeps on the order and its lines. */\n contentUrl?: string\n}\n\n/**\n * How much context analytics and Commerce may keep of a visit to this\n * surface. `minimal` drops what says WHICH screen someone was on and WHY —\n * the page (`content_url`, `content_title`), the slot (`location_id`) and\n * the entry (referrer, utm, landing page) — the collector drops it from the\n * events on its side (vio-analytics `privacy.ts`); the SDK keeps it off the\n * order and off the cart lines it sends to Commerce. What measures the\n * funnel and bills the sale stays: the surface, the campaign, the kind of\n * component, the products and the amounts. A mode the SDK could not learn\n * counts as `minimal`.\n */\nexport type SurfacePrivacyMode = 'standard' | 'minimal'\n\n/** Response of `GET /v2/mobile/surface`: what the key may know of its own surface. */\nexport interface SurfaceResponse {\n surface?: {\n id?: number\n name?: string\n status?: string\n privacyMode?: SurfacePrivacyMode | string | null\n } | null\n}\n\n/** Body of `POST /v2/mobile/components/manifest`. */\nexport interface ManifestRequest {\n platform: string\n /**\n * `merge` upserts the slots without deprecating those of other pages (a\n * surface on the web has many pages, each knowing only its own blocks);\n * `replace` (the native SDKs' mode) deprecates whatever is not listed.\n */\n mode: 'merge' | 'replace'\n locations: ManifestLocation[]\n /**\n * The campaign the PAGE belongs to (`Vio.init({ campaignId })`): the micro\n * assigns every declared location to it (`source: 'page'`) unless the\n * dashboard already assigned that slot.\n */\n campaignId?: number\n}\n\n/** Response of `POST /v2/mobile/components/manifest`. */\nexport interface ManifestResult {\n clientAppId: number\n platform: string\n mode: 'merge' | 'replace'\n locations: Array<{\n id: number | string\n locationId: string\n displayName?: string | null\n /**\n * What the micro did with the page's campaign for this slot: `created` /\n * `kept` / `replaced` a page assignment, `dashboard` (the dashboard's\n * assignment stands — the page's campaign is ignored there), `none`.\n */\n assignment?: 'created' | 'kept' | 'replaced' | 'dashboard' | 'none'\n }>\n deprecatedCount: number\n warnings: Array<{ kind: string; detail: string }>\n}\n\n/**\n * A placement component returned by `/v2/mobile/campaigns/:id/components`.\n * Used by `<vio-product-carousel campaign-id=\"...\">` to know which products\n * to render at a given slot.\n */\nexport interface PlacementComponent {\n id: number\n componentType: string\n locationId: string\n sponsorId?: number\n config: {\n productIds?: number[]\n [key: string]: unknown\n }\n}\n\n/** Helper: extract a useful display price from a Product. */\nexport function displayPrice(product: Product): string {\n const p = product.price\n const amount = p.amount_incl_taxes ?? p.amount\n return formatPrice(amount, p.currency_code)\n}\n\n/**\n * Active shipping/market country for the page. The host (e.g. the Vev Config\n * block) sets `globalThis.__VIO_COUNTRY__` / localStorage `vio.country`; falls\n * back to NO.\n */\nexport function getGlobalCountryCode(): string {\n const g = globalThis as { __VIO_COUNTRY__?: string }\n if (g.__VIO_COUNTRY__) return g.__VIO_COUNTRY__\n if (typeof localStorage !== 'undefined') {\n try {\n const v = localStorage.getItem('vio.country')\n if (v) return v\n } catch {\n /* privacy mode */\n }\n }\n return 'NO'\n}\n\n/**\n * Active display locale for the page (number formatting + payment sheets).\n * Host sets `globalThis.__VIO_LOCALE__` / localStorage `vio.locale`; falls\n * back to nb-NO.\n */\nexport function getGlobalLocale(): string {\n const g = globalThis as { __VIO_LOCALE__?: string }\n if (g.__VIO_LOCALE__) return g.__VIO_LOCALE__\n if (typeof localStorage !== 'undefined') {\n try {\n const v = localStorage.getItem('vio.locale')\n if (v) return v\n } catch {\n /* privacy mode */\n }\n }\n return 'nb-NO'\n}\n\n/**\n * Currency symbol for display. With no explicit currency, a host-set override\n * (`__VIO_SYMBOL__` / vio.symbol) wins; otherwise a small per-currency map.\n */\nexport function getGlobalSymbol(currency?: string): string {\n const activeCurrency = currency || getGlobalCurrency()\n const g = globalThis as { __VIO_SYMBOL__?: string }\n if (!currency && g.__VIO_SYMBOL__) return g.__VIO_SYMBOL__\n if (!currency && typeof localStorage !== 'undefined') {\n try {\n const v = localStorage.getItem('vio.symbol')\n if (v) return v\n } catch {\n /* privacy mode */\n }\n }\n const curr = String(activeCurrency).toUpperCase()\n if (curr === 'NOK' || curr === 'DKK') return 'Kr'\n if (curr === 'SEK') return 'SEK'\n if (curr === 'EUR') return '€'\n if (curr === 'USD' || curr === 'CAD') return '$'\n if (curr === 'GBP') return '£'\n if (curr === 'CHF') return 'CHF'\n return activeCurrency\n}\n\n/**\n * Active display currency for the page. The host (e.g. the Vev Config block)\n * sets `globalThis.__VIO_CURRENCY__` / localStorage `vio.currency`; falls back\n * to NOK.\n */\nexport function getGlobalCurrency(): string {\n const g = globalThis as { __VIO_CURRENCY__?: string }\n if (g.__VIO_CURRENCY__) return g.__VIO_CURRENCY__\n if (typeof localStorage !== 'undefined') {\n try {\n const v = localStorage.getItem('vio.currency')\n if (v) return v\n } catch {\n /* privacy mode */\n }\n }\n return 'NOK'\n}\n\n/** Cache of validated locales — hosts can feed anything into vio.locale. */\nconst validatedLocales = new Map<string, string>()\n\n/** Return the locale if Intl accepts it, else nb-NO (a host-set `nb_NO` with\n * an underscore makes toLocaleString throw and blanks the whole render). */\nfunction safeLocale(locale: string): string {\n const cached = validatedLocales.get(locale)\n if (cached) return cached\n let resolved = 'nb-NO'\n try {\n if (Intl.NumberFormat.supportedLocalesOf([locale]).length > 0) resolved = locale\n } catch {\n /* structurally invalid tag — keep the fallback */\n }\n validatedLocales.set(locale, resolved)\n return resolved\n}\n\n/** Format a numeric amount + currency using the page locale and symbol map. */\nexport function formatPrice(amount: number, currency?: string): string {\n const activeCurrency = currency || getGlobalCurrency()\n const activeLocale = safeLocale(getGlobalLocale())\n const activeSymbol = getGlobalSymbol(activeCurrency)\n const formatted = amount\n .toLocaleString(activeLocale, { minimumFractionDigits: 0, maximumFractionDigits: 2 })\n // Normalize non-breaking space to regular space for predictable rendering.\n .replace(/ /g, ' ')\n return `${formatted} ${activeSymbol}`\n}\n\n/**\n * Helper: pick the first image URL (variant first, then product). Defensive:\n * accepts loose shapes (backend cart rows, catalog rows) where images may be\n * plain strings or live under image / imageUrl / image_url / primaryImage.\n */\nexport function primaryImageUrl(product: Product): string | undefined {\n /* eslint-disable @typescript-eslint/no-explicit-any */\n const p = product as any\n if (!p || typeof p !== 'object') return undefined\n if (Array.isArray(p.variants) && p.variants.length > 0) {\n const vImages = p.variants[0]?.images\n if (Array.isArray(vImages) && vImages.length > 0) {\n const vUrl = typeof vImages[0] === 'string' ? vImages[0] : vImages[0]?.url\n if (vUrl) return vUrl\n }\n }\n if (Array.isArray(p.images) && p.images.length > 0) {\n const img0 = p.images[0]\n const url = typeof img0 === 'string' ? img0 : img0?.url\n if (url) return url\n }\n if (typeof p.image === 'string' && p.image) return p.image\n if (p.image && typeof p.image === 'object' && p.image.url) return p.image.url\n if (typeof p.imageUrl === 'string' && p.imageUrl) return p.imageUrl\n if (typeof p.image_url === 'string' && p.image_url) return p.image_url\n if (typeof p.primaryImage === 'string' && p.primaryImage) return p.primaryImage\n if (p.primaryImage && typeof p.primaryImage === 'object' && p.primaryImage.url) {\n return p.primaryImage.url\n }\n return undefined\n /* eslint-enable @typescript-eslint/no-explicit-any */\n}\n","/**\n * Commerce GraphQL client — talks to Vio Commerce.\n *\n * Mirrors the iOS SDK's `SdkClient.channel.product` surface, but uses\n * `graphql-request` (lightweight) instead of Apollo. Auth header: `Authorization: <apiKey>`\n * (per-sponsor commerce apiKey, NOT the top-level Vio apiKey).\n *\n * Usage:\n * const commerce = createCommerceClient({\n * endpoint: 'https://graph-ql-dev.vio.live',\n * apiKey: '<sponsor-commerce-apiKey>', // sponsor's commerce apiKey\n * })\n * const products = await commerce.channel.product.getByIds({\n * product_ids: [408895, 408896],\n * currency: 'NOK',\n * image_size: 'large',\n * })\n */\n\nimport { GraphQLClient } from 'graphql-request'\nimport { getGlobalCountryCode, getGlobalCurrency, type ImageSize, type Product } from '../types.js'\n\nexport interface CommerceClientOptions {\n /** Vio Commerce GraphQL endpoint, e.g. `https://graph-ql-dev.vio.live`. */\n endpoint: string\n /** Per-sponsor commerce apiKey (from bootstrap.primarySponsor.commerce.apiKey). */\n apiKey: string\n}\n\nconst GET_PRODUCTS_BY_IDS = /* GraphQL */ `\n query GetProductsByIds(\n $currency: String\n $imageSize: ImageSize\n $productIds: [Int!]\n $useCache: Boolean!\n $shippingCountryCode: String\n ) {\n Channel {\n GetProductsByIds(\n currency: $currency\n image_size: $imageSize\n product_ids: $productIds\n useCache: $useCache\n shipping_country_code: $shippingCountryCode\n ) {\n id\n brand\n title\n description\n tags\n sku\n quantity\n price {\n amount\n currency_code\n compare_at\n amount_incl_taxes\n compare_at_incl_taxes\n tax_amount\n tax_rate\n }\n variants {\n id\n barcode\n quantity\n sku\n title\n price {\n amount\n currency_code\n compare_at\n amount_incl_taxes\n compare_at_incl_taxes\n tax_amount\n tax_rate\n }\n images {\n id\n url\n width\n height\n order\n }\n }\n barcode\n options {\n id\n name\n order\n values\n }\n categories {\n id\n name\n }\n images {\n id\n url\n width\n height\n order\n }\n }\n }\n }\n`\n\n/**\n * Only the seller's Company name of a product (Settings → Company), for the\n * header of the product detail. Apart from GET_PRODUCTS_BY_IDS on purpose:\n * `supplier_company` is new (2026-10-08), and an API without it fails the\n * whole query — here that costs the header its name, there it would cost\n * the product.\n */\nconst GET_PRODUCT_SELLER = /* GraphQL */ `\n query GetProductSeller($productIds: [Int!], $useCache: Boolean!) {\n Channel {\n GetProductsByIds(product_ids: $productIds, useCache: $useCache) {\n id\n supplier_company\n }\n }\n }\n`\n\nexport interface GetProductsByIdsOptions {\n product_ids: number[]\n currency?: string | null\n image_size?: ImageSize | null\n useCache?: boolean\n shipping_country_code?: string | null\n}\n\nclass ChannelProduct {\n constructor(private readonly client: GraphQLClient) {}\n\n /**\n * Fetch a batch of products by their numeric ids.\n * Returns an empty array if no ids are provided.\n */\n async getByIds(options: GetProductsByIdsOptions): Promise<Product[]> {\n if (!options.product_ids || options.product_ids.length === 0) return []\n\n const variables = {\n productIds: options.product_ids,\n // Page-level currency/country defaults (multi-market support).\n currency: options.currency ?? getGlobalCurrency(),\n imageSize: options.image_size ?? 'large',\n useCache: options.useCache ?? true,\n shippingCountryCode: options.shipping_country_code ?? getGlobalCountryCode(),\n }\n\n const data = await this.client.request<{\n Channel: { GetProductsByIds: Product[] }\n }>(GET_PRODUCTS_BY_IDS, variables)\n\n return data.Channel?.GetProductsByIds ?? []\n }\n\n /**\n * The seller's Company name for one product, or null (none set, or an API\n * that does not have the field yet). Never throws.\n *\n * Never from the cache, on purpose: graphql caches product answers by\n * path whatever fields the query asked, so this narrow query, written to\n * the cache, would hand the next full product query a product with no\n * price and no images. `useCache: false` neither reads nor writes it.\n */\n async getSellerCompany(productId: number): Promise<string | null> {\n try {\n const data = await this.client.request<{\n Channel: { GetProductsByIds: Array<{ id: number; supplier_company?: string | null }> }\n }>(GET_PRODUCT_SELLER, { productIds: [productId], useCache: false })\n const name = String(data.Channel?.GetProductsByIds?.[0]?.supplier_company ?? '').trim()\n return name || null\n } catch {\n return null\n }\n }\n}\n\nclass Channel {\n readonly product: ChannelProduct\n\n constructor(client: GraphQLClient) {\n this.product = new ChannelProduct(client)\n }\n}\n\n/** CommerceClient — namespaced facade, mirrors the iOS SdkClient. */\nexport class CommerceClient {\n readonly channel: Channel\n /** Underlying graphql-request client (escape hatch for custom queries). */\n readonly raw: GraphQLClient\n\n constructor(options: CommerceClientOptions) {\n if (!options.endpoint) throw new Error('[VioCommerce] endpoint is required')\n if (!options.apiKey) throw new Error('[VioCommerce] apiKey is required')\n\n this.raw = new GraphQLClient(options.endpoint, {\n headers: { Authorization: options.apiKey },\n })\n this.channel = new Channel(this.raw)\n }\n}\n\nexport function createCommerceClient(options: CommerceClientOptions): CommerceClient {\n return new CommerceClient(options)\n}\n","/**\n * Content (article) attribution — the other half of \"where did this happen\".\n *\n * The SLOT says the place on the page (`carousel-1`, `hero`); the CONTENT says\n * the article/page the place was rendered in. One Vev design serves thousands\n * of article URLs, so the article must not leak into the slot id — it travels\n * on every analytics event as `content_id` / `content_title` instead, and this\n * module finds it without the editor doing anything.\n *\n * Pure: `resolveContent()` takes the document and location (defaults to the\n * globals) so it can be tested, never throws, and answers `{}` where there is\n * no DOM (SSR, node tests). `Vio.content()` resolves it live on every call —\n * an SPA route change or a new title is seen on the next event.\n */\n\nexport interface ContentRef {\n id?: string\n title?: string\n /** The page's URL as origin + path (no query, no fragment), capped — what the order and the cart's origins carry as `content_url`. */\n url?: string\n}\n\nexport interface ContentInit {\n contentId?: string | number | null\n contentTitle?: string | null\n}\n\n/** The URL query parameters a host can set per page. */\nexport const CONTENT_ID_QUERY = 'vio_content'\nexport const CONTENT_TITLE_QUERY = 'vio_content_title'\n\n/**\n * The collector's caps (vio-analytics `analytics-schema.ts`): an event with a\n * longer `content_id` is rejected whole, silently. A candidate id that does\n * not fit is skipped — the next source is tried — never cut, since a cut\n * canonical URL is not the article any more. Titles are cut.\n */\nexport const CONTENT_ID_MAX_LENGTH = 128\nexport const CONTENT_TITLE_MAX_LENGTH = 255\n/** The collector (and Commerce's `order.content_url`) cap `content_url` at 2 048 chars. */\nexport const CONTENT_URL_MAX_LENGTH = 2_048\n\n/**\n * A page as the ORDER and the cart's origins name it (`content_url` to\n * Commerce): origin + path — no query string, no fragment — within the cap.\n * The query is where a page carries e-mails, tokens and tracking tails\n * (`?email=…&utm_…#frag`); none of that belongs on an order row. A site whose\n * article lives in the query or the hash identifies it through `contentId`\n * (`Vio.init({ contentId })`, `?vio_content=`), not through the URL. Also\n * the shape of the landing's referrer and page (client-context.ts).\n */\nexport function originAndPath(raw: unknown, max: number = CONTENT_URL_MAX_LENGTH): string | undefined {\n const value = text(raw)\n if (!value) return undefined\n try {\n const url = new URL(value)\n return cutTo(`${url.origin}${url.pathname}`, max)\n } catch {\n // Not an absolute URL (an old engine, a scheme-less value): without its query and fragment.\n const end = value.search(/[?#]/)\n return cutTo(end >= 0 ? value.slice(0, end) : value, max)\n }\n}\n\nfunction cutTo(value: string, max: number): string | undefined {\n const out = value.length > max ? value.slice(0, max) : value\n return out || undefined\n}\n\n/**\n * A page URL within the cap for the analytics EVENTS — as is, else without\n * its query string (a long one is usually the tracking tail, not the page),\n * else cut. The collector keeps the query there (`page_views` strip it\n * themselves); the order does not (`originAndPath`).\n */\nexport function capContentUrl(value: unknown): string | undefined {\n const url = text(value)\n if (!url) return undefined\n if (url.length <= CONTENT_URL_MAX_LENGTH) return url\n const cut = url.search(/[?#]/)\n const withoutQuery = cut >= 0 ? url.slice(0, cut) : url\n return withoutQuery.length <= CONTENT_URL_MAX_LENGTH ? withoutQuery : withoutQuery.slice(0, CONTENT_URL_MAX_LENGTH)\n}\n\n/**\n * Id: `Vio.init({ contentId })` → `?vio_content=` → `<meta name=\"vio:content-id\">`\n * → `<link rel=\"canonical\">` href or `<meta property=\"og:url\">` (without query\n * and hash) → `location.pathname`.\n * Title: `Vio.init({ contentTitle })` → `?vio_content_title=` →\n * `<meta name=\"vio:content-title\">` → `<meta property=\"og:title\">` → `document.title`.\n */\nexport function resolveContent(\n init?: ContentInit | null,\n doc: Document | null | undefined = typeof document !== 'undefined' ? document : null,\n loc: Location | { href?: string; pathname?: string; search?: string } | null | undefined = typeof location !==\n 'undefined'\n ? location\n : null,\n): ContentRef {\n const out: ContentRef = {}\n try {\n // The URL first: a document that throws below must not cost the page.\n // Origin + path: what the order and the cart's origins carry.\n const url = originAndPath(loc?.href)\n if (url !== undefined) out.url = url\n } catch {\n /* no location */\n }\n try {\n const query = parseQuery(loc?.search)\n const id =\n fits(text(init?.contentId)) ??\n fits(text(query.get(CONTENT_ID_QUERY))) ??\n fits(text(meta(doc, 'name', 'vio:content-id'))) ??\n fits(stripQueryAndHash(text(attr(doc, 'link[rel=\"canonical\"]', 'href')))) ??\n fits(stripQueryAndHash(text(meta(doc, 'property', 'og:url')))) ??\n fits(text(loc?.pathname))\n const title =\n text(init?.contentTitle) ??\n text(query.get(CONTENT_TITLE_QUERY)) ??\n text(meta(doc, 'name', 'vio:content-title')) ??\n text(meta(doc, 'property', 'og:title')) ??\n text(doc?.title)\n if (id !== undefined) out.id = id\n if (title !== undefined) out.title = title.slice(0, CONTENT_TITLE_MAX_LENGTH)\n return out\n } catch {\n return out\n }\n}\n\n/** The candidate when it fits the collector's id cap; `undefined` (= try the next) otherwise. */\nfunction fits(value: string | undefined): string | undefined {\n return value !== undefined && value.length <= CONTENT_ID_MAX_LENGTH ? value : undefined\n}\n\nfunction text(value: unknown): string | undefined {\n if (value === undefined || value === null) return undefined\n const s = String(value).trim()\n return s ? s : undefined\n}\n\nfunction parseQuery(search: string | null | undefined): URLSearchParams {\n try {\n return new URLSearchParams(typeof search === 'string' ? search : '')\n } catch {\n return new URLSearchParams()\n }\n}\n\nfunction meta(doc: Document | null | undefined, key: 'name' | 'property', value: string): string | undefined {\n return attr(doc, `meta[${key}=\"${value}\"]`, 'content')\n}\n\nfunction attr(doc: Document | null | undefined, selector: string, name: string): string | undefined {\n try {\n if (!doc || typeof doc.querySelector !== 'function') return undefined\n const el = doc.querySelector(selector)\n const v = el?.getAttribute?.(name)\n return typeof v === 'string' ? v : undefined\n } catch {\n return undefined\n }\n}\n\n/** `https://host/a/b?x=1#y` → `https://host/a/b`; untouched when it has neither. */\nfunction stripQueryAndHash(url: string | undefined): string | undefined {\n if (!url) return undefined\n const cut = url.search(/[?#]/)\n const clean = cut >= 0 ? url.slice(0, cut) : url\n return clean.trim() || undefined\n}\n","/**\n * A line origin as Commerce receives it (ADR-0035 phase B): `origin` on each\n * line of `AddItem` and, when the quantity goes UP, on `UpdateItem` — the\n * origin of the units that update adds. shopcart keeps every origin of a\n * line with its units (`cart_item.origins`) and writes the order from them:\n * `order_item.campaign_id` / `location_id` / `component_kind`, and the\n * order's page when the checkout does not name one.\n *\n * snake_case on the wire, the caps of shopcart's `LineOriginDto` enforced\n * here, once. Pure: `lineOriginWire()` takes the origin and the page.\n */\n\nimport { CONTENT_TITLE_MAX_LENGTH, originAndPath, resolveContent, type ContentRef } from '../content.js'\nimport { SLOT_ID_MAX_LENGTH, SLOT_KIND_MAX_LENGTH, componentKindOf } from '../slots.js'\nimport type { SurfacePrivacyMode } from '../types.js'\nimport type { CartOrigin } from './types.js'\n\n/** The largest `Int` GraphQL coerces; a bigger id would fail the whole mutation. */\nexport const GRAPHQL_INT_MAX = 2_147_483_647\n\n/** `LineOriginDto` (shopcart `cart/dtos/send/line-origin.dto.ts`). */\nexport interface LineOriginWire {\n campaign_id?: number\n location_id?: string\n component_kind?: string\n content_url?: string\n content_title?: string\n}\n\n/** The caps of `LineOriginDto` — a longer value is refused whole by the API, so it is cut here. */\nexport const LINE_ORIGIN_CAPS = Object.freeze({\n locationId: SLOT_ID_MAX_LENGTH,\n componentKind: SLOT_KIND_MAX_LENGTH,\n contentUrl: 2_048,\n contentTitle: CONTENT_TITLE_MAX_LENGTH,\n})\n\n/** The page the units are added from, for an origin that does not carry its own. */\nexport interface OriginPage {\n contentUrl?: string\n contentTitle?: string\n}\n\nexport interface LineOriginWireOptions {\n /** The current page, for an origin that does not carry its own. */\n page?: OriginPage\n /**\n * The surface's privacy mode. Only on a `standard` surface do the slot\n * (`location_id`) and the page (`content_url`, `content_title`) travel —\n * which screen a unit was sold from is what `minimal` keeps private, the\n * same promise the collector keeps for the events. `campaign_id` and\n * `component_kind` always do. Default `unknown`: fail closed.\n */\n privacyMode?: SurfacePrivacyMode | 'unknown'\n}\n\n/**\n * The origin for the wire, or `undefined` when the SDK knows no PLACE for the\n * units — no campaign, no slot, no kind of element (a host adding with no\n * attribution): then nothing is sent and the line inherits the order's\n * campaign on the server. The page is the origin's own when it has one — the\n * page the units were added from — else the current page's, as origin + path;\n * `campaign_id` only as a positive `Int` (the DTO's `@IsInt() @Min(1)`, the\n * gateway's 32-bit coercion).\n */\nexport function lineOriginWire(\n origin: CartOrigin | null | undefined,\n options: LineOriginWireOptions = {},\n): LineOriginWire | undefined {\n if (!origin || typeof origin !== 'object') return undefined\n const page = options.page ?? {}\n const standard = options.privacyMode === 'standard'\n const out: LineOriginWire = {}\n const campaignId = Number(origin.campaignId)\n if (Number.isInteger(campaignId) && campaignId > 0 && campaignId <= GRAPHQL_INT_MAX) out.campaign_id = campaignId\n const locationId = cut(origin.slot, LINE_ORIGIN_CAPS.locationId)\n if (locationId && standard) out.location_id = locationId\n // The kind the element said, else the kind word in the slot id — the\n // collector's rule, so the order line and `breakdown?by=component_kind` agree.\n const kind = cut(origin.componentKind, LINE_ORIGIN_CAPS.componentKind) ?? componentKindOf(undefined, origin.slot)\n if (kind) out.component_kind = kind\n if (!out.campaign_id && !out.location_id && !out.component_kind) return undefined\n if (!standard) return out\n const url = originAndPath(origin.contentUrl, LINE_ORIGIN_CAPS.contentUrl) ?? originAndPath(page.contentUrl, LINE_ORIGIN_CAPS.contentUrl)\n if (url) out.content_url = url\n const title = cut(origin.contentTitle, LINE_ORIGIN_CAPS.contentTitle) ?? cut(page.contentTitle, LINE_ORIGIN_CAPS.contentTitle)\n if (title) out.content_title = title\n return out\n}\n\n/**\n * The current page as `OriginPage`: what `Vio.content()` answers (the init\n * options included) when the facade is on the page, else `resolveContent()`\n * — its url (origin + path, capped) and title; `{}` without a document.\n */\nexport function currentOriginPage(): OriginPage {\n const out: OriginPage = {}\n try {\n const facade = (globalThis as { __VIO_FACADE__?: { content?: () => ContentRef } }).__VIO_FACADE__\n const content = typeof facade?.content === 'function' ? facade.content() : resolveContent()\n const url = originAndPath(content?.url, LINE_ORIGIN_CAPS.contentUrl)\n if (url) out.contentUrl = url\n const title = cut(content?.title, LINE_ORIGIN_CAPS.contentTitle)\n if (title) out.contentTitle = title\n } catch {\n /* no page to speak of */\n }\n return out\n}\n\nfunction cut(value: unknown, max: number): string | undefined {\n if (typeof value !== 'string' && typeof value !== 'number') return undefined\n const text = String(value).trim()\n if (!text) return undefined\n return text.length > max ? text.slice(0, max).trim() || undefined : text\n}\n\n/**\n * The surface's privacy mode as the facade knows it, for the cart's lines:\n * the answer the facade preloaded at `Vio.init()` (`privacyMode()` resolves\n * at once when it is known, and never waits more than the preload's cap);\n * `unknown` — fail closed — without a facade or when it cannot tell.\n */\nexport async function currentPrivacyMode(): Promise<SurfacePrivacyMode | 'unknown'> {\n try {\n const facade = (globalThis as { __VIO_FACADE__?: { privacyMode?: () => Promise<unknown> | unknown } }).__VIO_FACADE__\n if (typeof facade?.privacyMode !== 'function') return 'unknown'\n const mode = await facade.privacyMode()\n return mode === 'standard' || mode === 'minimal' ? mode : 'unknown'\n } catch {\n return 'unknown'\n }\n}\n","/**\n * The buyer reference — shopcart's `buyer_ref`: the keyed hash Commerce\n * computes from the buyer's email, so one person is one ref across orders,\n * devices and platforms, and nothing in it can be turned back into an email\n * without Commerce's secret. The SDK forwards it as analytics `buyer_id`\n * (EVENTS_CONTRACT `commerce.buyer_id`, ≤ 128 chars in the collector's\n * schema) and never puts anything else in its place: an email, a name, an\n * over-long value are dropped — not hashed client-side, not cut (a cut hash\n * is another identity).\n */\n\nexport const BUYER_REF_MAX_LENGTH = 128\n\n/** What a reference is made of: the unreserved URL characters. An email, a name, a sentence never match. */\nconst BUYER_REF_PATTERN = /^[A-Za-z0-9._~-]+$/\n\n/** The reference when `value` is one; `undefined` for anything else (never an email). */\nexport function normalizeBuyerRef(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined\n const ref = value.trim()\n if (!ref || ref.length > BUYER_REF_MAX_LENGTH || !BUYER_REF_PATTERN.test(ref)) return undefined\n return ref\n}\n","/**\n * What the commerce gateway may not know yet.\n *\n * The SDK ships ahead of the gateway more than once a quarter: a selection\n * (`buyer_ref`, 2026-10-19), an argument (`origin` on the cart lines,\n * `attribution` on the checkout — ADR-0035 phase B). A gateway that does not\n * have the field refuses the WHOLE operation at validation — before anything\n * runs, with no `data` — so each such operation is sent again without the\n * field, once, and the answer remembered for the page load. An operation that\n * DID run and failed is never repeated: for a mutation that would be a second\n * charge, a second line in the cart.\n *\n * One mechanism for all of them, so the next field costs a token here and a\n * call to `withGatewayFeature`, not a new copy of the retry.\n */\n\nexport type GatewayFeature = 'buyer_ref' | 'line_origin' | 'checkout_attribution'\n\n/**\n * What the gateway's validation error names when it does not know the\n * feature: the field or argument first, then the input types the SDK\n * declares for it (a variable of an unknown type fails on the TYPE's name).\n * The type names are the ones `vio-live/graphql#30` (`schema.gql`) defines —\n * `gateway-schema.contract.test.ts` checks them against that schema; a rename\n * there makes the SDK fall back to the legacy shape — and say so in the\n * console — until it is updated here.\n */\nconst FEATURE_TOKENS: Readonly<Record<GatewayFeature, readonly string[]>> = {\n buyer_ref: ['buyer_ref'],\n line_origin: ['origin', 'CartLineOriginInput'],\n checkout_attribution: ['attribution', 'CheckoutAttributionInput', 'CheckoutAttributionEntryInput'],\n}\n\n/** The names a feature goes by on the gateway: its field or argument, then its input types (tests). */\nexport function featureTokens(feature: GatewayFeature): readonly string[] {\n return FEATURE_TOKENS[feature]\n}\n\n/** What a gateway says of a field, argument or type it does not have. */\nconst UNKNOWN_PATTERN =\n /cannot query field|unknown field|unknown argument|unknown type|is not defined by type|not defined by type|field \"[^\"]+\" is not defined/i\n\nconst refused = new Set<GatewayFeature>()\nconst warned = new Set<GatewayFeature>()\n\n/** Whether this page load still expects the gateway to know `feature` (false once it refused it). */\nexport function gatewayHas(feature: GatewayFeature): boolean {\n return !refused.has(feature)\n}\n\n/** Forget what this page load learned (tests). One feature, or all of them. */\nexport function resetGatewayFeatures(feature?: GatewayFeature): void {\n if (feature) {\n refused.delete(feature)\n warned.delete(feature)\n return\n }\n refused.clear()\n warned.clear()\n}\n\n/**\n * What `executeCartGraphQL` attaches to the error it throws: whether the\n * envelope carried data, and its errors — their `path` included, since an\n * error WITH a path is one a resolver raised (something ran), even when the\n * envelope's `data` is null (a non-null root that failed).\n */\nexport interface GraphQLErrorInfo {\n hasData: boolean\n errors: Array<{ message?: string; path?: unknown }>\n}\n\n/** The messages an error carries: its own and the envelope's, when it has one. */\nfunction messagesOf(err: unknown): string[] {\n if (!err || typeof err !== 'object') return []\n const { message, graphql } = err as { message?: unknown; graphql?: Partial<GraphQLErrorInfo> }\n return [message, ...(graphql?.errors ?? []).map((e) => e?.message)].filter(\n (m): m is string => typeof m === 'string',\n )\n}\n\n/**\n * True when the operation ran: the envelope carried data, or an error names\n * a `path` — Apollo answers `data: null` plus errors with a path when a\n * resolver failed, and that is a failure of something that executed, never a\n * refused selection. A validation error has `locations`, never a `path`.\n */\nfunction ranSomething(err: unknown): boolean {\n if (!err || typeof err !== 'object') return false\n const graphql = (err as { graphql?: Partial<GraphQLErrorInfo> }).graphql\n if (graphql?.hasData === true) return true\n return (graphql?.errors ?? []).some((e) => Array.isArray(e?.path) && e.path.length > 0)\n}\n\n/**\n * True when `err` is the gateway refusing something it does not know, named\n * `token` (`Cannot query field \"buyer_ref\" on type …`, `Unknown argument\n * \"origin\" on field …`, `Unknown type \"CartLineOriginInput\"`, `Field \"origin\" is\n * not defined by type \"LineItemInput\"`): a validation error, with no `data`\n * and no `path` because nothing ran — safe to send again without it, a\n * mutation included. Anything that ran (data present, or an error with a\n * path) or any other message is not.\n */\nexport function isUnknownTokenError(err: unknown, token: string): boolean {\n if (ranSomething(err)) return false\n return messagesOf(err).some((m) => m.includes(`\"${token}\"`) && UNKNOWN_PATTERN.test(m))\n}\n\n/** `isUnknownTokenError` for any of the names a feature goes by. */\nexport function isUnknownFeatureError(err: unknown, feature: GatewayFeature): boolean {\n return FEATURE_TOKENS[feature].some((token) => isUnknownTokenError(err, token))\n}\n\n/**\n * Runs `request(true)` (the operation with the feature); when the gateway\n * does not know it, `request(false)` (without it) — and from then on, for\n * this page load, straight to the latter. Said once in the console: a\n * gateway behind the SDK is worth knowing about, and so is a renamed type.\n */\nexport async function withGatewayFeature<T>(\n feature: GatewayFeature,\n request: (supported: boolean) => Promise<T>,\n): Promise<T> {\n if (!gatewayHas(feature)) return request(false)\n try {\n return await request(true)\n } catch (err) {\n if (!isUnknownFeatureError(err, feature)) throw err\n refused.add(feature)\n if (!warned.has(feature) && typeof console !== 'undefined') {\n warned.add(feature)\n console.warn(\n `[Vio] the commerce gateway does not know \"${FEATURE_TOKENS[feature][0]}\" (${feature}) yet — sent without it on this page load:`,\n messagesOf(err)[0] ?? '',\n )\n }\n return request(false)\n }\n}\n","// GraphQL Queries and Mutations for VIO Cart & Checkout Services\n\nexport const CREATE_CART_MUTATION = `\nmutation CreateCart($customerSessionId: String!, $currency: String!, $shippingCountry: String) {\n Cart {\n CreateCart(customer_session_id: $customerSessionId, currency: $currency, shipping_country: $shippingCountry) {\n cart_id\n customer_session_id\n shipping_country\n line_items {\n id\n supplier\n image {\n id\n url\n width\n height\n }\n sku\n barcode\n brand\n product_id\n title\n variant_id\n variant_title\n variant {\n option\n value\n }\n quantity\n price {\n amount\n currency_code\n discount\n compare_at\n compare_at_incl_taxes\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n shipping {\n id\n name\n description\n price {\n amount\n currency_code\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n }\n available_shippings {\n id\n name\n description\n country_code\n price {\n amount\n currency_code\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n }\n }\n subtotal\n shipping\n currency\n available_shipping_countries\n }\n }\n}\n`;\n\nexport const ADD_ITEM_MUTATION = `\nmutation AddItem($cartId: String!, $lineItems: [LineItemInput!]!) {\n Cart {\n AddItem(cart_id: $cartId, line_items: $lineItems) {\n cart_id\n customer_session_id\n shipping_country\n line_items {\n id\n supplier\n image {\n id\n url\n width\n height\n }\n sku\n barcode\n brand\n product_id\n title\n variant_id\n variant_title\n variant {\n option\n value\n }\n quantity\n price {\n amount\n currency_code\n discount\n compare_at\n compare_at_incl_taxes\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n shipping {\n id\n name\n description\n price {\n amount\n currency_code\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n }\n available_shippings {\n id\n name\n description\n country_code\n price {\n amount\n currency_code\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n }\n }\n subtotal\n shipping\n currency\n available_shipping_countries\n }\n }\n}\n`;\n\nexport const DELETE_ITEM_MUTATION = `\nmutation DeleteItem($cartId: String!, $cartItemId: String!) {\n Cart {\n DeleteItem(cart_id: $cartId, cart_item_id: $cartItemId) {\n cart_id\n customer_session_id\n shipping_country\n line_items {\n id\n supplier\n image {\n id\n url\n width\n height\n }\n sku\n barcode\n brand\n product_id\n title\n variant_id\n variant_title\n variant {\n option\n value\n }\n quantity\n price {\n amount\n currency_code\n discount\n compare_at\n compare_at_incl_taxes\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n shipping {\n id\n name\n description\n price {\n amount\n currency_code\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n }\n available_shippings {\n id\n name\n description\n country_code\n price {\n amount\n currency_code\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n }\n }\n subtotal\n shipping\n currency\n available_shipping_countries\n }\n }\n}\n`;\n\n/** With `origin` — where the units a quantity increase adds come from (ADR-0035 phase B, gateway-features `line_origin`) — or without it, for a gateway that predates it. */\nconst updateItemMutation = (withExtra: boolean) => `\nmutation UpdateItem($cartId: String!, $cartItemId: String!, $shippingId: String, $qty: Int${withExtra ? ', $origin: CartLineOriginInput' : ''}) {\n Cart {\n UpdateItem(cart_id: $cartId, cart_item_id: $cartItemId, shipping_id: $shippingId, qty: $qty${withExtra ? ', origin: $origin' : ''}) {\n cart_id\n customer_session_id\n shipping_country\n line_items {\n id\n supplier\n image {\n id\n url\n width\n height\n }\n sku\n barcode\n brand\n product_id\n title\n variant_id\n variant_title\n variant {\n option\n value\n }\n quantity\n price {\n amount\n currency_code\n discount\n compare_at\n compare_at_incl_taxes\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n shipping {\n id\n name\n description\n price {\n amount\n currency_code\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n }\n available_shippings {\n id\n name\n description\n country_code\n price {\n amount\n currency_code\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n }\n }\n subtotal\n shipping\n currency\n available_shipping_countries\n }\n }\n}\n`\nexport const UPDATE_ITEM_MUTATION = updateItemMutation(false)\n/** `UpdateItem` with the `origin` of the added units (`CartLineOriginInput`, snake_case fields — see `lineOriginWire`). */\nexport const UPDATE_ITEM_WITH_ORIGIN_MUTATION = updateItemMutation(true)\n\nexport const GET_CART_QUERY = `\nquery GetCart($cartId: String!) {\n Cart {\n GetCart(cart_id: $cartId) {\n cart_id\n customer_session_id\n shipping_country\n line_items {\n id\n supplier\n image {\n id\n url\n width\n height\n }\n sku\n barcode\n brand\n product_id\n title\n variant_id\n variant_title\n variant {\n option\n value\n }\n quantity\n price {\n amount\n currency_code\n discount\n compare_at\n compare_at_incl_taxes\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n shipping {\n id\n name\n description\n price {\n amount\n currency_code\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n }\n available_shippings {\n id\n name\n description\n country_code\n price {\n amount\n currency_code\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n }\n }\n subtotal\n shipping\n currency\n available_shipping_countries\n }\n }\n}\n`;\n\nexport const GET_LINE_ITEMS_BY_SUPPLIER_QUERY = `\nquery GetLineItemsBySupplier($cartId: String!) {\n Cart {\n GetLineItemsBySupplier(cart_id: $cartId) {\n supplier {\n id\n name\n }\n available_shippings {\n id\n name\n description\n country_code\n price {\n amount\n currency_code\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n }\n line_items {\n id\n supplier\n image {\n id\n url\n width\n height\n }\n sku\n barcode\n brand\n product_id\n title\n variant_id\n variant_title\n variant {\n option\n value\n }\n quantity\n price {\n amount\n currency_code\n discount\n compare_at\n compare_at_incl_taxes\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n shipping {\n id\n name\n description\n price {\n amount\n currency_code\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n }\n }\n }\n }\n}\n`;\n\nexport const UPDATE_SHIPPINGS_BY_SUPPLIER_MUTATION = `\nmutation UpdateShippingsBySupplier($cartId: String!, $data: [DataUpdateShippingsBySupplier!]!) {\n Cart {\n UpdateShippingsBySupplier(cart_id: $cartId, data: $data) {\n cart_id\n customer_session_id\n shipping_country\n line_items {\n id\n supplier\n image {\n id\n url\n width\n height\n }\n sku\n barcode\n brand\n product_id\n title\n variant_id\n variant_title\n variant {\n option\n value\n }\n quantity\n price {\n amount\n currency_code\n discount\n compare_at\n compare_at_incl_taxes\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n shipping {\n id\n name\n description\n price {\n amount\n currency_code\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n }\n available_shippings {\n id\n name\n description\n country_code\n price {\n amount\n currency_code\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n }\n }\n subtotal\n shipping\n currency\n available_shipping_countries\n }\n }\n}\n`;\n\n/** With `attribution` — the surface, the page's campaign, the page and the entry the order is born with (ADR-0035 phase B, gateway-features `checkout_attribution`) — or without it, for a gateway that predates it. */\nconst createCheckoutMutation = (withExtra: boolean) => `\nmutation CreateCheckout($cartId: String!${withExtra ? ', $attribution: CheckoutAttributionInput' : ''}) {\n Checkout {\n CreateCheckout(cart_id: $cartId${withExtra ? ', attribution: $attribution' : ''}) {\n buyer_accepts_purchase_conditions\n buyer_accepts_terms_conditions\n created_at\n updated_at\n id\n deleted_at\n success_url\n cancel_url\n payment_method\n email\n status\n checkout_url\n origin_payment_id\n billing_address {\n id\n first_name\n last_name\n phone_code\n phone\n company\n address1\n address2\n city\n province\n province_code\n country\n country_code\n zip\n }\n shipping_address {\n id\n first_name\n last_name\n phone_code\n phone\n company\n address1\n address2\n city\n province\n province_code\n country\n country_code\n zip\n }\n available_payment_methods {\n name\n }\n discount_code\n cart {\n cart_id\n customer_session_id\n shipping_country\n line_items {\n id\n supplier\n image {\n id\n url\n width\n height\n }\n sku\n barcode\n brand\n product_id\n title\n variant_id\n variant_title\n variant {\n option\n value\n }\n quantity\n price {\n amount\n currency_code\n discount\n compare_at\n compare_at_incl_taxes\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n shipping {\n id\n name\n description\n price {\n amount\n currency_code\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n }\n available_shippings {\n id\n name\n description\n country_code\n price {\n amount\n currency_code\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n }\n }\n subtotal\n shipping\n currency\n available_shipping_countries\n }\n totals {\n currency_code\n subtotal\n shipping\n total\n taxes\n tax_rate\n discounts\n }\n }\n }\n}\n`\nexport const CREATE_CHECKOUT_MUTATION = createCheckoutMutation(false)\n/** `CreateCheckout` with the checkout's `attribution` (`CheckoutAttributionInput`, snake_case fields — see `checkoutAttributionOf`). */\nexport const CREATE_CHECKOUT_WITH_ATTRIBUTION_MUTATION = createCheckoutMutation(true)\n\n/** With `attribution` (the checkout's, merged key by key on the server) or without it, for a gateway that predates it. */\nconst updateCheckoutMutation = (withExtra: boolean) => `\nmutation UpdateCheckout($checkoutId: String!, $status: String, $successUrl: String, $email: String, $cancelUrl: String, $paymentMethod: String, $shippingAddress: AddressArgs, $billingAddress: AddressArgs, $buyerAcceptsPurchaseConditions: Boolean, $buyerAcceptsTermsConditions: Boolean${withExtra ? ', $attribution: CheckoutAttributionInput' : ''}) {\n Checkout {\n UpdateCheckout(checkout_id: $checkoutId, status: $status, success_url: $successUrl, email: $email, cancel_url: $cancelUrl, payment_method: $paymentMethod, shipping_address: $shippingAddress, billing_address: $billingAddress, buyer_accepts_purchase_conditions: $buyerAcceptsPurchaseConditions, buyer_accepts_terms_conditions: $buyerAcceptsTermsConditions${withExtra ? ', attribution: $attribution' : ''}) {\n buyer_accepts_purchase_conditions\n buyer_accepts_terms_conditions\n created_at\n updated_at\n id\n deleted_at\n success_url\n cancel_url\n payment_method\n email\n status\n checkout_url\n origin_payment_id\n billing_address {\n id\n first_name\n last_name\n phone_code\n phone\n company\n address1\n address2\n city\n province\n province_code\n country\n country_code\n zip\n }\n shipping_address {\n id\n first_name\n last_name\n phone_code\n phone\n company\n address1\n address2\n city\n province\n province_code\n country\n country_code\n zip\n }\n available_payment_methods {\n name\n }\n discount_code\n cart {\n cart_id\n customer_session_id\n shipping_country\n line_items {\n id\n supplier\n image {\n id\n url\n width\n height\n }\n sku\n barcode\n brand\n product_id\n title\n variant_id\n variant_title\n variant {\n option\n value\n }\n quantity\n price {\n amount\n currency_code\n discount\n compare_at\n compare_at_incl_taxes\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n shipping {\n id\n name\n description\n price {\n amount\n currency_code\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n }\n available_shippings {\n id\n name\n description\n country_code\n price {\n amount\n currency_code\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n }\n }\n subtotal\n shipping\n currency\n available_shipping_countries\n }\n totals {\n currency_code\n subtotal\n shipping\n total\n taxes\n tax_rate\n discounts\n }\n }\n }\n}\n`\nexport const UPDATE_CHECKOUT_MUTATION = updateCheckoutMutation(false)\n/** `UpdateCheckout` with the checkout's `attribution` (`CheckoutAttributionInput`). */\nexport const UPDATE_CHECKOUT_WITH_ATTRIBUTION_MUTATION = updateCheckoutMutation(true)\n\nexport const GET_CHECKOUT_QUERY = `\nquery GetCheckout($checkoutId: String!) {\n Checkout {\n GetCheckout(checkout_id: $checkoutId) {\n buyer_accepts_purchase_conditions\n buyer_accepts_terms_conditions\n created_at\n updated_at\n id\n deleted_at\n success_url\n cancel_url\n payment_method\n email\n status\n checkout_url\n origin_payment_id\n duplicate_of\n billing_address {\n id\n first_name\n last_name\n phone_code\n phone\n company\n address1\n address2\n city\n province\n province_code\n country\n country_code\n zip\n }\n shipping_address {\n id\n first_name\n last_name\n phone_code\n phone\n company\n address1\n address2\n city\n province\n province_code\n country\n country_code\n zip\n }\n available_payment_methods {\n name\n }\n discount_code\n cart {\n cart_id\n customer_session_id\n shipping_country\n line_items {\n id\n supplier\n image {\n id\n url\n width\n height\n }\n sku\n barcode\n brand\n product_id\n title\n variant_id\n variant_title\n variant {\n option\n value\n }\n quantity\n price {\n amount\n currency_code\n discount\n compare_at\n compare_at_incl_taxes\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n shipping {\n id\n name\n description\n price {\n amount\n currency_code\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n }\n available_shippings {\n id\n name\n description\n country_code\n price {\n amount\n currency_code\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n }\n }\n subtotal\n shipping\n currency\n available_shipping_countries\n }\n totals {\n currency_code\n subtotal\n shipping\n total\n taxes\n tax_rate\n discounts\n }\n }\n }\n}\n`;\n\nexport const GET_AVAILABLE_PAYMENT_METHODS_QUERY = `\nquery Config {\n Payment {\n GetAvailablePaymentMethods {\n config {\n name\n type\n value\n }\n name\n }\n }\n}\n`;\n\n\n/**\n * Server-side cart / checkout GraphQL client (Vio Commerce).\n *\n * Ported from the hand-edited Vev bundle (Alan, 2026-07-28/29) into the SDK\n * source so the vendored bundle stays a pure esbuild artifact.\n */\n\nimport { Configuration } from '../configuration.js'\nimport { normalizeBuyerRef } from '../buyer-ref.js'\nimport { getGlobalCountryCode, getGlobalCurrency } from '../types.js'\nimport {\n gatewayHas,\n isUnknownTokenError,\n resetGatewayFeatures,\n withGatewayFeature,\n type GraphQLErrorInfo,\n} from './gateway-features.js'\nimport type { LineOriginWire } from '../cart/origin-wire.js'\nimport type { CheckoutAttributionWire } from '../checkout/attribution.js'\n\n/** Transport options for a cart/checkout GraphQL call. */\nexport interface CartQueryOptions {\n endpoint?: string\n apiKey?: string\n /** Sponsor commerce key — goes in the Authorization header. */\n commerceKey?: string\n /** True when the commerce key came from a resolved sponsor (bootstrap).\n * False = we fell back to the host apiKey — writes like CreateCart should\n * NOT proceed with the wrong key (the cart would be orphaned). */\n sponsorResolved?: boolean\n}\n\n/**\n * Resolve endpoint + keys for cart GraphQL calls. Awaits Vio.bootstrap() once\n * if it hasn't run yet (the sponsor commerce keys come from bootstrap), then\n * uses the sponsor's commerce apiKey (via the Vio facade on globalThis,\n * avoiding an import cycle); falls back to the host apiKey.\n */\nexport async function getCartGraphQLOptions(sponsorId?: number): Promise<CartQueryOptions> {\n const facade = (\n globalThis as {\n __VIO_FACADE__?: {\n findSponsor?: (id: number) => unknown\n bootstrap?: () => Promise<unknown>\n bootstrapCache?: unknown\n }\n }\n ).__VIO_FACADE__\n // Hosts that mount several independent components (Vev blocks mount in no\n // guaranteed order) may have one query the commerce API before another has\n // called Vio.init(). Wait for initialization FIRST: bootstrap needs the\n // apiKey, so attempting it before init throws \"Not initialized\", and it used\n // to be attempted here and never retried. The sponsor then stayed unknown,\n // `commerceKey` fell back to the platform apiKey, and every commerce call\n // answered \"Authentication failed\" — a wrong key, not a missing one, which\n // is why it read as a credentials problem instead of a load-order one.\n if (!Configuration.isInitialized) {\n await Configuration.whenReady()\n }\n\n // Only now can bootstrap succeed. Without it there is no sponsor, and\n // without a sponsor there is no commerce key.\n if (\n Configuration.isInitialized &&\n facade &&\n typeof facade.bootstrap === 'function' &&\n !facade.bootstrapCache\n ) {\n try {\n await facade.bootstrap()\n } catch (err) {\n if (typeof console !== 'undefined') {\n console.warn('[Vio] getCartGraphQLOptions bootstrap failed:', err)\n }\n }\n }\n\n const cfg = Configuration.isInitialized\n ? Configuration.get()\n : { apiKey: undefined, graphQLBase: 'https://graph-ql-dev.vio.live' }\n const anyCfg = cfg as { apiKey?: string; graphQLBase?: string }\n let commerceKey = anyCfg.apiKey\n let sponsorResolved = false\n if (sponsorId && typeof facade?.findSponsor === 'function') {\n const sponsor = facade.findSponsor(sponsorId) as\n | { commerce?: { apiKey?: string } }\n | undefined\n if (sponsor?.commerce?.apiKey) {\n commerceKey = sponsor.commerce.apiKey\n sponsorResolved = true\n }\n }\n if (sponsorId && !sponsorResolved && typeof console !== 'undefined') {\n // Say it plainly: the call is about to go out with the platform key, which\n // commerce rejects. Silence here is what made this look like bad\n // credentials for a whole day.\n console.warn(\n `[Vio] no commerce key for sponsor ${sponsorId} — falling back to the ` +\n 'platform apiKey, which the commerce API will reject. Is the sponsor ' +\n 'configured, and did Vio.init run before this call?',\n )\n }\n return {\n endpoint: anyCfg.graphQLBase || 'https://graph-ql-dev.vio.live',\n apiKey: anyCfg.apiKey,\n commerceKey,\n sponsorResolved,\n }\n}\n\nconst CUSTOMER_SESSION_KEY = 'vio.customer_session_id.v1'\n\n/** Stable per-browser customer session id (backend CreateCart requires one). */\nexport function getCustomerSessionId(): string {\n if (typeof localStorage === 'undefined') return 'cs_session_default'\n let id = localStorage.getItem(CUSTOMER_SESSION_KEY)\n if (!id) {\n id = 'cs_' + Math.random().toString(36).slice(2, 11) + Date.now().toString(36)\n localStorage.setItem(CUSTOMER_SESSION_KEY, id)\n }\n return id\n}\n\ninterface GraphQLEnvelope {\n data?: Record<string, Record<string, unknown>> | null\n errors?: Array<{ message?: string; path?: unknown }>\n}\n\n/** Upper bound for one commerce GraphQL round trip. A request that never\n * answers would otherwise pin a line's quantity sync — and anything awaiting\n * `waitForCartMutations`, i.e. the checkout — forever; past this it rejects\n * like any other failure and the caller reconciles from the server. */\nexport const CART_GRAPHQL_TIMEOUT_MS = 15_000\n\n/** Execute a GraphQL query/mutation against the configured commerce endpoint.\n * Callers that skip `getCartGraphQLOptions()` (or pass a bare sponsorId) get\n * it resolved here instead of silently sending an unauthenticated request.\n * Rejects after `CART_GRAPHQL_TIMEOUT_MS` (and aborts the fetch). */\nexport async function executeCartGraphQL(\n query: string,\n variables: Record<string, unknown>,\n options: CartQueryOptions | number | undefined = {},\n): Promise<GraphQLEnvelope> {\n const resolvedOptions: CartQueryOptions =\n typeof options === 'number'\n ? await getCartGraphQLOptions(options)\n : !options.apiKey && !options.commerceKey\n ? { ...(await getCartGraphQLOptions()), ...options }\n : options\n const { endpoint = 'https://graph-ql-dev.vio.live', apiKey, commerceKey } = resolvedOptions\n\n const headers: Record<string, string> = { 'Content-Type': 'application/json' }\n if (apiKey) headers['X-API-Key'] = apiKey\n if (commerceKey || apiKey) headers['Authorization'] = (commerceKey || apiKey) as string\n\n // Own timer + AbortController rather than AbortSignal.timeout: the race also\n // covers a fetch that ignores the signal (polyfills, mocks), and the timer\n // is an ordinary setTimeout, so it can be tested with fake timers.\n const controller = typeof AbortController !== 'undefined' ? new AbortController() : undefined\n let timer: ReturnType<typeof setTimeout> | undefined\n const timedOut = new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n controller?.abort()\n reject(new Error(`GraphQL request timed out after ${CART_GRAPHQL_TIMEOUT_MS}ms`))\n }, CART_GRAPHQL_TIMEOUT_MS)\n })\n try {\n const res = await Promise.race([\n fetch(endpoint, {\n method: 'POST',\n headers,\n body: JSON.stringify({ query, variables }),\n signal: controller?.signal,\n }),\n timedOut,\n ])\n const json = (await Promise.race([res.json().catch(() => ({})), timedOut])) as GraphQLEnvelope\n if (!res.ok || json.errors) {\n const errMsg = json.errors?.[0]?.message || `GraphQL request failed (HTTP ${res.status})`\n // What the envelope says travels with the error — whether anything ran\n // (`data`, or an error with a `path`) and the errors, never the data\n // itself — so a caller can tell a validation error (the gateway refused\n // the selection, nothing ran) from a failure of something that did run;\n // see gateway-features `isUnknownTokenError`.\n throw Object.assign(new Error(errMsg), {\n graphql: { hasData: json.data !== undefined && json.data !== null, errors: json.errors ?? [] },\n })\n }\n return json\n } finally {\n clearTimeout(timer)\n }\n}\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nexport async function createCart(\n customerSessionId: string,\n currency: string,\n shippingCountry?: string | null,\n options?: CartQueryOptions,\n): Promise<any> {\n const json = await executeCartGraphQL(\n CREATE_CART_MUTATION,\n {\n customerSessionId,\n currency: currency || getGlobalCurrency(),\n shippingCountry: shippingCountry || getGlobalCountryCode(),\n },\n options,\n )\n return json?.data?.Cart?.CreateCart\n}\n\n/**\n * `AddItem`. A line may carry `origin` (`LineOriginWire`: where its units\n * come from — ADR-0035 phase B). A gateway that predates the field refuses\n * the whole mutation at validation (`LineItemInput` has no `origin`), so the\n * lines are sent again without it, once per page load — see gateway-features.\n */\nexport async function addItem(\n cartId: string,\n lineItems: unknown[],\n options?: CartQueryOptions,\n): Promise<any> {\n const attributed = lineItems.some((li) => !!(li as { origin?: unknown } | null)?.origin)\n const json = attributed\n ? await withGatewayFeature('line_origin', (supported) =>\n executeCartGraphQL(\n ADD_ITEM_MUTATION,\n { cartId, lineItems: supported ? lineItems : lineItems.map(withoutOrigin) },\n options,\n ),\n )\n : await executeCartGraphQL(ADD_ITEM_MUTATION, { cartId, lineItems }, options)\n return json?.data?.Cart?.AddItem\n}\n\n/** A line item without its `origin` — the legacy `LineItemInput`. */\nfunction withoutOrigin(lineItem: unknown): unknown {\n if (!lineItem || typeof lineItem !== 'object') return lineItem\n const { origin: _origin, ...rest } = lineItem as { origin?: unknown }\n return rest\n}\n\nexport async function deleteItem(\n cartId: string,\n cartItemId: string,\n options?: CartQueryOptions,\n): Promise<any> {\n const json = await executeCartGraphQL(DELETE_ITEM_MUTATION, { cartId, cartItemId }, options)\n return json?.data?.Cart?.DeleteItem\n}\n\n/**\n * `UpdateItem`. `extra.origin` is where the units a quantity INCREASE adds\n * come from (ADR-0035 phase B); the server credits the new units to it. Sent\n * only with it; a gateway that predates the argument gets the legacy\n * mutation instead, once per page load — see gateway-features.\n */\nexport async function updateItem(\n cartId: string,\n cartItemId: string,\n shippingId?: string | null,\n qty?: number | null,\n options?: CartQueryOptions,\n extra: { origin?: LineOriginWire } = {},\n): Promise<any> {\n const variables = { cartId, cartItemId, shippingId: shippingId || null, qty: qty != null ? qty : null }\n const origin = extra.origin\n const json = origin\n ? await withGatewayFeature('line_origin', (supported) =>\n executeCartGraphQL(\n supported ? UPDATE_ITEM_WITH_ORIGIN_MUTATION : UPDATE_ITEM_MUTATION,\n supported ? { ...variables, origin } : variables,\n options,\n ),\n )\n : await executeCartGraphQL(UPDATE_ITEM_MUTATION, variables, options)\n return json?.data?.Cart?.UpdateItem\n}\n\nexport async function getCart(cartId: string, options?: CartQueryOptions): Promise<any> {\n const json = await executeCartGraphQL(GET_CART_QUERY, { cartId }, options)\n return json?.data?.Cart?.GetCart\n}\n\nexport async function getLineItemsBySupplier(\n cartId: string,\n options?: CartQueryOptions,\n): Promise<any> {\n const json = await executeCartGraphQL(GET_LINE_ITEMS_BY_SUPPLIER_QUERY, { cartId }, options)\n return json?.data?.Cart?.GetLineItemsBySupplier\n}\n\nexport async function updateShippingsBySupplier(\n cartId: string,\n data: unknown[],\n options?: CartQueryOptions,\n): Promise<any> {\n const json = await executeCartGraphQL(\n UPDATE_SHIPPINGS_BY_SUPPLIER_MUTATION,\n { cartId, data },\n options,\n )\n return json?.data?.Cart?.UpdateShippingsBySupplier\n}\n\n/**\n * `CreateCheckout`. With `extra.attribution` (`CheckoutAttributionWire`:\n * the surface, the page's campaign, the page and the entry — ADR-0035 phase\n * B) the checkout is born attributed; a gateway that predates the argument\n * gets the legacy mutation, once per page load — see gateway-features.\n */\nexport async function createCheckout(\n cartId: string,\n options?: CartQueryOptions,\n extra: { attribution?: CheckoutAttributionWire } = {},\n): Promise<any> {\n const attribution = extra.attribution\n const json = attribution\n ? await withGatewayFeature('checkout_attribution', (supported) =>\n executeCartGraphQL(\n supported ? CREATE_CHECKOUT_WITH_ATTRIBUTION_MUTATION : CREATE_CHECKOUT_MUTATION,\n supported ? { cartId, attribution } : { cartId },\n options,\n ),\n )\n : await executeCartGraphQL(CREATE_CHECKOUT_MUTATION, { cartId }, options)\n return json?.data?.Checkout?.CreateCheckout\n}\n\n/**\n * `UpdateCheckout`. `variables.attribution` (`CheckoutAttributionWire`) is\n * merged key by key over what the checkout has; a gateway that predates the\n * argument gets the legacy mutation without it, once per page load.\n */\nexport async function updateCheckout(\n variables: Record<string, unknown>,\n options?: CartQueryOptions,\n): Promise<any> {\n const { attribution, ...legacy } = variables\n const json = attribution\n ? await withGatewayFeature('checkout_attribution', (supported) =>\n executeCartGraphQL(\n supported ? UPDATE_CHECKOUT_WITH_ATTRIBUTION_MUTATION : UPDATE_CHECKOUT_MUTATION,\n supported ? variables : legacy,\n options,\n ),\n )\n : await executeCartGraphQL(UPDATE_CHECKOUT_MUTATION, legacy, options)\n return json?.data?.Checkout?.UpdateCheckout\n}\n\nexport async function getCheckout(checkoutId: string, options?: CartQueryOptions): Promise<any> {\n const json = await executeCartGraphQL(GET_CHECKOUT_QUERY, { checkoutId }, options)\n return json?.data?.Checkout?.GetCheckout\n}\n\n// ── buyer_ref: a selection the gateway may not know yet ─────────────────────\n\n/**\n * shopcart's buyer reference (`buyer_ref`, the keyed hash of the buyer's\n * email — analytics `buyer_id`, see core/buyer-ref.ts) is new on the gateway\n * (2026-10-19) and selected on three answers: the order number query, the\n * Apple Pay confirmation and the Klarna native confirmation. A gateway that\n * does not have the field yet refuses the WHOLE operation at validation —\n * before anything runs — so each of them is sent again without the field,\n * once, and the answer remembered for the page load (gateway-features, the\n * same mechanism the cart's `origin` and the checkout's `attribution` use).\n * A confirmation that DID run and failed is never repeated: that would\n * charge twice.\n */\nexport const BUYER_REF_FIELD = 'buyer_ref'\n\n/** Whether this page load still expects the gateway to know `buyer_ref` (false once it refused the selection). */\nexport function gatewayHasBuyerRef(): boolean {\n return gatewayHas('buyer_ref')\n}\n\n/** Forget what this page load learned about `buyer_ref` (tests). */\nexport function resetBuyerRefSupport(): void {\n resetGatewayFeatures('buyer_ref')\n}\n\nexport type { GraphQLErrorInfo }\n\n/**\n * True when `err` is the gateway refusing a selection it does not know\n * (`Cannot query field \"buyer_ref\" on type …`): a validation error, with no\n * `data` because nothing ran — safe to send again without the field, a\n * mutation included. Anything that ran (data present) or any other message\n * is not. (`isUnknownTokenError` of gateway-features, by field name.)\n */\nexport function isUnknownFieldError(err: unknown, field: string): boolean {\n return isUnknownTokenError(err, field)\n}\n\n/**\n * Runs `request(true)` (the selection with `buyer_ref`); when the gateway does\n * not know the field, `request(false)` (without it) — and from then on, for\n * this page load, straight to the latter.\n */\nexport function withBuyerRef<T>(request: (withBuyerRef: boolean) => Promise<T>): Promise<T> {\n return withGatewayFeature('buyer_ref', request)\n}\n\n/**\n * Only the Vio order number of a checkout (#4497) and its buyer reference.\n * Apart from GET_CHECKOUT_QUERY on purpose: `order_id` is new (2026-10-08),\n * `buyer_ref` newer (2026-10-19), and an API that does not have them yet\n * fails the WHOLE query — here that costs a line on the receipt, there it\n * would cost the payment check.\n */\nconst orderNumberQuery = (withRef: boolean) => `\nquery GetCheckoutOrderNumber($checkoutId: String!) {\n Checkout {\n GetCheckout(checkout_id: $checkoutId) {\n id\n order_id${withRef ? `\\n ${BUYER_REF_FIELD}` : ''}\n }\n }\n}\n`\nexport const GET_CHECKOUT_ORDER_NUMBER_QUERY = orderNumberQuery(true)\n/** The same selection for a gateway that predates `buyer_ref`. */\nexport const GET_CHECKOUT_ORDER_NUMBER_QUERY_LEGACY = orderNumberQuery(false)\n\n/** What a checkout says of itself after paying: its Vio order number, once the order exists, and its buyer reference. */\nexport interface CheckoutReference {\n orderNumber: number | null\n buyerRef: string | null\n}\n\n/** The order number (null while the order does not exist yet) and the buyer reference (null when the API does not say it). */\nexport async function getCheckoutReference(\n checkoutId: string,\n options?: CartQueryOptions,\n): Promise<CheckoutReference> {\n const json = await withBuyerRef((withRef) =>\n executeCartGraphQL(\n withRef ? GET_CHECKOUT_ORDER_NUMBER_QUERY : GET_CHECKOUT_ORDER_NUMBER_QUERY_LEGACY,\n { checkoutId },\n options,\n ),\n )\n const checkout = (json?.data as any)?.Checkout?.GetCheckout\n const n = Number(checkout?.order_id)\n return {\n orderNumber: Number.isInteger(n) && n > 0 ? n : null,\n buyerRef: normalizeBuyerRef(checkout?.[BUYER_REF_FIELD]) ?? null,\n }\n}\n\n/** The Vio order number, or null while the order does not exist yet. */\nexport async function getCheckoutOrderNumber(\n checkoutId: string,\n options?: CartQueryOptions,\n): Promise<number | null> {\n return (await getCheckoutReference(checkoutId, options)).orderNumber\n}\n\nexport async function getAvailablePaymentMethods(options?: CartQueryOptions): Promise<any> {\n const json = await executeCartGraphQL(GET_AVAILABLE_PAYMENT_METHODS_QUERY, {}, options)\n return json?.data?.Payment?.GetAvailablePaymentMethods\n}\n\nexport const CREATE_PAYMENT_STRIPE_MUTATION = `\nmutation CreatePaymentStripe($checkoutId: String!, $successUrl: String!, $paymentMethod: String!, $email: String!) {\n Payment {\n CreatePaymentStripe(checkout_id: $checkoutId, success_url: $successUrl, payment_method: $paymentMethod, email: $email) {\n order_id\n checkout_url\n }\n }\n}\n`\n\nexport async function createPaymentStripe(\n variables: Record<string, unknown>,\n options?: CartQueryOptions,\n): Promise<any> {\n const json = await executeCartGraphQL(CREATE_PAYMENT_STRIPE_MUTATION, variables, options)\n return json?.data?.Payment?.CreatePaymentStripe\n}\n\nexport const CREATE_PAYMENT_APPLE_PAY_MUTATION = `\nmutation CreatePaymentApplePay($checkoutId: String!) {\n Payment {\n CreatePaymentApplePay(checkout_id: $checkoutId) {\n gateway\n gateway_merchant_id\n }\n }\n}\n`\n\n/** Register the Apple Pay payment on the backend checkout. Returns the gateway\n * info (gateway + gateway_merchant_id) the sheet/session should use. */\nexport async function createPaymentApplePay(\n variables: Record<string, unknown>,\n options?: CartQueryOptions,\n): Promise<any> {\n const json = await executeCartGraphQL(CREATE_PAYMENT_APPLE_PAY_MUTATION, variables, options)\n return json?.data?.Payment?.CreatePaymentApplePay\n}\n\nconst confirmApplePayMutation = (withRef: boolean) => `\nmutation ConfirmPaymentApplePay($checkoutId: String!, $applePayToken: String!, $email: String, $shippingAddress: ApplePayAddressInput) {\n Payment {\n ConfirmPaymentApplePay(checkout_id: $checkoutId, apple_pay_token: $applePayToken, email: $email, shipping_address: $shippingAddress) {\n order_id\n status${withRef ? `\\n ${BUYER_REF_FIELD}` : ''}\n }\n }\n}\n`\nexport const CONFIRM_PAYMENT_APPLE_PAY_MUTATION = confirmApplePayMutation(true)\n/** The same selection for a gateway that predates `buyer_ref`. */\nexport const CONFIRM_PAYMENT_APPLE_PAY_MUTATION_LEGACY = confirmApplePayMutation(false)\n\n/** Confirm (charge) the Apple Pay payment server-side. Called from the sheet's\n * authorize callback BEFORE completing it — the backend does the actual charge.\n * Sent again without `buyer_ref` only when the gateway refused the selection\n * (nothing ran); a confirmation that ran and failed is never repeated. */\nexport async function confirmPaymentApplePay(\n variables: Record<string, unknown>,\n options?: CartQueryOptions,\n): Promise<any> {\n const json = await withBuyerRef((withRef) =>\n executeCartGraphQL(\n withRef ? CONFIRM_PAYMENT_APPLE_PAY_MUTATION : CONFIRM_PAYMENT_APPLE_PAY_MUTATION_LEGACY,\n variables,\n options,\n ),\n )\n return json?.data?.Payment?.ConfirmPaymentApplePay\n}\n\nexport {\n CREATE_PAYMENT_VIPPS_MUTATION,\n GET_VIPPS_STATUS_QUERY,\n createPaymentVipps,\n getVippsStatus,\n} from '../checkout/payments/vipps.js'\n\n","/**\n * Vipps MobilePay Payment Adapter — GraphQL Integration & Types.\n *\n * Vipps payment integration uses 2 GraphQL operations:\n *\n * 1. `CreatePaymentVipps` mutation:\n * Initiates a Vipps payment session for a checkout and returns `payment_url`.\n *\n * 2. `GetVippsStatus` query:\n * Queries Vipps payment state directly for a checkout (`state`).\n */\n\nimport { executeCartGraphQL, type CartQueryOptions } from '../../api/cart-queries.js'\n\n/**\n * GraphQL mutation to create a Vipps payment session.\n */\nexport const CREATE_PAYMENT_VIPPS_MUTATION = `\nmutation CreatePaymentVipps($checkoutId: String!, $email: String, $returnUrl: String!, $express: Boolean) {\n Payment {\n CreatePaymentVipps(checkout_id: $checkoutId, email: $email, return_url: $returnUrl, express: $express) {\n payment_url\n reference\n express\n reason\n }\n }\n}\n`\n\n/**\n * GraphQL query to fetch current Vipps payment status.\n */\nexport const GET_VIPPS_STATUS_QUERY = `\nquery GetVippsStatus($checkoutId: String!) {\n Payment {\n GetVippsStatus(checkout_id: $checkoutId) {\n state\n duplicate_of\n }\n }\n}\n`\n\nexport interface CreatePaymentVippsVariables extends Record<string, unknown> {\n checkoutId: string\n /** Optional since Express: Vipps hands the email back with the payment. */\n email?: string\n returnUrl: string\n /**\n * `true` asks for Express — address and delivery chosen inside the Vipps\n * app. When the cart cannot have it, no payment is created and the answer\n * says `express: false` with the reason; the caller then opens the\n * ordinary checkout.\n */\n express?: boolean\n}\n\nexport interface CreatePaymentVippsResponse {\n /** Absent when Express was asked for and refused. */\n payment_url?: string\n /** The reference the seller reads in its Vipps portal. */\n reference?: string\n express?: boolean\n reason?: string\n}\n\nexport interface GetVippsStatusVariables extends Record<string, unknown> {\n checkoutId: string\n}\n\nexport interface VippsStatusResult {\n state: string\n /** Set when this checkout was closed as a duplicate: the checkout that paid the cart. */\n duplicate_of?: string | null\n}\n\nexport type VippsPaymentState =\n | 'CREATED'\n | 'INITIATED'\n | 'AUTHORIZED'\n | 'TERMINATED'\n | 'EXPIRED'\n | string\n\n/**\n * Executes the `CreatePaymentVipps` GraphQL mutation.\n */\nexport async function createPaymentVipps(\n variables: CreatePaymentVippsVariables | Record<string, unknown>,\n options?: CartQueryOptions,\n): Promise<CreatePaymentVippsResponse | null> {\n const json = await executeCartGraphQL(CREATE_PAYMENT_VIPPS_MUTATION, variables, options)\n return (json?.data?.Payment?.CreatePaymentVipps as CreatePaymentVippsResponse) ?? null\n}\n\n/**\n * Executes the `GetVippsStatus` GraphQL query.\n */\nexport async function getVippsStatus(\n variables: GetVippsStatusVariables | Record<string, unknown>,\n options?: CartQueryOptions,\n): Promise<VippsStatusResult | null> {\n const json = await executeCartGraphQL(GET_VIPPS_STATUS_QUERY, variables, options)\n return (json?.data?.Payment?.GetVippsStatus as VippsStatusResult) ?? null\n}\n","/**\n * CartManager — multi-sponsor cart state.\n *\n * Mirrors iOS's `CartManager` + `cartsBySponsor`. Holds local state in\n * memory and persists to localStorage. Reactive: dispatches a `change`\n * CustomEvent that UI components subscribe to (Web Components react via\n * `requestUpdate()`).\n *\n * The backend cart (Vio Commerce GraphQL CreateCart / AddItem / UpdateItem /\n * DeleteItem) is kept in sync optimistically from here; since 0.26 every add\n * and every increase tells it where the units come from (`origin`, ADR-0035\n * phase B) so the order is born attributed — see `origin-wire.ts`.\n */\n\nimport {\n formatPrice,\n getGlobalCountryCode,\n getGlobalCurrency,\n primaryImageUrl,\n type Product,\n} from '../types.js'\nimport type { CartLineItem, CartLineOrigin, CartOrigin, SponsorCartState } from './types.js'\nimport { currentOriginPage, currentPrivacyMode, lineOriginWire } from './origin-wire.js'\nimport { componentKindOf } from '../slots.js'\nimport { CONTENT_TITLE_MAX_LENGTH, originAndPath } from '../content.js'\nimport {\n addItem as gqlAddItem,\n createCart as gqlCreateCart,\n deleteItem as gqlDeleteItem,\n getCart as gqlGetCart,\n getCartGraphQLOptions,\n getCustomerSessionId,\n getLineItemsBySupplier as gqlGetLineItemsBySupplier,\n updateItem as gqlUpdateItem,\n updateShippingsBySupplier as gqlUpdateShippingsBySupplier,\n} from '../api/cart-queries.js'\n\nconst STORAGE_KEY = 'vio.cart.v1'\n\nexport interface CartChangeDetail {\n cartsBySponsor: Map<number, SponsorCartState>\n itemCount: number\n}\n\nexport interface AddProductOptions {\n product: Product\n sponsorId: number\n sponsorName?: string\n quantity?: number\n variantId?: number\n /** Where these units come from (`Vio.attribution(slot)`); see `CartOrigin`. */\n origin?: CartOrigin\n}\n\n/** Minimal product shape — for callers who only have e.g. mock data, not a full Product. */\nexport interface AddManualOptions {\n productId: number\n sponsorId: number\n sponsorName?: string\n brand: string\n name: string\n unitPrice: number\n currency: string\n imageUrl: string\n quantity?: number\n variantId?: number\n /** Where these units come from (`Vio.attribution(slot)`); see `CartOrigin`. */\n origin?: CartOrigin\n}\n\n/**\n * One change queued behind the request in flight: `delta` units more —\n * credited to `origin`, the place they were added from — or fewer (no\n * origin; the server takes them off the most recent, as the line does).\n */\ninterface QtyStep {\n delta: number\n origin?: CartOrigin\n}\n\n/** One backend quantity sync for one line. See `CartManager.qtySyncs`. */\ninterface QtySync {\n /** Target quantity of the request currently in flight. */\n sent: number\n /**\n * What arrived while in flight, in order, reduced as the line's own\n * origins are (a decrease comes off the most recent queued increase\n * first): one request per step once the current one settles, so every\n * increase reaches the server with ITS origin — a burst of +1 from the\n * hero and +1 from the carousel is two updates, not one credited to the\n * last. The line is heading to `sent + Σ delta`.\n */\n steps: QtyStep[]\n}\n\n/** The quantity a sync is heading to once every queued step has gone out. */\nfunction finalTarget(sync: QtySync): number {\n return sync.steps.reduce((quantity, step) => quantity + step.delta, sync.sent)\n}\n\n/**\n * Queue a target behind the request in flight: more units go on the last\n * step when it is an increase from the same origin, else on a new one; fewer\n * come off the most recent queued increases first and, past them, become a\n * decrease below what is in flight. A target already reached queues nothing.\n */\nfunction queueStep(sync: QtySync, target: number, origin: CartOrigin | undefined): void {\n const delta = target - finalTarget(sync)\n if (delta === 0) return\n if (delta > 0) {\n const last = sync.steps[sync.steps.length - 1]\n if (last && last.delta > 0 && sameOrigin(last.origin ?? {}, origin ?? {})) last.delta += delta\n else sync.steps.push({ delta, origin })\n return\n }\n let left = -delta\n while (left > 0 && sync.steps.length > 0) {\n const last = sync.steps[sync.steps.length - 1]!\n if (last.delta <= 0) break\n const take = Math.min(last.delta, left)\n last.delta -= take\n left -= take\n if (last.delta === 0) sync.steps.pop()\n }\n if (left > 0) {\n const last = sync.steps[sync.steps.length - 1]\n if (last && last.delta < 0) last.delta -= left\n else sync.steps.push({ delta: -left })\n }\n}\n\nfunction lineId(): string {\n return 'li_' + Math.random().toString(36).slice(2, 10) + Date.now().toString(36)\n}\n\n/** Normalise an id-ish value for matching: null/0/'null' → '' (no id). */\nfunction normId(val: unknown): string {\n if (val === null || val === undefined || val === 0 || val === '0' || val === 'null' || val === 'undefined') {\n return ''\n }\n return String(val).trim()\n}\n\nexport class CartManager extends EventTarget {\n private cartsBySponsor: Map<number, SponsorCartState>\n /** In-flight CreateCart per sponsor — two quick adds must share ONE backend\n * cart (two CreateCarts split the items and one silently disappears). */\n private cartIdPromises = new Map<number, Promise<string | undefined>>()\n /** Monotonic mutation counter per sponsor + last applied response, so a\n * slow response can't overwrite the state of a newer one. */\n private mutationSeq = new Map<number, number>()\n private appliedSeq = new Map<number, number>()\n /** In-flight AddItem/UpdateItem/DeleteItem per sponsor. Callers that need\n * the backend cart to reflect a just-made change (e.g. fetching shippings\n * right after an add) should `await waitForCartMutations(sponsorId)` first\n * — otherwise they can race the mutation and see the cart from before it\n * landed (Alan, 2026-08-18: shippings queried before AddItem settled,\n * came back empty). */\n private inFlightMutations = new Map<number, Set<Promise<unknown>>>()\n /** Per-line quantity sync with the backend: at most ONE UpdateItem /\n * DeleteItem in flight per line. Targets that arrive while one is in flight\n * are coalesced into `pending` (only the latest survives) and sent when the\n * current request settles. Keyed by `${sponsorId}:${cartItemId}`.\n * (Alan, 2026-10-15: a burst of +/− clicks fired one UpdateItem per click\n * in parallel; each response re-applied the whole backend cart, so an\n * older one landing after a newer optimistic change rolled the line back.) */\n private qtySyncs = new Map<string, QtySync>()\n\n constructor() {\n super()\n this.cartsBySponsor = this.loadFromStorage()\n }\n\n private nextSeq(sponsorId: number): number {\n const n = (this.mutationSeq.get(sponsorId) ?? 0) + 1\n this.mutationSeq.set(sponsorId, n)\n return n\n }\n\n /** Resolves once every in-flight AddItem/UpdateItem/DeleteItem for this\n * sponsor has settled (success or failure), including ones started while\n * waiting (a quantity intent replayed by an AddItem reconcile). No-op if\n * nothing is pending. */\n async waitForCartMutations(sponsorId: number): Promise<void> {\n for (;;) {\n const set = this.inFlightMutations.get(sponsorId)\n if (!set || set.size === 0) return\n // The mutations catch their own failures; allSettled is belt and braces.\n await Promise.allSettled([...set])\n }\n }\n\n /**\n * True while an AddItem/UpdateItem/DeleteItem of this sponsor OTHER than\n * `except` has not settled. A mutation applying its own answer passes\n * itself: its response is current for what IT sent — only the others make\n * it stale.\n */\n private hasMutationsInFlight(sponsorId: number, except?: Promise<unknown>): boolean {\n const set = this.inFlightMutations.get(sponsorId)\n if (!set || set.size === 0) return false\n for (const m of set) if (m !== except) return true\n return false\n }\n\n /** Register a backend mutation so `waitForCartMutations` can await it. */\n private trackMutation(sponsorId: number, mutation: Promise<unknown>): void {\n let set = this.inFlightMutations.get(sponsorId)\n if (!set) {\n set = new Set()\n this.inFlightMutations.set(sponsorId, set)\n }\n const tracked = set\n tracked.add(mutation)\n const untrack = () => {\n tracked.delete(mutation)\n if (tracked.size === 0 && this.inFlightMutations.get(sponsorId) === tracked) {\n this.inFlightMutations.delete(sponsorId)\n }\n }\n mutation.then(untrack, untrack)\n }\n\n private qtySyncKey(sponsorId: number, cartItemId: string): string {\n return `${sponsorId}:${cartItemId}`\n }\n\n /** The quantity a line is heading to (pending beats in flight), or\n * undefined when no quantity sync is active for it. */\n private intendedQuantity(sponsorId: number, cartItemId: string): number | undefined {\n const sync = this.qtySyncs.get(this.qtySyncKey(sponsorId, cartItemId))\n return sync ? finalTarget(sync) : undefined\n }\n\n /** Apply a backend response only if no newer response was applied already.\n * Returns false when it was discarded as stale. */\n private applyBackendCart(\n sponsorId: number,\n backendCart: unknown,\n seq: number,\n settling?: Promise<unknown>,\n ): boolean {\n if (seq < (this.appliedSeq.get(sponsorId) ?? 0)) return false\n this.appliedSeq.set(sponsorId, seq)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this.updateFromBackendCart(sponsorId, backendCart as any, { settling })\n return true\n }\n\n /** The final answer of a line's sync lost the per-sponsor seq race (another\n * line answered later): the cart as a whole is stale, but for THIS line it\n * is the latest word. Copy its quantity (and price) so a server-side clamp\n * — stock — doesn't leave the optimistic value behind for good, with the\n * checkout / Apple Pay total built on it. */\n private reconcileLineFromResponse(\n sponsorId: number,\n cartItemId: string,\n resCart: {\n line_items?: Array<{\n id: string\n quantity: number\n price?: { amount?: number; amount_incl_taxes?: number | null } | null\n }>\n },\n settling?: Promise<unknown>,\n ): void {\n const cart = this.cartsBySponsor.get(sponsorId)\n const line = cart?.items.find((i) => i.cartItemId === cartItemId || i.id === cartItemId)\n const server = resCart.line_items?.find((li) => li.id === cartItemId)\n if (!cart || !line || !server) return\n const price = server.price?.amount_incl_taxes ?? server.price?.amount\n let changed = false\n if (server.quantity !== line.quantity) {\n line.quantity = server.quantity\n if (!this.hasMutationsInFlight(sponsorId, settling)) {\n line.origins = reconciledOrigins(line.origins, server.quantity)\n }\n changed = true\n }\n if (price != null && price !== line.unitPrice) {\n line.unitPrice = price\n changed = true\n }\n if (!changed) return\n this.persist()\n this.emit()\n }\n\n /** Surface a cart sync problem to hosts/UI (and the console). */\n private emitError(message: string, err?: unknown): void {\n if (typeof console !== 'undefined') console.warn('[CartManager]', message, err ?? '')\n this.dispatchEvent(new CustomEvent('error', { detail: { message } }))\n if (typeof document !== 'undefined') {\n document.dispatchEvent(\n new CustomEvent('vio:cart-error', { bubbles: true, detail: { message } }),\n )\n }\n }\n\n // MARK: - Backend cart sync (Vio Commerce GraphQL)\n\n /** Ensure the sponsor cart exists server-side; returns its backend cart id. */\n async ensureCartId(\n sponsorId: number,\n currency?: string,\n shippingCountry?: string,\n ): Promise<string | undefined> {\n const activeCurrency = currency || getGlobalCurrency()\n const activeCountry = shippingCountry || getGlobalCountryCode()\n let cart = this.cartsBySponsor.get(sponsorId)\n if (!cart) {\n cart = { sponsorId, items: [], currency: activeCurrency, shippingCountry: activeCountry }\n this.cartsBySponsor.set(sponsorId, cart)\n } else {\n cart.shippingCountry = activeCountry\n }\n if (cart.cartId) return cart.cartId\n\n // Dedupe: concurrent callers share ONE CreateCart per sponsor.\n const inFlight = this.cartIdPromises.get(sponsorId)\n if (inFlight) return inFlight\n\n const creation = (async (): Promise<string | undefined> => {\n const opts = await getCartGraphQLOptions(sponsorId)\n // Never create a backend cart with the wrong key — a cart signed with\n // the host apiKey is orphaned once the sponsor key resolves later.\n if (!opts.sponsorResolved) {\n this.emitError(`no commerce key resolved for sponsor ${sponsorId} — cart not synced`)\n return undefined\n }\n const customerSessionId = getCustomerSessionId()\n try {\n const backendCart = await gqlCreateCart(\n customerSessionId,\n activeCurrency,\n activeCountry,\n opts,\n )\n if (backendCart?.cart_id) {\n cart.cartId = backendCart.cart_id\n if (Array.isArray(backendCart.line_items) && backendCart.line_items.length > 0) {\n this.updateFromBackendCart(sponsorId, backendCart)\n } else {\n // Fresh backend cart (no lines yet) — adopt the meta only. Calling\n // updateFromBackendCart here would wipe the optimistic local items.\n if (backendCart.currency) cart.currency = backendCart.currency\n if (backendCart.shipping_country) cart.shippingCountry = backendCart.shipping_country\n if (backendCart.subtotal != null) cart.subtotal = backendCart.subtotal\n if (backendCart.shipping != null) cart.shipping = backendCart.shipping\n if (backendCart.available_shipping_countries) {\n cart.availableShippingCountries = backendCart.available_shipping_countries\n }\n this.persist()\n this.emit()\n }\n }\n } catch (err) {\n this.emitError('createCart failed', err)\n }\n return cart.cartId\n })().finally(() => {\n this.cartIdPromises.delete(sponsorId)\n })\n\n this.cartIdPromises.set(sponsorId, creation)\n return creation\n }\n\n /**\n * Overwrite local cart state with the backend cart response (source of\n * truth). `opts.settling` is the mutation whose answer this is: it does not\n * count as \"in flight\" for the origins (see `hasMutationsInFlight`).\n */\n updateFromBackendCart(\n sponsorId: number,\n backendCart: {\n cart_id?: string\n currency?: string\n shipping_country?: string\n subtotal?: number\n shipping?: number\n available_shipping_countries?: string[]\n line_items?: Array<{\n id: string\n product_id: number\n variant_id?: number | string | null\n variant_title?: string | null\n brand?: string | null\n title?: string | null\n quantity: number\n image?: string | { url?: string } | null\n imageUrl?: string | null\n image_url?: string | null\n price?: {\n amount?: number\n amount_incl_taxes?: number | null\n currency_code?: string\n } | null\n shipping?: unknown\n available_shippings?: unknown[]\n }>\n },\n opts: { settling?: Promise<unknown> } = {},\n ): void {\n const cart = this.cartsBySponsor.get(sponsorId)\n if (!cart) return\n if (backendCart.cart_id) cart.cartId = backendCart.cart_id\n if (backendCart.currency) cart.currency = backendCart.currency\n if (backendCart.shipping_country) cart.shippingCountry = backendCart.shipping_country\n if (backendCart.subtotal != null) cart.subtotal = backendCart.subtotal\n if (backendCart.shipping != null) cart.shipping = backendCart.shipping\n if (backendCart.available_shipping_countries) {\n cart.availableShippingCountries = backendCart.available_shipping_countries\n }\n\n // Lines the shopper removed while their AddItem was still in flight: they\n // get their DeleteItem now that they have a backend id (see below).\n const removedBeforeSync: string[] = []\n if (Array.isArray(backendCart.line_items)) {\n const existingItems = cart.items || []\n if (backendCart.line_items.length === 0 && existingItems.length > 0) {\n // Backend says empty while we have optimistic local lines (add still\n // in flight) — keep the local view; a later sync will reconcile.\n this.persist()\n this.emit()\n return\n }\n cart.items = backendCart.line_items.flatMap((li): CartLineItem[] => {\n // A line whose quantity sync is still active keeps its optimistic\n // quantity: this response predates that intent. Heading to 0 means\n // the shopper already removed it — don't resurrect it for a frame.\n const intended = this.intendedQuantity(sponsorId, li.id)\n if (intended !== undefined && intended <= 0) return []\n // Removed locally before it had a backend id: the shopper saw it go\n // and vio:removed-from-cart already went out. Don't bring it back —\n // and don't replay the removal through updateQuantity (that emitted\n // the event a second time); just send the DeleteItem.\n const earlyKey = this.intentKey(li.product_id, li.variant_id)\n const earlyIntent = this.pendingQtyIntents.get(earlyKey)\n if (earlyIntent !== undefined && earlyIntent <= 0) {\n this.pendingQtyIntents.delete(earlyKey)\n removedBeforeSync.push(li.id)\n return []\n }\n const urlFromBackend =\n (typeof li.image === 'string' ? li.image : li.image?.url) ||\n li.imageUrl ||\n li.image_url ||\n ''\n // Match the backend line to a local one to preserve display fields the\n // backend may omit (image, brand, name, price).\n const matchedLocal = existingItems.find((existing) => {\n const p1 = normId(existing.productId)\n const p2 = normId(li.product_id)\n const v1 = normId(existing.variantId)\n const v2 = normId(li.variant_id)\n if (p1 && p2 && p1 === p2 && v1 === v2) return true\n if (v1 && v2 && v1 === v2) return true\n if (p1 && p2 && p1 === p2 && !v1 && !v2) return true\n const n1 = (existing.name || '').trim().toLowerCase()\n const n2 = (li.title || '').trim().toLowerCase()\n if (n1 && n2 && n1 === n2 && v1 === v2) return true\n return false\n })\n const imageUrl = urlFromBackend || matchedLocal?.imageUrl || ''\n\n const line: CartLineItem = {\n id: li.id,\n cartItemId: li.id,\n productId: li.product_id,\n sponsorId,\n variantId: li.variant_id != null ? Number(li.variant_id) : undefined,\n brand: li.brand || matchedLocal?.brand || '',\n name: li.title\n ? li.variant_title\n ? `${li.title} — ${li.variant_title}`\n : li.title\n : matchedLocal?.name || '',\n unitPrice: li.price?.amount_incl_taxes ?? li.price?.amount ?? matchedLocal?.unitPrice ?? 0,\n currency: li.price?.currency_code || backendCart.currency || matchedLocal?.currency || 'NOK',\n imageUrl,\n quantity: intended ?? li.quantity,\n // The server keeps its own copy of the origins (per request); the\n // cart read model does not answer them, so keep the local ones. They\n // are squared with its quantity (a stock clamp) only when no OTHER\n // mutation is in flight for this sponsor — an AddItem answering\n // while another is pending reports a quantity that is already old\n // (see `lineOrigins`).\n origins: matchedLocal\n ? this.hasMutationsInFlight(sponsorId, opts.settling)\n ? matchedLocal.origins\n : reconciledOrigins(matchedLocal.origins, intended ?? li.quantity)\n : undefined,\n shipping: li.shipping,\n availableShippings: li.available_shippings,\n }\n return [line]\n })\n }\n this.persist()\n this.emit()\n\n const syncedCartId = cart.cartId\n if (syncedCartId) {\n for (const id of removedBeforeSync) this.syncQuantity(sponsorId, syncedCartId, id, 0)\n }\n\n // Replay quantity intents recorded while the line had no backend id yet.\n if (this.pendingQtyIntents.size > 0) {\n const currentCart = this.cartsBySponsor.get(sponsorId)\n for (const [key, qty] of [...this.pendingQtyIntents]) {\n const line = currentCart?.items.find(\n (i) => this.intentKey(i.productId, i.variantId) === key && i.cartItemId,\n )\n if (line) {\n this.pendingQtyIntents.delete(key)\n if (line.quantity !== qty) {\n this.updateQuantity(line.cartItemId!, sponsorId, qty)\n }\n }\n }\n }\n }\n\n // MARK: - Mutations\n\n /** Add a Product DTO to a sponsor's cart. Bumps quantity if already present.\n * When a variantId is given, the line uses the VARIANT's price / image / title\n * (not the product base), so different combinations are priced correctly. */\n addProduct(opts: AddProductOptions): CartLineItem {\n const variant =\n opts.variantId != null\n ? opts.product.variants?.find((v) => v.id === opts.variantId)\n : undefined\n const price = variant?.price ?? opts.product.price\n // Tax-inclusive is the consumer-facing price; `amount` is the fallback.\n const unitPrice = price.amount_incl_taxes ?? price.amount ?? 0\n const imageUrl = variant?.images?.[0]?.url || primaryImageUrl(opts.product) || ''\n const name = variant?.title\n ? `${opts.product.title} — ${variant.title}`\n : opts.product.title\n return this.addManual({\n productId: opts.product.id,\n sponsorId: opts.sponsorId,\n sponsorName: opts.sponsorName,\n brand: opts.product.brand ?? '',\n name,\n unitPrice,\n currency: price.currency_code,\n imageUrl,\n quantity: opts.quantity,\n variantId: opts.variantId,\n origin: opts.origin,\n })\n }\n\n /** Add a manually-specified line item (no Product DTO). */\n addManual(opts: AddManualOptions): CartLineItem {\n const qty = Math.max(1, opts.quantity ?? 1)\n let cart = this.cartsBySponsor.get(opts.sponsorId)\n if (!cart) {\n cart = {\n sponsorId: opts.sponsorId,\n sponsorName: opts.sponsorName,\n items: [],\n currency: opts.currency,\n }\n this.cartsBySponsor.set(opts.sponsorId, cart)\n } else if (opts.sponsorName && !cart.sponsorName) {\n cart.sponsorName = opts.sponsorName\n }\n\n // Robust dedupe: backend-synced lines may carry ids as strings / omit\n // fields, so match on normalised product+variant ids with a name fallback.\n const existing = cart.items.find((i) => {\n const p1 = normId(i.productId)\n const p2 = normId(opts.productId)\n const v1 = normId(i.variantId)\n const v2 = normId(opts.variantId)\n if (p1 && p2 && p1 === p2 && v1 === v2) return true\n if (v1 && v2 && v1 === v2) return true\n if (p1 && p2 && p1 === p2 && !v1 && !v2) return true\n const n1 = (i.name || '').trim().toLowerCase()\n const n2 = (opts.name || '').trim().toLowerCase()\n if (n1 && n2 && n1 === n2 && v1 === v2) return true\n return false\n })\n if (existing) {\n existing.quantity += qty\n addOriginQuantity(existing, opts.origin, qty)\n } else {\n const item: CartLineItem = {\n id: lineId(),\n productId: opts.productId,\n sponsorId: opts.sponsorId,\n variantId: opts.variantId,\n brand: opts.brand,\n name: opts.name,\n unitPrice: opts.unitPrice,\n currency: opts.currency,\n imageUrl: opts.imageUrl,\n quantity: qty,\n origins: [{ ...normalizeOrigin(opts.origin), quantity: qty }],\n }\n cart.items.push(item)\n }\n this.persist()\n this.emit()\n\n const addedItem = existing ?? cart.items[cart.items.length - 1]!\n const addedLineId = addedItem.id\n\n // Async sync with the backend cart. Optimistic — but a REJECTED AddItem\n // reverts the local line (a ghost line means the UI total and the charged\n // total diverge silently).\n const seq = this.nextSeq(opts.sponsorId)\n // This mutation, for `applyBackendCart` to tell its own answer from the others'.\n let settling: Promise<unknown> | undefined\n const mutation = (async () => {\n try {\n const cartId = await this.ensureCartId(opts.sponsorId, opts.currency || undefined)\n if (cartId) {\n const gqlOpts = await getCartGraphQLOptions(opts.sponsorId)\n // Where these units come from, for the order (ADR-0035 phase B):\n // the add's own origin; nothing when the host gave none. On a\n // `minimal` surface (or one whose mode is not known) the slot and\n // the page stay out of it — see `lineOriginWire`.\n const origin = opts.origin\n ? lineOriginWire(normalizeOrigin(opts.origin), {\n page: currentOriginPage(),\n privacyMode: await currentPrivacyMode(),\n })\n : undefined\n const lineItemsInput = [\n {\n product_id: Number(opts.productId || 0),\n quantity: qty,\n variant_id: opts.variantId != null ? Number(opts.variantId) : null,\n ...(origin ? { origin } : {}),\n },\n ]\n const resCart = await gqlAddItem(cartId, lineItemsInput, gqlOpts)\n if (resCart && Array.isArray(resCart.line_items)) {\n this.applyBackendCart(opts.sponsorId, resCart, seq, settling)\n }\n }\n // No cartId (no commerce key): the cart stays local-only; checkout is\n // blocked upstream, so no ghost-charge risk.\n } catch (err) {\n // Revert the optimistic add — subtract what THIS add contributed.\n const c = this.cartsBySponsor.get(opts.sponsorId)\n const line = c?.items.find((i) => i.id === addedLineId)\n if (c && line) {\n line.quantity -= qty\n // Off the origin whose add failed — not whatever was added last.\n removeFromOrigin(line, opts.origin, qty)\n if (line.quantity <= 0) c.items = c.items.filter((i) => i !== line)\n if (c.items.length === 0) this.cartsBySponsor.delete(opts.sponsorId)\n this.persist()\n this.emit()\n }\n this.emitError('AddItem rejected by the backend — item removed from the cart', err)\n }\n })()\n settling = mutation\n this.trackMutation(opts.sponsorId, mutation)\n\n return addedItem\n }\n\n /** Quantity intents for lines whose backend id hasn't arrived yet — replayed\n * when the AddItem response reconciles (keyed by product::variant). */\n private pendingQtyIntents = new Map<string, number>()\n\n private intentKey(productId: unknown, variantId: unknown): string {\n return `${normId(productId)}::${normId(variantId)}`\n }\n\n private findLine(sponsorId: number, lineItemId: string): CartLineItem | undefined {\n return this.cartsBySponsor\n .get(sponsorId)\n ?.items.find((i) => i.id === lineItemId || i.cartItemId === lineItemId)\n }\n\n /** Change a line's quantity by `delta`, computed on the manager's CURRENT\n * quantity — not on whatever a UI rendered a moment ago. A burst of +/−\n * clicks before a re-render therefore asks for 2, 3, 4… and not for the\n * same target several times. Reaching 0 removes the line. */\n adjustQuantity(\n lineItemId: string,\n sponsorId: number,\n delta: number,\n opts: { origin?: CartOrigin } = {},\n ): void {\n const item = this.findLine(sponsorId, lineItemId)\n if (!item) return\n this.updateQuantity(lineItemId, sponsorId, item.quantity + delta, opts)\n }\n\n /** Set a line's quantity (0 or less removes it). Optimistic: the local\n * state and `change` update at once; the backend is synced through\n * `syncQuantity`, one request in flight per line, latest target wins. */\n updateQuantity(\n lineItemId: string,\n sponsorId: number,\n quantity: number,\n opts: { origin?: CartOrigin } = {},\n ): void {\n const cart = this.cartsBySponsor.get(sponsorId)\n if (!cart) return\n const item = cart.items.find((i) => i.id === lineItemId || i.cartItemId === lineItemId)\n if (!item) return\n const target = quantity > 0 ? quantity : 0\n // Already there (or already heading there): nothing new to say or send.\n if (target === item.quantity) return\n const targetItemId = item.cartItemId\n // The origins follow the quantity: more units go to the given origin (or\n // the most recent one), fewer come off the most recent first.\n const removedOrigin = latestOrigin(item)\n const increase = target > item.quantity\n if (increase) addOriginQuantity(item, opts.origin, target - item.quantity)\n else removeOriginQuantity(item, item.quantity - target)\n // The origin the new units were credited to (the given one, else the most\n // recent) goes to the server with the increase; a decrease names none.\n const addedOrigin = increase ? latestOrigin(item) : undefined\n if (target <= 0) {\n cart.items = cart.items.filter((i) => i !== item)\n // Choke point de la baja: sale acá y no en la UI para que también\n // cuente cuando el host llama removeItem() por API.\n if (typeof document !== 'undefined') {\n document.dispatchEvent(\n new CustomEvent('vio:removed-from-cart', {\n bubbles: true,\n detail: {\n productId: item.productId,\n variantId: item.variantId,\n name: item.name,\n brand: item.brand,\n price: item.unitPrice,\n quantity: item.quantity,\n currency: item.currency,\n sponsorId,\n // Attribution of the removed units: their most recent origin.\n slot: removedOrigin?.slot,\n campaignId: removedOrigin?.campaignId,\n contentId: removedOrigin?.contentId,\n },\n }),\n )\n }\n } else {\n item.quantity = target\n }\n if (cart.items.length === 0) this.cartsBySponsor.delete(sponsorId)\n this.persist()\n this.emit()\n\n if (!cart.cartId) return\n\n // The line hasn't been assigned its backend id yet (AddItem in flight):\n // sending the local id would 404. Record the intent — it's replayed as\n // soon as the reconcile lands.\n if (!targetItemId) {\n this.pendingQtyIntents.set(this.intentKey(item.productId, item.variantId), target)\n return\n }\n\n this.syncQuantity(sponsorId, cart.cartId, targetItemId, target, addedOrigin)\n }\n\n /** Send a line's target quantity to the backend — ONE request in flight per\n * line. Targets that arrive while one is in flight queue behind it as\n * steps (`queueStep`): reduced like the line's origins, sent in order once\n * the current request settles — one request per queued increase from a\n * different origin, one for a net decrease — so the server ends on the\n * last intent, credits every increase to its own origin, and never sees two\n * updates racing each other. While the sync is active the line keeps its\n * optimistic quantity through any backend response (see\n * `updateFromBackendCart`); a rejection drops what was queued and\n * reconciles the cart from the server. */\n private syncQuantity(\n sponsorId: number,\n backendCartId: string,\n cartItemId: string,\n target: number,\n origin?: CartOrigin,\n ): void {\n const key = this.qtySyncKey(sponsorId, cartItemId)\n const active = this.qtySyncs.get(key)\n if (active) {\n queueStep(active, target, origin)\n return\n }\n const sync: QtySync = { sent: target, steps: [] }\n this.qtySyncs.set(key, sync)\n\n // This mutation, for `applyBackendCart` to tell its own answer from the others'.\n let settling: Promise<unknown> | undefined\n const run = (async () => {\n let next: number | undefined = target\n let nextOrigin: CartOrigin | undefined = origin\n let removalRetried = false\n while (next !== undefined) {\n const seq = this.nextSeq(sponsorId)\n try {\n const gqlOpts = await getCartGraphQLOptions(sponsorId)\n // The origin of the units this update adds (ADR-0035 phase B) —\n // when it was an increase and the SDK knows a place for them.\n const originWire =\n next > 0 && nextOrigin\n ? lineOriginWire(nextOrigin, { page: currentOriginPage(), privacyMode: await currentPrivacyMode() })\n : undefined\n const resCart =\n next <= 0\n ? await gqlDeleteItem(backendCartId, cartItemId, gqlOpts)\n : originWire\n ? await gqlUpdateItem(backendCartId, cartItemId, null, next, gqlOpts, { origin: originWire })\n : await gqlUpdateItem(backendCartId, cartItemId, null, next, gqlOpts)\n // The next queued step, if any: an increase with its origin, or a\n // decrease. It becomes `sent` at once — the line is heading there,\n // and the response being applied below must not roll it back.\n const step = sync.steps.shift()\n if (step) {\n next = sync.sent + step.delta\n nextOrigin = step.delta > 0 ? step.origin : undefined\n sync.sent = next\n } else {\n next = undefined\n nextOrigin = undefined\n }\n // Nothing queued: the server's view of this line is the truth now.\n // With a step queued the entry stays, so this (already stale)\n // response cannot roll the line back.\n if (next === undefined) this.qtySyncs.delete(key)\n if (resCart && Array.isArray(resCart.line_items)) {\n const applied = this.applyBackendCart(sponsorId, resCart, seq, settling)\n if (!applied && next === undefined) {\n this.reconcileLineFromResponse(sponsorId, cartItemId, resCart, settling)\n }\n }\n } catch (err) {\n // Rejected: whatever was queued is moot — the server decides — with\n // one exception. A queued REMOVAL already happened for the shopper\n // (the line is gone, vio:removed-from-cart went out), so it is sent\n // once more, once, instead of letting the reconcile bring the line\n // back without a DeleteItem ever going out.\n const retryRemoval = !removalRetried && sync.steps.length > 0 && finalTarget(sync) <= 0\n sync.steps = []\n next = undefined\n nextOrigin = undefined\n if (retryRemoval) {\n removalRetried = true\n // Entry stays (heading to 0): the reconcile below leaves the line out.\n sync.sent = 0\n next = 0\n } else {\n this.qtySyncs.delete(key)\n }\n // The reconcile emits `change`.\n this.emitError('Update/DeleteItem failed — cart re-synced from backend', err)\n try {\n await this.fetchCartFromBackend(sponsorId)\n } catch (fetchErr) {\n this.emitError('cart re-sync after a rejected Update/DeleteItem failed', fetchErr)\n }\n }\n }\n })()\n settling = run\n this.trackMutation(sponsorId, run)\n }\n\n removeItem(lineItemId: string, sponsorId: number): void {\n this.updateQuantity(lineItemId, sponsorId, 0)\n }\n\n clearSponsorCart(sponsorId: number): void {\n if (this.cartsBySponsor.delete(sponsorId)) {\n this.persist()\n this.emit()\n }\n }\n\n clearAllCarts(): void {\n if (this.cartsBySponsor.size === 0) return\n this.cartsBySponsor.clear()\n this.persist()\n this.emit()\n }\n\n /** Refresh the local cart from the backend (source of truth). */\n async fetchCartFromBackend(sponsorId: number): Promise<unknown> {\n const cart = this.cartsBySponsor.get(sponsorId)\n if (!cart?.cartId) return null\n const gqlOpts = await getCartGraphQLOptions(sponsorId)\n const resCart = await gqlGetCart(cart.cartId, gqlOpts)\n if (resCart) this.updateFromBackendCart(sponsorId, resCart)\n return resCart\n }\n\n /** Line items grouped by supplier (shipping is per-supplier server-side). */\n async fetchLineItemsBySupplier(sponsorId: number): Promise<unknown> {\n const cart = this.cartsBySponsor.get(sponsorId)\n if (!cart?.cartId) return null\n const gqlOpts = await getCartGraphQLOptions(sponsorId)\n return gqlGetLineItemsBySupplier(cart.cartId, gqlOpts)\n }\n\n /** Set the chosen shipping option per supplier on the backend cart. */\n async updateShippingsBySupplier(\n sponsorId: number,\n data: Array<{ shipping_id: string; supplier_id: number }>,\n ): Promise<unknown> {\n const cart = this.cartsBySponsor.get(sponsorId)\n if (!cart?.cartId) return null\n const gqlOpts = await getCartGraphQLOptions(sponsorId)\n const resCart = await gqlUpdateShippingsBySupplier(cart.cartId, data, gqlOpts)\n if (resCart && Array.isArray(resCart.line_items)) {\n this.updateFromBackendCart(sponsorId, resCart)\n }\n return resCart\n }\n\n // MARK: - Read accessors\n\n getAllCarts(): Map<number, SponsorCartState> {\n return new Map(this.cartsBySponsor)\n }\n\n getCart(sponsorId: number): SponsorCartState | undefined {\n return this.cartsBySponsor.get(sponsorId)\n }\n\n get itemCount(): number {\n let count = 0\n for (const cart of this.cartsBySponsor.values()) {\n for (const item of cart.items) count += item.quantity\n }\n return count\n }\n\n subtotalForSponsor(sponsorId: number): number {\n const cart = this.cartsBySponsor.get(sponsorId)\n if (!cart) return 0\n return cart.items.reduce((sum, i) => sum + i.unitPrice * i.quantity, 0)\n }\n\n get totalAcrossSponsors(): number {\n let sum = 0\n for (const cart of this.cartsBySponsor.values()) {\n for (const item of cart.items) sum += item.unitPrice * item.quantity\n }\n return sum\n }\n\n get primaryCurrency(): string {\n for (const cart of this.cartsBySponsor.values()) return cart.currency\n return 'NOK'\n }\n\n formatTotal(): string {\n return formatPrice(this.totalAcrossSponsors, this.primaryCurrency)\n }\n\n // MARK: - Persistence\n\n private persist(): void {\n if (typeof localStorage === 'undefined') return\n try {\n const obj: Record<string, SponsorCartState> = {}\n for (const [k, v] of this.cartsBySponsor) obj[String(k)] = v\n localStorage.setItem(STORAGE_KEY, JSON.stringify(obj))\n } catch {\n // Ignore quota / privacy errors.\n }\n }\n\n private loadFromStorage(): Map<number, SponsorCartState> {\n if (typeof localStorage === 'undefined') return new Map()\n try {\n const raw = localStorage.getItem(STORAGE_KEY)\n if (!raw) return new Map()\n const obj = JSON.parse(raw) as Record<string, SponsorCartState>\n const map = new Map<number, SponsorCartState>()\n for (const [k, v] of Object.entries(obj)) {\n const id = parseInt(k, 10)\n if (!Number.isNaN(id) && v && Array.isArray(v.items)) map.set(id, v)\n }\n return map\n } catch {\n return new Map()\n }\n }\n\n private emit(): void {\n const detail: CartChangeDetail = {\n cartsBySponsor: this.getAllCarts(),\n itemCount: this.itemCount,\n }\n this.dispatchEvent(new CustomEvent<CartChangeDetail>('change', { detail }))\n }\n}\n\n// ── Origins (where each unit of a line came from) ───────────────────────────\n\n/**\n * Only the attribution fields, trimmed; `{}` when nothing is known. The kind\n * of element is kept as Commerce and the collector name it (`card`,\n * `carousel`, `detail` — `componentKindOf`), from `componentKind` or from\n * the `componentTemplateId` an element's attribution carries (`product-card`);\n * the page as origin + path (`contentUrl`) and its title, within Commerce's caps.\n */\nexport function normalizeOrigin(origin: CartOrigin | null | undefined): CartOrigin {\n const out: CartOrigin = {}\n if (!origin || typeof origin !== 'object') return out\n const campaignId = Number(origin.campaignId)\n if (origin.campaignId !== undefined && origin.campaignId !== null && Number.isFinite(campaignId)) {\n out.campaignId = campaignId\n }\n if (typeof origin.slot === 'string' && origin.slot.trim()) out.slot = origin.slot.trim()\n if (origin.contentId !== undefined && origin.contentId !== null && String(origin.contentId).trim()) {\n out.contentId = String(origin.contentId).trim()\n }\n const kind = componentKindOf(origin.componentKind ?? (origin as { componentTemplateId?: unknown }).componentTemplateId)\n if (kind) out.componentKind = kind\n const contentUrl = originAndPath(origin.contentUrl)\n if (contentUrl) out.contentUrl = contentUrl\n if (typeof origin.contentTitle === 'string' && origin.contentTitle.trim()) {\n out.contentTitle = origin.contentTitle.trim().slice(0, CONTENT_TITLE_MAX_LENGTH)\n }\n return out\n}\n\n/** Two origins are the same place when campaign, slot, content and kind of element all match (the page's URL and title are attributes of the place, not its identity). */\nexport function sameOrigin(a: CartOrigin, b: CartOrigin): boolean {\n return (\n a.campaignId === b.campaignId &&\n a.slot === b.slot &&\n a.contentId === b.contentId &&\n a.componentKind === b.componentKind\n )\n}\n\n/** The most recent origin of a line, or undefined. */\nexport function latestOrigin(line: Pick<CartLineItem, 'origins'>): CartLineOrigin | undefined {\n const origins = Array.isArray(line.origins) ? line.origins : []\n return origins[origins.length - 1]\n}\n\n/**\n * `qty` more units from `origin`: added to the matching origin when there is\n * one (moved to the end, as the most recent), else to a new one. Without an\n * origin they go to the most recent origin — or to an empty `{}` one.\n */\nexport function addOriginQuantity(\n line: Pick<CartLineItem, 'origins'>,\n origin: CartOrigin | null | undefined,\n qty: number,\n): void {\n if (!(qty > 0)) return\n const origins = Array.isArray(line.origins) ? line.origins : []\n const target: CartOrigin | undefined = origin ? normalizeOrigin(origin) : latestOrigin({ origins })\n const index = target ? origins.findIndex((o) => sameOrigin(o, target)) : -1\n if (index >= 0) {\n const [found] = origins.splice(index, 1)\n found!.quantity += qty\n origins.push(found!)\n } else {\n origins.push({ ...(target ?? {}), quantity: qty })\n }\n line.origins = origins\n}\n\n/**\n * `qty` fewer units off a given origin first (a rejected add is reverted from\n * the origin that failed), then off the most recent ones.\n */\nexport function removeFromOrigin(\n line: Pick<CartLineItem, 'origins'>,\n origin: CartOrigin | null | undefined,\n qty: number,\n): void {\n if (!(qty > 0) || !Array.isArray(line.origins)) return\n let left = qty\n if (origin) {\n const target = normalizeOrigin(origin)\n const index = line.origins.findIndex((o) => sameOrigin(o, target))\n if (index >= 0) {\n const found = line.origins[index]!\n const take = Math.min(found.quantity, left)\n found.quantity -= take\n left -= take\n if (found.quantity <= 0) line.origins.splice(index, 1)\n }\n }\n if (left > 0) removeOriginQuantity(line, left)\n}\n\n/** `qty` fewer units: off the most recent origins first. */\nexport function removeOriginQuantity(line: Pick<CartLineItem, 'origins'>, qty: number): void {\n if (!(qty > 0) || !Array.isArray(line.origins)) return\n let left = qty\n const origins = line.origins\n while (left > 0 && origins.length > 0) {\n const last = origins[origins.length - 1]!\n const take = Math.min(last.quantity, left)\n last.quantity -= take\n left -= take\n if (last.quantity <= 0) origins.pop()\n }\n}\n\n/** Origins squared with a quantity the server answered (stock clamps, re-syncs). */\nexport function reconciledOrigins(\n origins: CartLineOrigin[] | undefined,\n quantity: number,\n): CartLineOrigin[] | undefined {\n if (!Array.isArray(origins)) return undefined\n const copy = origins.map((o) => ({ ...o }))\n const total = copy.reduce((sum, o) => sum + (o.quantity > 0 ? o.quantity : 0), 0)\n const line = { origins: copy }\n if (quantity > total) addOriginQuantity(line, undefined, quantity - total)\n else if (quantity < total) removeOriginQuantity(line, total - quantity)\n return line.origins\n}\n\n/**\n * The origins of a line for reporting: what it carries, plus an empty origin\n * for any units it does not account for (a cart persisted before origins\n * existed, a server-side bump). Their quantities add up to the line's.\n */\nexport function lineOrigins(line: Pick<CartLineItem, 'origins' | 'quantity'>): CartLineOrigin[] {\n const known = (Array.isArray(line.origins) ? line.origins : []).filter((o) => o && o.quantity > 0)\n const total = known.reduce((sum, o) => sum + o.quantity, 0)\n const quantity = line.quantity > 0 ? line.quantity : 0\n if (total === quantity) return known.map((o) => ({ ...o }))\n if (total < quantity) return [...known.map((o) => ({ ...o })), { quantity: quantity - total }]\n // More units remembered than the line has (a server clamp while an add was\n // in flight): report the line's quantity, trimming the most recent first —\n // on a copy, the line's own origins are not touched.\n const copy = { origins: known.map((o) => ({ ...o })) }\n removeOriginQuantity(copy, total - quantity)\n return copy.origins\n}\n","/**\n * Who sells — the sponsor's (brand's) display identity: its name and logo.\n *\n * ONE rule for every place that names a sponsor (the product detail, the\n * carousel's retailer line, the cart, the checkout header, the confirmation,\n * the payment event and `getOrderReference`): the bootstrap's sponsor block —\n * the config's primary and secondaries, then every `campaigns[]` primary and\n * secondaries, first match — and, when the bootstrap does not know the id,\n * what this tab remembered of the checkout, then the cart's `sponsorName`.\n *\n * In a checkout and on its confirmation the sponsor is the CHECKOUT's (the\n * cart's sponsor, the one the order is with), never the page's attribution:\n * an article of brand A may sell a product of brand B.\n *\n * Pure helpers and a tiny per-checkout memory in `sessionStorage`; no DOM.\n */\n\nimport type { BootstrapResponse, Sponsor } from './types.js'\n\n/** What a sponsor looks like to a shopper. `name` is the brand's display name. */\nexport interface SponsorIdentity {\n id: number\n name: string\n /** The brand's logo, as the bootstrap gives it (never rewritten); `null` when it has none. */\n logoUrl: string | null\n avatarUrl: string | null\n /** The brand's purchase terms page — https only; `null` when it has none. */\n termsUrl?: string | null\n /** The brand's returns / refund policy page — https only; `null` when it has none. */\n refundPolicyUrl?: string | null\n}\n\n/** The sponsor of a checkout / an order as events and `getOrderReference` carry it. */\nexport type CheckoutSponsor = Pick<SponsorIdentity, 'id' | 'name' | 'logoUrl'>\n\n/** `sessionStorage` key of the per-checkout memory. */\nexport const CHECKOUT_SPONSOR_STORAGE_KEY = 'vio.checkoutSponsor.v1'\n/** How many checkouts the memory keeps (the most recent). */\nexport const CHECKOUT_SPONSOR_MEMORY_MAX = 20\n\n/** A positive integer id, from a number or a numeric string; `undefined` otherwise. */\nexport function toSponsorId(value: unknown): number | undefined {\n if (value === null || value === undefined || value === '') return undefined\n const n = typeof value === 'number' ? value : Number(String(value).trim())\n return Number.isInteger(n) && n > 0 ? n : undefined\n}\n\n/** A non-empty string, trimmed; `null` for anything else (an empty `logoUrl` is no logo). */\nfunction urlOrNull(value: unknown): string | null {\n if (typeof value !== 'string') return null\n const v = value.trim()\n return v ? v : null\n}\n\n/** A page link the shopper will open: an absolute https URL, or nothing. */\nfunction pageUrlOrNull(value: unknown): string | null {\n const v = urlOrNull(value)\n if (!v) return null\n try {\n return new URL(v).protocol === 'https:' ? v : null\n } catch {\n return null\n }\n}\n\nfunction nameOf(value: unknown): string {\n return typeof value === 'string' ? value.trim() : ''\n}\n\n/**\n * The sponsor block of `sponsorId` in a bootstrap: the config's\n * `primarySponsor`, its `secondarySponsors`, then every `campaigns[]` entry's\n * primary and secondaries — the first match. Tolerates any shape.\n */\nexport function findSponsorIn(\n boot: BootstrapResponse | null | undefined,\n sponsorId: number | string | null | undefined,\n): Sponsor | undefined {\n const id = toSponsorId(sponsorId)\n if (id === undefined || !boot || typeof boot !== 'object') return undefined\n const match = (s: unknown): s is Sponsor =>\n !!s && typeof s === 'object' && Number((s as { id?: unknown }).id) === id\n if (match(boot.primarySponsor)) return boot.primarySponsor\n const secondary = Array.isArray(boot.secondarySponsors) ? boot.secondarySponsors.find(match) : undefined\n if (secondary) return secondary\n // A sponsor may live only in a non-default campaign (the one a slot shows).\n const campaigns = Array.isArray(boot.campaigns) ? boot.campaigns : []\n for (const c of campaigns) {\n if (!c || typeof c !== 'object') continue\n if (match(c.primarySponsor)) return c.primarySponsor\n const s = Array.isArray(c.secondarySponsors) ? c.secondarySponsors.find(match) : undefined\n if (s) return s\n }\n return undefined\n}\n\n/**\n * The identity of a sponsor from a bootstrap (`findSponsorIn`): its trimmed\n * name and its logo / avatar URLs as given (an empty string is `null`).\n * `null` when the bootstrap does not know the id, or the block says neither\n * a name nor a logo. Pure, never throws.\n */\nexport function sponsorIdentityFrom(\n boot: BootstrapResponse | null | undefined,\n sponsorId: number | string | null | undefined,\n): SponsorIdentity | null {\n try {\n const id = toSponsorId(sponsorId)\n if (id === undefined) return null\n const sponsor = findSponsorIn(boot, id)\n if (!sponsor) return null\n const name = nameOf(sponsor.name)\n const logoUrl = urlOrNull(sponsor.logoUrl)\n if (!name && !logoUrl) return null\n // The brand's pages only when it gave them: an identity without them keeps its shape.\n const termsUrl = pageUrlOrNull((sponsor as { termsUrl?: unknown }).termsUrl)\n const refundPolicyUrl = pageUrlOrNull((sponsor as { refundPolicyUrl?: unknown }).refundPolicyUrl)\n return {\n id,\n name,\n logoUrl,\n avatarUrl: urlOrNull(sponsor.avatarUrl),\n ...(termsUrl ? { termsUrl } : {}),\n ...(refundPolicyUrl ? { refundPolicyUrl } : {}),\n }\n } catch {\n return null\n }\n}\n\n/** The event / order-reference shape of an identity (`{ id, name, logoUrl }`). */\nexport function checkoutSponsorOf(identity: SponsorIdentity | CheckoutSponsor | null | undefined): CheckoutSponsor | undefined {\n if (!identity) return undefined\n return { id: identity.id, name: identity.name, logoUrl: identity.logoUrl ?? null }\n}\n\n// MARK: - Per-checkout memory\n\n/** What this tab remembers of a checkout: whose it is, and how that sponsor looked then. */\nexport interface RememberedCheckoutSponsor {\n checkoutId: string\n sponsorId: number\n name: string\n logoUrl: string | null\n}\n\n/**\n * Same-page fallback when `sessionStorage` is unavailable (private mode, a\n * sandboxed iframe): the memory still serves the page it was written on.\n */\nlet inMemory: RememberedCheckoutSponsor[] = []\n/** A write to `sessionStorage` failed on this page (quota, blocked): read the in-page copy from then on. */\nlet storageRefusedWrite = false\n\nfunction sessionStore(): Storage | null {\n try {\n const s = (globalThis as { sessionStorage?: Storage }).sessionStorage\n return s && typeof s.getItem === 'function' && typeof s.setItem === 'function' ? s : null\n } catch {\n return null\n }\n}\n\nfunction normalizeEntry(raw: unknown): RememberedCheckoutSponsor | null {\n if (!raw || typeof raw !== 'object') return null\n const r = raw as Record<string, unknown>\n const checkoutId = typeof r.checkoutId === 'string' ? r.checkoutId.trim() : ''\n const sponsorId = toSponsorId(r.sponsorId)\n if (!checkoutId || sponsorId === undefined) return null\n return { checkoutId, sponsorId, name: nameOf(r.name), logoUrl: urlOrNull(r.logoUrl) }\n}\n\nfunction readEntries(): RememberedCheckoutSponsor[] {\n const store = storageRefusedWrite ? null : sessionStore()\n if (store) {\n try {\n const raw = store.getItem(CHECKOUT_SPONSOR_STORAGE_KEY)\n if (!raw) return []\n const parsed: unknown = JSON.parse(raw)\n if (Array.isArray(parsed)) {\n return parsed.map(normalizeEntry).filter((e): e is RememberedCheckoutSponsor => e !== null)\n }\n } catch {\n /* unreadable or blocked: fall back to what this page wrote */\n }\n }\n return inMemory.slice()\n}\n\nfunction writeEntries(entries: RememberedCheckoutSponsor[]): void {\n inMemory = entries.slice()\n const store = sessionStore()\n if (!store) return\n try {\n store.setItem(CHECKOUT_SPONSOR_STORAGE_KEY, JSON.stringify(entries))\n } catch {\n // Quota / blocked: the in-page copy serves this page from now on.\n storageRefusedWrite = true\n }\n}\n\n/**\n * Remember whose checkout `checkoutId` is (and the sponsor's name and logo as\n * known now), so the confirmation after a redirect (Vipps, Stripe) or a\n * reload can still name the brand when the bootstrap is late or the cart is\n * already cleared. The last 20 checkouts are kept, most recent last; a name\n * already remembered is not replaced by an empty one. Never throws.\n */\nexport function rememberCheckoutSponsor(\n checkoutId: string | null | undefined,\n sponsor: { sponsorId: number | string | null | undefined; name?: string | null; logoUrl?: string | null },\n): void {\n try {\n const id = typeof checkoutId === 'string' ? checkoutId.trim() : ''\n const sponsorId = toSponsorId(sponsor?.sponsorId)\n if (!id || sponsorId === undefined) return\n const entries = readEntries()\n const previous = entries.find((e) => e.checkoutId === id)\n let name = nameOf(sponsor.name)\n let logoUrl = urlOrNull(sponsor.logoUrl)\n if (previous && previous.sponsorId === sponsorId && !name && !logoUrl) {\n name = previous.name\n logoUrl = previous.logoUrl\n }\n const next = entries.filter((e) => e.checkoutId !== id)\n next.push({ checkoutId: id, sponsorId, name, logoUrl })\n writeEntries(next.slice(-CHECKOUT_SPONSOR_MEMORY_MAX))\n } catch {\n /* memory is a convenience — never a failure */\n }\n}\n\n/** What this tab remembers of a checkout, or `null`. Never throws. */\nexport function rememberedCheckoutSponsor(checkoutId: string | null | undefined): RememberedCheckoutSponsor | null {\n try {\n const id = typeof checkoutId === 'string' ? checkoutId.trim() : ''\n if (!id) return null\n return readEntries().find((e) => e.checkoutId === id) ?? null\n } catch {\n return null\n }\n}\n\n/** The most recent remembered checkout of a sponsor that names it, or `null`. Never throws. */\nexport function rememberedSponsor(sponsorId: number | string | null | undefined): RememberedCheckoutSponsor | null {\n try {\n const id = toSponsorId(sponsorId)\n if (id === undefined) return null\n const entries = readEntries()\n for (let i = entries.length - 1; i >= 0; i--) {\n const e = entries[i]!\n if (e.sponsorId === id && (e.name || e.logoUrl)) return e\n }\n return null\n } catch {\n return null\n }\n}\n\n/** For tests: forget the in-page copy (storage is the test's own). */\nexport function resetCheckoutSponsorMemory(): void {\n inMemory = []\n storageRefusedWrite = false\n}\n","/**\n * Apple Pay on the Web — via Stripe Payment Request API.\n *\n * Architecture decision (matches iOS Vio SDK pattern):\n * - One Stripe **publishable key** for the Vio platform (global, set\n * via `Vio.init({ stripePublishableKey })`).\n * - One **Stripe Connect account id** per sponsor — sourced from\n * `Vio.bootstrap()` response. Without it, the payment lands on the\n * platform account instead of the merchant.\n *\n * Apple Pay on the Web prerequisites (Stripe-managed for us):\n * - Stripe Connect account is enabled for Apple Pay\n * - Domain registration for Apple Pay (Stripe handles via Dashboard)\n * - Safari + macOS/iOS device with Apple Pay configured\n *\n * In Chrome / non-Apple browsers `canMakePayment()` returns null, so the\n * UI hides the Apple Pay button automatically.\n */\n\nconst STRIPE_JS_URL = 'https://js.stripe.com/v3'\n\nexport interface ApplePayConfig {\n /** Stripe platform publishable key (pk_live_xxx or pk_test_xxx). */\n publishableKey: string\n /** Sponsor's Stripe Connect account (acct_xxx). Optional but recommended. */\n connectedAccount?: string\n /** Amount in the smallest unit of the currency (e.g. øre for NOK, cents for USD). */\n amount: number\n /** ISO currency code, lowercased internally for Stripe. */\n currency: string\n /** Two-letter country code, e.g. \"NO\". */\n country: string\n /** Label shown in the Apple Pay sheet (merchant or order name). */\n label: string\n /** Whether to ask the user for payer name. */\n requestPayerName?: boolean\n /** Whether to ask the user for payer email. */\n requestPayerEmail?: boolean\n /** Whether to ask for shipping address. */\n requestShipping?: boolean\n /**\n * Shipping options shown natively in the Apple Pay sheet. `amount` is in the\n * smallest unit (øre). When set, `requestShipping` is forced on and the sheet\n * total = `amount` (items) + the selected option; switching options updates\n * the total live (Apple Pay native shipping).\n */\n shippingOptions?: Array<{ id: string; label: string; detail?: string; amount: number }>\n /**\n * Charge hook, run INSIDE the sheet's authorize event with the tokenized\n * payment. Must perform the real (backend) charge and throw on failure —\n * only then does the sheet close with success; a throw closes it with\n * failure. Its resolved value is surfaced as `ApplePayResult.confirmation`.\n */\n onAuthorize?: (result: ApplePayResult) => Promise<unknown>\n}\n\nexport interface ApplePayResult {\n /** Stripe PaymentMethod id (pm_xxx) — pass to backend to confirm the PaymentIntent. */\n paymentMethodId: string\n payerName?: string\n payerEmail?: string\n payerPhone?: string\n shippingAddress?: {\n line1?: string\n line2?: string\n city?: string\n postal_code?: string\n state?: string\n country?: string\n }\n /** Whatever `onAuthorize` resolved with (e.g. backend order_id/status). */\n confirmation?: unknown\n}\n\nlet stripeJsPromise: Promise<unknown> | null = null\n\n/** Warm the Stripe.js load ahead of time (safe to call anywhere, never throws). */\nexport function preloadStripeJs(): void {\n if (typeof window === 'undefined') return\n void loadStripeJs().catch(() => {})\n}\n\n/** Dynamically load Stripe.js exactly once. Shared with the Payment Element. */\nexport function loadStripeJs(): Promise<unknown> {\n if (stripeJsPromise) return stripeJsPromise\n if (typeof document === 'undefined') {\n return Promise.reject(new Error('[VioApplePay] Stripe.js requires a browser environment'))\n }\n stripeJsPromise = new Promise<unknown>((resolve, reject) => {\n const w = window as unknown as { Stripe?: unknown }\n if (w.Stripe) {\n resolve(w.Stripe)\n return\n }\n const existing = document.querySelector(\n `script[src^=\"${STRIPE_JS_URL}\"]`,\n ) as HTMLScriptElement | null\n if (existing) {\n existing.addEventListener('load', () => resolve(w.Stripe))\n existing.addEventListener('error', () =>\n reject(new Error('[VioApplePay] Failed to load Stripe.js')),\n )\n return\n }\n const script = document.createElement('script')\n script.src = STRIPE_JS_URL\n script.async = true\n script.addEventListener('load', () => resolve(w.Stripe))\n script.addEventListener('error', () =>\n reject(new Error('[VioApplePay] Failed to load Stripe.js')),\n )\n document.head.appendChild(script)\n })\n return stripeJsPromise\n}\n\ninterface StripeCanMakePaymentResult {\n applePay?: boolean\n googlePay?: boolean\n link?: boolean\n}\n\ninterface StripePaymentRequest {\n canMakePayment(): Promise<StripeCanMakePaymentResult | null>\n show(): void\n on(event: string, handler: (ev: unknown) => void): void\n}\n\ninterface StripeInstance {\n paymentRequest(options: Record<string, unknown>): StripePaymentRequest\n}\n\ntype StripeFactory = (\n publishableKey: string,\n options?: { stripeAccount?: string },\n) => StripeInstance\n\nasync function getStripe(config: ApplePayConfig): Promise<StripeInstance> {\n const Stripe = (await loadStripeJs()) as StripeFactory\n return Stripe(\n config.publishableKey,\n config.connectedAccount ? { stripeAccount: config.connectedAccount } : undefined,\n )\n}\n\nfunction buildRequestOptions(config: ApplePayConfig): Record<string, unknown> {\n const ship = config.shippingOptions\n // With shipping options, the sheet's total = items + the (first/selected) option.\n const preselectedShipping = ship && ship.length > 0 ? ship[0]!.amount : 0\n return {\n country: config.country,\n currency: config.currency.toLowerCase(),\n total: { label: config.label, amount: config.amount + preselectedShipping },\n requestPayerName: config.requestPayerName ?? true,\n requestPayerEmail: config.requestPayerEmail ?? true,\n requestShipping: ship && ship.length > 0 ? true : (config.requestShipping ?? false),\n ...(ship && ship.length > 0 ? { shippingOptions: ship } : {}),\n disableWallets: ['link', 'googlePay'],\n }\n}\n\n/**\n * Check whether Apple Pay is available right now (Safari + supported device\n * + Stripe configured + domain registered).\n *\n * Returns false on any failure path — never throws.\n */\nexport async function checkApplePayAvailability(config: ApplePayConfig): Promise<boolean> {\n if (typeof window === 'undefined') return false\n // Quick precheck — Apple Pay is only on Safari + supported macOS/iOS devices.\n if (typeof (window as unknown as { ApplePaySession?: unknown }).ApplePaySession === 'undefined') {\n return false\n }\n if (!config.publishableKey) return false\n try {\n const stripe = await getStripe(config)\n const pr = stripe.paymentRequest(buildRequestOptions(config))\n const result = await pr.canMakePayment()\n return !!result?.applePay\n } catch (err) {\n if (typeof console !== 'undefined') {\n console.warn('[VioApplePay] availability check failed:', err)\n }\n return false\n }\n}\n\n/**\n * Show the Apple Pay sheet. Resolves with the payment method id (`pm_xxx`)\n * after the user authorises, or rejects on cancel / error.\n *\n * The backend must then confirm a Stripe PaymentIntent with this\n * payment method id (server-side step, not handled here).\n */\nexport async function showApplePaySheet(config: ApplePayConfig): Promise<ApplePayResult | null> {\n if (!config.publishableKey) {\n throw new Error('[VioApplePay] publishableKey is required')\n }\n const stripe = await getStripe(config)\n const pr = stripe.paymentRequest(buildRequestOptions(config))\n const canMake = await pr.canMakePayment()\n if (!canMake?.applePay) {\n throw new Error('[VioApplePay] Apple Pay is not available on this device')\n }\n return new Promise<ApplePayResult | null>((resolve, reject) => {\n let settled = false\n // Apple requires the address-change event to be answered or the sheet stalls.\n pr.on('shippingaddresschange', (raw: unknown) => {\n const ev = raw as { updateWith: (u: Record<string, unknown>) => void }\n ev.updateWith({ status: 'success' })\n })\n pr.on('paymentmethod', (raw: unknown) => {\n const ev = raw as {\n paymentMethod: { id: string }\n payerName?: string\n payerEmail?: string\n payerPhone?: string\n shippingAddress?: ApplePayResult['shippingAddress']\n complete: (status: 'success' | 'fail') => void\n }\n settled = true\n const result: ApplePayResult = {\n paymentMethodId: ev.paymentMethod.id,\n payerName: ev.payerName,\n payerEmail: ev.payerEmail,\n payerPhone: ev.payerPhone,\n shippingAddress: ev.shippingAddress,\n }\n // Fail-closed: the backend charge (onAuthorize) runs BEFORE the sheet\n // closes. Success only if the charge succeeded.\n void (async () => {\n try {\n const confirmation = config.onAuthorize ? await config.onAuthorize(result) : undefined\n ev.complete('success')\n resolve({ ...result, confirmation })\n } catch (err) {\n ev.complete('fail')\n reject(err)\n }\n })()\n })\n pr.on('cancel', () => {\n // User closed the sheet — not an error.\n if (!settled) resolve(null)\n })\n pr.show()\n })\n}\n\nexport interface PreparedApplePay {\n /** True if Apple Pay can be shown (canMakePayment resolved with applePay). */\n available: boolean\n /**\n * Open the Apple Pay sheet. MUST be invoked synchronously from the click\n * handler — the async work (Stripe.js load + canMakePayment) already ran in\n * `prepareApplePay`, so this fires `pr.show()` inside the user gesture. Apple\n * blocks the sheet if `show()` is reached after an `await`.\n */\n show(): Promise<ApplePayResult>\n}\n\n/**\n * Pre-create the Apple Pay PaymentRequest and resolve `canMakePayment()` ahead\n * of the click. Express buttons should call this on load/render, then call the\n * returned `show()` synchronously on tap — preserving the user gesture that\n * Apple requires to open the sheet.\n */\nexport async function prepareApplePay(config: ApplePayConfig): Promise<PreparedApplePay> {\n const unavailable = (msg: string): PreparedApplePay => ({\n available: false,\n show: () => Promise.reject(new Error(msg)),\n })\n if (typeof window === 'undefined' || !config.publishableKey) {\n return unavailable('[VioApplePay] unavailable')\n }\n if (typeof (window as unknown as { ApplePaySession?: unknown }).ApplePaySession === 'undefined') {\n return unavailable('[VioApplePay] ApplePaySession not available')\n }\n try {\n const stripe = await getStripe(config)\n const pr = stripe.paymentRequest(buildRequestOptions(config))\n // Recompute the total live when the user switches shipping option in the\n // Apple Pay sheet: total = items (config.amount) + chosen option amount.\n if (config.shippingOptions && config.shippingOptions.length > 0) {\n pr.on('shippingoptionchange', (raw: unknown) => {\n const ev = raw as {\n shippingOption?: { id?: string }\n updateWith: (u: Record<string, unknown>) => void\n }\n const opt = config.shippingOptions?.find((o) => o.id === ev.shippingOption?.id)\n ev.updateWith({\n status: 'success',\n total: { label: config.label, amount: config.amount + (opt?.amount ?? 0) },\n })\n })\n }\n pr.on('shippingaddresschange', (raw: unknown) => {\n const ev = raw as { updateWith: (u: Record<string, unknown>) => void }\n ev.updateWith({ status: 'success' })\n })\n const result = await pr.canMakePayment()\n if (!result?.applePay) return unavailable('[VioApplePay] Apple Pay not available')\n return {\n available: true,\n show(): Promise<ApplePayResult> {\n return new Promise<ApplePayResult>((resolve, reject) => {\n let settled = false\n pr.on('paymentmethod', (raw: unknown) => {\n const ev = raw as {\n paymentMethod: { id: string }\n payerName?: string\n payerEmail?: string\n payerPhone?: string\n shippingAddress?: ApplePayResult['shippingAddress']\n complete: (status: 'success' | 'fail') => void\n }\n settled = true\n const res: ApplePayResult = {\n paymentMethodId: ev.paymentMethod.id,\n payerName: ev.payerName,\n payerEmail: ev.payerEmail,\n payerPhone: ev.payerPhone,\n shippingAddress: ev.shippingAddress,\n }\n void (async () => {\n try {\n const confirmation = config.onAuthorize ? await config.onAuthorize(res) : undefined\n ev.complete('success')\n resolve({ ...res, confirmation })\n } catch (err) {\n ev.complete('fail')\n reject(err)\n }\n })()\n })\n pr.on('cancel', () => {\n if (!settled) reject(new Error('[VioApplePay] User cancelled Apple Pay'))\n })\n pr.show() // synchronous — must run inside the click gesture\n })\n },\n }\n } catch (err) {\n if (typeof console !== 'undefined') {\n console.warn('[VioApplePay] prepare failed:', err)\n }\n return unavailable('[VioApplePay] prepare failed')\n }\n}\n","/**\n * SDK version reported in analytics events (`sdk_version`) and available\n * to consumers. Kept as a constant (not a package.json import) so the\n * core stays bundler-agnostic.\n *\n * RELEASE CHECKLIST: bump together with package.json (see CONTRIBUTING).\n */\nexport const SDK_VERSION = '0.28.0'\n","/**\n * Stripe on our own page — the Payment Element, no redirect.\n *\n * The older web flow minted a Stripe Payment Link and sent the shopper to a\n * page hosted by Stripe. This one keeps them here (Angelo, 2026-09-24):\n *\n * 1. Vio Commerce creates a PaymentIntent for the checkout\n * (`Payment { CreatePaymentIntentStripe }`) and answers with its client\n * secret AND the publishable key of the account that minted it — the\n * seller's when they brought both keys, ours otherwise. The two are\n * halves of one account: the browser confirms with the key what the\n * server minted with the secret one.\n * 2. Stripe's Payment Element is mounted in a LIGHT-DOM container, the way\n * the other embedded widgets are. Card fields are Stripe's own iframes,\n * so card data never touches this SDK or our servers.\n * 3. `confirm()` pays. A 3-D Secure challenge opens in Stripe's own modal\n * over the page: `redirect: 'if_required'` keeps the shopper here for\n * cards, and still redirects for a method that has no other way.\n * 4. The Commerce order is NOT born here. Stripe's `payment_intent.succeeded`\n * webhook creates it, verified server-side; the checkout is polled for\n * its status afterwards, exactly as the redirect return does.\n */\n\nimport { executeCartGraphQL, type CartQueryOptions } from '../../api/cart-queries.js'\nimport { loadStripeJs } from './apple-pay.js'\n\n/** What the backend hands over to pay a checkout on our page. */\nexport interface StripeIntent {\n /** `pi_..._secret_...`: what the browser confirms. */\n client_secret: string\n /** The key of the SAME account that minted the secret. */\n publishable_key: string\n customer?: string\n /**\n * Stripe Connect (ADR-0022): the seller's connected account, where the\n * intent lives. The browser must name it or Stripe answers \"no such\n * payment_intent\". Absent for every seller not on Connect.\n */\n stripe_account?: string\n}\n\nexport const CREATE_PAYMENT_INTENT_STRIPE_MUTATION = `\nmutation CreatePaymentIntentStripe($checkoutId: String!) {\n Payment {\n CreatePaymentIntentStripe(checkout_id: $checkoutId) {\n client_secret\n publishable_key\n customer\n }\n }\n}\n`\n\nexport async function createStripeIntent(\n checkoutId: string,\n options?: CartQueryOptions,\n): Promise<StripeIntent | null> {\n const json = await executeCartGraphQL(\n CREATE_PAYMENT_INTENT_STRIPE_MUTATION,\n { checkoutId },\n options,\n )\n return (json?.data?.Payment?.CreatePaymentIntentStripe as StripeIntent) ?? null\n}\n\n/** What `confirm()` answers. The browser's word is never the order. */\nexport type StripeConfirmOutcome =\n | { status: 'succeeded'; paymentIntentId?: string }\n /** Authorised but not settled yet, or Stripe redirected and will return. */\n | { status: 'pending'; paymentIntentId?: string }\n | { status: 'failed'; message?: string; code?: string }\n\nexport interface StripeElementHandle {\n confirm(): Promise<StripeConfirmOutcome>\n unmount(): void\n}\n\nexport interface MountStripeOptions {\n /** Where Stripe sends the shopper back when a method insists on leaving. */\n returnUrl: string\n theme?: { accent?: string; radiusMd?: string }\n /**\n * Stripe has PAINTED the form. `mount()` resolves long before that — up to\n * ten seconds on a cold cache (QA, 2026-09-24) — and until then the panel\n * is an empty box, so the caller keeps its \"loading\" state until this.\n */\n onReady?: () => void\n /** Stripe could not load the form at all. */\n onLoadError?: (message: string) => void\n /** Stripe's own labels. Defaults to Norwegian, like the rest of the checkout. */\n locale?: string\n}\n\n/** Stripe's own words for \"the money is in\". */\nconst SETTLED = new Set(['succeeded'])\nconst IN_FLIGHT = new Set(['processing', 'requires_capture'])\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/**\n * Mount the Payment Element. The container must live in the LIGHT DOM:\n * Stripe's iframes need a document-level element, and a shadow root hides\n * them from it.\n */\nexport async function mountStripeElement(\n container: HTMLElement,\n intent: StripeIntent,\n options: MountStripeOptions,\n): Promise<StripeElementHandle> {\n if (!intent?.client_secret || !intent.publishable_key) {\n throw new Error('[Stripe] the payment is missing its client secret or publishable key')\n }\n await loadStripeJs()\n const Stripe = (globalThis as any).Stripe\n if (typeof Stripe !== 'function') {\n throw new Error('[Stripe] stripe.js loaded but window.Stripe is missing')\n }\n // Without Connect, exactly the call of old.\n const stripe = intent.stripe_account\n ? Stripe(intent.publishable_key, { stripeAccount: intent.stripe_account })\n : Stripe(intent.publishable_key)\n const appearance: Record<string, unknown> = { theme: 'stripe' }\n const variables: Record<string, string> = {}\n if (options.theme?.accent) variables.colorPrimary = options.theme.accent\n if (options.theme?.radiusMd) variables.borderRadius = options.theme.radiusMd\n if (Object.keys(variables).length > 0) appearance.variables = variables\n\n // The rest of the checkout speaks Norwegian; Stripe's own labels (\"Card\n // number\", \"Expiration date\") should too.\n const elements = stripe.elements({\n clientSecret: intent.client_secret,\n appearance,\n locale: options.locale ?? 'nb',\n })\n const element = elements.create('payment', { layout: 'tabs' })\n if (options.onReady) element.on('ready', () => options.onReady?.())\n if (options.onLoadError) {\n element.on('loaderror', (event: any) =>\n options.onLoadError?.(String(event?.error?.message ?? 'Stripe could not load the form')),\n )\n }\n container.innerHTML = ''\n element.mount(container)\n\n let confirming = false\n return {\n async confirm(): Promise<StripeConfirmOutcome> {\n // A shopper can press twice; Stripe would refuse the second one while\n // the first is in flight.\n if (confirming) return { status: 'pending' }\n confirming = true\n try {\n const result = await stripe.confirmPayment({\n elements,\n confirmParams: { return_url: options.returnUrl },\n redirect: 'if_required',\n })\n if (result?.error) {\n return {\n status: 'failed',\n message: String(result.error.message ?? ''),\n code: String(result.error.code ?? ''),\n }\n }\n const paymentIntent = result?.paymentIntent\n const status = String(paymentIntent?.status ?? '')\n if (SETTLED.has(status)) return { status: 'succeeded', paymentIntentId: paymentIntent?.id }\n if (IN_FLIGHT.has(status)) return { status: 'pending', paymentIntentId: paymentIntent?.id }\n // requires_payment_method / requires_action / canceled: not paid.\n return { status: 'failed', code: status }\n } finally {\n confirming = false\n }\n },\n unmount(): void {\n try {\n element.unmount()\n } catch {\n /* already gone */\n }\n },\n }\n}\n/* eslint-enable @typescript-eslint/no-explicit-any */\n","/**\n * Klarna Express Checkout (KEC) — via the Klarna Web SDK v2.\n *\n * Frontend half of the flow (the only half that runs client-side):\n * 1. Load the Klarna Web SDK ESM module from Klarna's CDN.\n * 2. `KlarnaSDK({ clientId, products: ['PAYMENT'] })` → SDK instance.\n * 3. `Klarna.Payment.button({ paymentRequest, initiationMode })` → button.\n * 4. `button.mount(container)` renders the express button.\n * 5. User taps it → Klarna popup → on success the SDK yields an\n * **authorization token**.\n *\n * The authorization token is NOT an order. The merchant **backend** must\n * exchange it for an order against the Klarna Payments API\n * (`POST /payments/v1/authorizations/{token}/order`, Basic auth with the\n * server-side Klarna API key). That step needs secret credentials and is\n * intentionally out of this client module — we surface the token via\n * `onAuthorize` and let the host (or, later, vio-backend) create the order.\n *\n * Verified against Klarna Web SDK v2 docs (module URL, KlarnaSDK init,\n * Payment.button().mount(), authorization-token result). The exact\n * authorize *event name* varies by SDK minor version, so the subscription\n * below is defensive — it normalises across the documented shapes.\n *\n * Prerequisites (merchant-configured, like Stripe domain reg for Apple Pay):\n * - Klarna merchant account + a **Client Identifier** (Merchant Portal →\n * Payment settings → Client Identifiers).\n * - The integration domain registered under \"Allowed Origins\".\n * - A server-side Klarna API key for the order-creation step (backend).\n */\n\nimport { getGlobalLocale } from '../../types.js'\n\n/** Klarna Web SDK v2 ESM module (loaded from Klarna's CDN at runtime). */\nexport const KLARNA_SDK_URL = 'https://js.klarna.com/web-sdk/v2/klarna.mjs'\n\n/** One line in the express button's purchase data. Amounts in MINOR units. */\nexport interface KlarnaLineItem {\n name: string\n quantity: number\n /** Line total (unitPrice × quantity), minor units (e.g. øre for NOK). */\n totalAmount: number\n /** Per-unit price, minor units. Optional. */\n unitPrice?: number\n /** Merchant SKU / product reference. Optional. */\n reference?: string\n /** Absolute image URL. Optional. */\n imageUrl?: string\n}\n\n/** Payment request handed to the KEC button. Amounts in MINOR units. */\nexport interface KlarnaPaymentRequestData {\n /** ISO currency code (e.g. \"NOK\"). */\n currency: string\n /** Order total in minor units. */\n amount: number\n /** Line items — shown in the Klarna sheet. */\n supplementaryPurchaseData?: { lineItems: KlarnaLineItem[] }\n}\n\nexport interface KlarnaConfig {\n /** Klarna Client Identifier (public-safe — fine in client bundles). */\n clientId: string\n /** Optional BCP-47 locale, e.g. \"nb-NO\". */\n locale?: string\n /**\n * Klarna environment. `playground` = sandbox (test orders, \"TEST DRIVE\"\n * badge, no real money). `production` = live. Defaults to the SDK's own\n * default when omitted. The clientId must be generated for the matching\n * environment in the Klarna Merchant Portal.\n */\n environment?: 'playground' | 'production'\n}\n\nexport interface KlarnaAuthorizeResult {\n /** Authorization token — backend exchanges it for an order. */\n authorizationToken: string\n /** Klarna may require a finalize step (multistep flows). */\n finalizeRequired?: boolean\n /** Raw payload from the SDK, for debugging / forward-compat. */\n raw?: unknown\n}\n\nexport interface KlarnaButtonHandle {\n unmount(): void\n}\n\n// ── Minimal structural typings for the runtime-loaded SDK ────────────────\n// We don't ship Klarna's .d.ts; the SDK is fetched at runtime, so these are\n// just enough to call it type-safely.\n\ninterface KlarnaButtonInstance {\n mount(container: string | HTMLElement): KlarnaButtonInstance\n unmount(): KlarnaButtonInstance\n on(event: string, cb: (...args: unknown[]) => unknown): KlarnaButtonInstance\n}\n\ninterface KlarnaPaymentNamespace {\n button(config: Record<string, unknown>): KlarnaButtonInstance\n /**\n * Opens the Klarna flow. Takes a callback that returns the payment-request\n * data (or a Promise of it). Must be invoked synchronously from the\n * button's `click` handler so the popup keeps the user gesture. Resolves\n * with the authorization result once the user completes the popup.\n */\n initiate(resolvePaymentRequest: () => unknown): Promise<unknown>\n on?(event: string, cb: (...args: unknown[]) => unknown): unknown\n}\n\ninterface KlarnaSdkInstance {\n Payment: KlarnaPaymentNamespace\n}\n\ntype KlarnaSdkFactory = (config: Record<string, unknown>) => Promise<KlarnaSdkInstance>\n\n// Memoise the SDK instance per clientId so re-opening checkout reuses it.\nconst sdkCache = new Map<string, Promise<KlarnaSdkInstance>>()\n\nfunction loadKlarnaSdk(config: KlarnaConfig): Promise<KlarnaSdkInstance> {\n if (typeof window === 'undefined') {\n return Promise.reject(new Error('[VioKlarna] requires a browser environment'))\n }\n if (!config.clientId) {\n return Promise.reject(new Error('[VioKlarna] clientId is required'))\n }\n // Key the cache by clientId + environment so switching env re-inits.\n const cacheKey = `${config.clientId}:${config.environment ?? 'default'}`\n const cached = sdkCache.get(cacheKey)\n if (cached) return cached\n\n // Dynamic import of an absolute CDN URL. `@vite-ignore` stops the bundler\n // from trying to resolve/inline it — it stays a runtime fetch.\n const url = KLARNA_SDK_URL\n const promise = import(/* @vite-ignore */ url)\n .then((mod: { KlarnaSDK?: KlarnaSdkFactory; default?: KlarnaSdkFactory }) => {\n const factory = mod.KlarnaSDK ?? mod.default\n if (typeof factory !== 'function') {\n throw new Error('[VioKlarna] KlarnaSDK factory not found in module')\n }\n return factory({\n clientId: config.clientId,\n products: ['PAYMENT'],\n ...(config.locale ? { locale: config.locale } : {}),\n ...(config.environment ? { environment: config.environment } : {}),\n })\n })\n .catch((err) => {\n // Don't poison the cache on failure — allow a later retry.\n sdkCache.delete(cacheKey)\n throw err\n })\n sdkCache.set(cacheKey, promise)\n return promise\n}\n\n/**\n * True if Klarna Express can be offered right now (clientId set + SDK loads).\n * Never throws — returns false on any failure path (mirrors Apple Pay).\n */\nexport async function isKlarnaAvailable(config: KlarnaConfig): Promise<boolean> {\n if (typeof window === 'undefined' || !config.clientId) return false\n try {\n await loadKlarnaSdk(config)\n return true\n } catch (err) {\n if (typeof console !== 'undefined') {\n console.warn('[VioKlarna] availability check failed:', err)\n }\n return false\n }\n}\n\n/** Recursively search a result object for an authorization token. */\nfunction findAuthToken(value: unknown, depth = 0): string | undefined {\n if (!value || depth > 4 || typeof value !== 'object') return undefined\n const o = value as Record<string, unknown>\n for (const key of ['authorizationToken', 'authorization_token', 'authToken']) {\n if (typeof o[key] === 'string' && (o[key] as string).length > 0) return o[key] as string\n }\n for (const k of Object.keys(o)) {\n const found = findAuthToken(o[k], depth + 1)\n if (found) return found\n }\n return undefined\n}\n\n/**\n * Build + mount the Klarna Express button into `container`.\n *\n * Flow (Klarna Web SDK v2): the button's `click` handler **synchronously**\n * calls `Klarna.Payment.initiate(cb)` — `cb` returns the payment-request\n * data. That call opens the Klarna popup (the synchronous call preserves the\n * user gesture). The returned Promise resolves with the authorization result\n * once the user completes the popup; we pull the authorization token out and\n * hand it to `onAuthorize`. The token is NOT an order — the backend creates\n * the order from it.\n */\nexport async function mountKlarnaExpressButton(opts: {\n config: KlarnaConfig\n container: HTMLElement\n paymentRequest: KlarnaPaymentRequestData\n /** URL Klarna returns to after a redirect-based completion. Required by KEC. */\n returnUrl?: string\n /**\n * sessionStorage key + payload to persist BEFORE launching. On a redirect\n * completion the page reloads (the initiate() promise is lost), so the\n * resume handler reads this back to recreate the order. Survives the\n * cross-origin redirect because sessionStorage is per-tab.\n */\n pendingKey?: string\n pendingContext?: unknown\n onAuthorize: (result: KlarnaAuthorizeResult) => void\n onError?: (err: unknown) => void\n}): Promise<KlarnaButtonHandle> {\n const sdk = await loadKlarnaSdk(opts.config)\n\n const button = sdk.Payment.button({\n id: 'vio-klarna-express',\n // `PAY` = one-time purchase (vs BUY/SUBSCRIBE). Must be an array.\n intents: ['PAY'],\n // initiationMode belongs on the BUTTON config (per Klarna Web SDK docs),\n // NOT inside the initiate() data — when set only in initiate() the SDK\n // falls back to its default (DEVICE_BEST → desktop popup), which opened\n // and closed without completing. Forcing REDIRECT here makes the click do\n // a full-page navigation to Klarna's hosted journey, returning via\n // `returnUrl` (recovered by resumeKlarnaReturn()).\n initiationMode: 'REDIRECT',\n })\n\n // Clean origin+path (no existing query/hash) so Klarna's appended result\n // params land on a predictable URL the resume handler can parse.\n const returnUrl =\n opts.returnUrl ??\n (typeof window !== 'undefined'\n ? window.location.origin + window.location.pathname\n : '')\n\n let settled = false\n button.on('click', () => {\n // Persist the pending order so a REDIRECT completion (page reloads, this\n // promise never resolves) can be recovered on the return page.\n if (opts.pendingKey && opts.pendingContext && typeof sessionStorage !== 'undefined') {\n try {\n sessionStorage.setItem(opts.pendingKey, JSON.stringify(opts.pendingContext))\n } catch {\n /* storage unavailable — popup mode still works via the promise */\n }\n }\n // initiate() MUST be called synchronously here — going async first would\n // drop the user-gesture and the browser would block the popup.\n const promise = sdk.Payment.initiate(() => ({\n currency: opts.paymentRequest.currency,\n paymentAmount: opts.paymentRequest.amount,\n intents: ['PAY'],\n locale: getGlobalLocale(),\n // REDIRECT = full-page navigation to Klarna's hosted journey, then back\n // to `returnUrl` with the result. We force this (vs DEVICE_BEST's desktop\n // popup) because the popup proved unreliable here — it opened and closed\n // without completing. The redirect flow has no popup-blocker / window-\n // messaging failure modes; the return is recovered via resumeKlarnaReturn().\n initiationMode: 'REDIRECT',\n returnUrl,\n ...(opts.paymentRequest.supplementaryPurchaseData\n ? { supplementaryPurchaseData: opts.paymentRequest.supplementaryPurchaseData }\n : {}),\n }))\n\n Promise.resolve(promise)\n .then((result) => {\n if (settled) return\n const token = findAuthToken(result)\n if (token) {\n settled = true\n opts.onAuthorize({ authorizationToken: token, raw: result })\n } else if (typeof console !== 'undefined') {\n // Resolved without a recognisable token — log so we can map the\n // shape. Don't confirm the order on an ambiguous resolve.\n console.warn('[VioKlarna] authorize resolved without a token:', result)\n }\n })\n .catch((err) => {\n // Reject = user cancelled or a validation/auth error. Not a success.\n opts.onError?.(err)\n })\n\n // Hand the same promise back to the SDK (its contract for the handler).\n return promise\n })\n\n button.mount(opts.container)\n\n return {\n unmount: () => {\n try {\n button.unmount()\n } catch {\n /* already gone */\n }\n },\n }\n}\n\n/**\n * Read a Klarna authorization token from the current URL's query string.\n * Klarna's redirect completion appends it; param name varies, so check the\n * known variants. Returns the token + the param name found (to clean later).\n */\nexport function readKlarnaTokenFromUrl(): { token: string; param: string } | null {\n if (typeof window === 'undefined') return null\n const params = new URLSearchParams(window.location.search)\n for (const name of [\n 'authorization_token',\n 'authorizationToken',\n 'klarna_authorization_token',\n 'vio_klarna_token',\n ]) {\n const v = params.get(name)\n if (v && v.length > 0 && v !== '{klarna.authorization_token}') {\n return { token: v, param: name }\n }\n }\n return null\n}\n\n/** Strip the given query params from the URL without reloading. */\nexport function cleanUrlParams(params: string[]): void {\n if (typeof window === 'undefined' || !window.history?.replaceState) return\n const url = new URL(window.location.href)\n let changed = false\n for (const p of params) {\n if (url.searchParams.has(p)) {\n url.searchParams.delete(p)\n changed = true\n }\n }\n if (changed) window.history.replaceState({}, '', url.toString())\n}\n\n/**\n * Subscribe to the SDK's namespace-level `complete`/`error` events. On a\n * REDIRECT return the SDK resumes its persisted session and fires `complete`\n * with the authorization token — this is how we recover the token when the\n * page reloaded and the initiate() promise was lost.\n *\n * Never throws; logs and resolves even if the SDK can't load.\n */\nexport async function listenForKlarnaCompletion(opts: {\n config: KlarnaConfig\n onComplete: (result: KlarnaAuthorizeResult) => void\n onError?: (err: unknown) => void\n}): Promise<void> {\n let sdk: KlarnaSdkInstance\n try {\n sdk = await loadKlarnaSdk(opts.config)\n } catch (err) {\n if (typeof console !== 'undefined') {\n console.warn('[VioKlarna] resume: SDK load failed:', err)\n }\n return\n }\n let settled = false\n const onComplete = (...args: unknown[]) => {\n if (settled) return\n for (const a of args) {\n const token = findAuthToken(a)\n if (token) {\n settled = true\n opts.onComplete({ authorizationToken: token, raw: a })\n return\n }\n }\n }\n try {\n sdk.Payment.on?.('complete', onComplete)\n } catch {\n /* unsupported */\n }\n try {\n sdk.Payment.on?.('error', (...a: unknown[]) => opts.onError?.(a[0]))\n } catch {\n /* unsupported */\n }\n}\n","/**\n * Klarna Payments — classic widget flow (`kp/lib/v1/api.js`).\n *\n * This is the alternative to KEC (Web SDK v2 button + `initiate` redirect).\n * Instead of a public `clientId` + origin handshake (which 403'd on the\n * `klarnaevt` bridge from localhost), it uses a **server-minted client_token**:\n *\n * 1. Vio Commerce creates a Payments session → `client_token` + categories\n * (GraphQL `Payment { CreatePaymentKlarnaNative }`, authed with the\n * sponsor's commerce API key).\n * 2. We load Klarna's widget **inline** (an iframe) into a container via\n * `Klarna.Payments.init({ client_token })` + `Klarna.Payments.load(...)`.\n * 3. The customer picks/fills a method; `Klarna.Payments.authorize(...)`\n * yields an `authorization_token`.\n * 4. Vio Commerce exchanges the token for a real order\n * (GraphQL `Payment { ConfirmPaymentKlarnaNative }`).\n *\n * No redirect, no popup, no public clientId — so the origin/handshake failure\n * mode simply doesn't apply here.\n *\n * All payment legs go through **Vio Commerce**. The Vio backend has no\n * payment routes — it never sees card data, tokens, or Klarna credentials.\n */\n\n/** Klarna Payments JS library (classic). Loaded via <script>, sets window.Klarna. */\nexport const KLARNA_KP_LIB_URL = 'https://x.klarnacdn.net/kp/lib/v1/api.js'\n\nexport interface KlarnaPaymentsCategory {\n identifier: string\n name: string\n asset_urls?: { descriptive?: string; standard?: string }\n}\n\n// ── Minimal runtime typings for the <script>-loaded global ────────────────\ninterface KpLoadResult {\n show_form?: boolean\n error?: unknown\n}\ninterface KpAuthorizeResult {\n approved?: boolean\n show_form?: boolean\n authorization_token?: string\n finalize_required?: boolean\n error?: unknown\n}\ninterface KlarnaPaymentsApi {\n init(opts: { client_token: string }): void\n load(\n opts: { container: string | HTMLElement; payment_method_category?: string },\n data: Record<string, unknown>,\n cb?: (res: KpLoadResult) => void,\n ): void\n authorize(\n opts: { payment_method_category?: string; auto_finalize?: boolean },\n data: Record<string, unknown>,\n cb?: (res: KpAuthorizeResult) => void,\n ): void\n /** Debug/lifecycle events — e.g. 'fullscreenOverlayShown'/'fullscreenOverlayHidden'. */\n on?(event: string, cb: () => void): void\n}\ninterface KlarnaGlobal {\n Payments: KlarnaPaymentsApi\n}\n\ndeclare global {\n interface Window {\n Klarna?: KlarnaGlobal\n klarnaAsyncCallback?: () => void\n }\n}\n\nlet kpLoad: Promise<KlarnaGlobal> | null = null\n\n/** Load kp/lib/v1/api.js once; resolves when window.Klarna.Payments is ready. */\nfunction loadKpLib(): Promise<KlarnaGlobal> {\n if (typeof window === 'undefined' || typeof document === 'undefined') {\n return Promise.reject(new Error('[VioKlarnaKP] requires a browser environment'))\n }\n if (window.Klarna?.Payments) return Promise.resolve(window.Klarna)\n if (kpLoad) return kpLoad\n\n kpLoad = new Promise<KlarnaGlobal>((resolve, reject) => {\n const timer = setTimeout(\n () => reject(new Error('[VioKlarnaKP] kp/lib/v1/api.js load timed out')),\n 12000,\n )\n const ready = () => {\n clearTimeout(timer)\n if (window.Klarna?.Payments) resolve(window.Klarna)\n else reject(new Error('[VioKlarnaKP] Klarna global missing after ready'))\n }\n // Klarna invokes window.klarnaAsyncCallback once the lib is initialised.\n const prev = window.klarnaAsyncCallback\n window.klarnaAsyncCallback = () => {\n if (typeof prev === 'function') {\n try {\n prev()\n } catch {\n /* host callback threw — ignore */\n }\n }\n ready()\n }\n\n const existing = document.querySelector<HTMLScriptElement>(\n `script[src=\"${KLARNA_KP_LIB_URL}\"]`,\n )\n if (existing) {\n // Script already in the DOM (e.g. re-open). If Klarna is up, resolve now;\n // otherwise our klarnaAsyncCallback above will fire.\n if (window.Klarna?.Payments) ready()\n } else {\n const s = document.createElement('script')\n s.src = KLARNA_KP_LIB_URL\n s.async = true\n s.onerror = () => {\n clearTimeout(timer)\n kpLoad = null\n reject(new Error('[VioKlarnaKP] failed to load kp/lib/v1/api.js'))\n }\n document.head.appendChild(s)\n }\n }).catch((err) => {\n kpLoad = null // allow retry\n throw err\n })\n\n return kpLoad\n}\n\nexport interface KlarnaPaymentsWidgetInput {\n clientToken: string\n /** Klarna session id (native GraphQL flow) — informational, for callers/logs. */\n sessionId?: string\n categories: KlarnaPaymentsCategory[]\n container: HTMLElement\n /** Category to load first. Defaults to the first available. */\n category?: string\n}\n\nexport interface KlarnaPaymentsWidget {\n /** Categories offered by the session (pay_now / pay_later / pay_over_time). */\n categories: KlarnaPaymentsCategory[]\n /** Currently selected payment_method_category. */\n selected: string\n /** (Re)load the widget for a category into the container. */\n load(category?: string): Promise<{ showForm: boolean }>\n /**\n * Authorize a category. Resolves with the authorization token, rejects on\n * decline/cancel/error. `category` overrides `selected` for this call (and\n * reloads the widget first if it differs) — pass it explicitly rather than\n * relying on `selected` alone, since a caller UI's own state and the\n * widget's internal `selected` can drift. `data` is an optional order-data\n * update (the session already carries the lines; pass billing/extra if\n * available).\n */\n authorize(category?: string, data?: Record<string, unknown>): Promise<string>\n}\n\n/** True if the Klarna Payments lib can load in this environment. */\nexport async function isKlarnaPaymentsAvailable(): Promise<boolean> {\n if (typeof window === 'undefined') return false\n try {\n await loadKpLib()\n return true\n } catch (err) {\n if (typeof console !== 'undefined') {\n console.warn('[VioKlarnaKP] availability check failed:', err)\n }\n return false\n }\n}\n\n/**\n * Init Klarna Payments with a server-minted client_token and mount the widget.\n * Returns a handle to (re)load categories and to authorize.\n */\n/** Pick the direct-payment category (\"Betal nå\") when the session offers one —\n * the demo sells physical goods paid up front, not financing. Ported from\n * Alan's round-5 improvement. */\nexport function findPayNowCategory(categories: KlarnaPaymentsCategory[]): string | null {\n if (!Array.isArray(categories) || categories.length === 0) return null\n const byId = (re: RegExp) => categories.find((c) => c?.identifier && re.test(c.identifier))\n const byName = (re: RegExp) => categories.find((c) => c?.name && re.test(c.name))\n const cat =\n categories.find((c) => c?.identifier === 'pay_now') ??\n byName(/betal\\s*n[åa]|pay\\s*now/i) ??\n byId(/pay_now|direct_debit|direct_bank_transfer|pay_in_full|klarna_pay_now/i) ??\n byName(/direkte|bank|kort|straks|sofort/i) ??\n categories.find((c) => c?.identifier && !/pay_later|pay_over_time|slice_it/.test(c.identifier))\n console.log('findPayNowCategory - Selected: ', cat)\n return cat?.identifier ?? null\n}\n\nexport async function createKlarnaPaymentsWidget(\n input: KlarnaPaymentsWidgetInput,\n): Promise<KlarnaPaymentsWidget> {\n const Klarna = await loadKpLib()\n console.log('[DEBUG Klarna] Initializing Klarna Payments')\n Klarna.Payments.init({ client_token: input.clientToken })\n console.log('[DEBUG Klarna] Klarna Payments initialized')\n Klarna.Payments.on?.('fullscreenOverlayShown', () => {\n console.log('[DEBUG Klarna] FULLSCREEN OVERLAY SHOWN')\n })\n Klarna.Payments.on?.('fullscreenOverlayHidden', () => {\n console.log('[DEBUG Klarna] FULLSCREEN OVERLAY HIDDEN')\n })\n\n let selected =\n input.category ??\n findPayNowCategory(input.categories) ??\n input.categories[0]?.identifier ??\n 'pay_now'\n if (typeof console !== 'undefined') {\n console.log('[VioKlarna] Received payment_method_categories from backend:', input.categories)\n console.log('[VioKlarna] Selected initial payment_method_category:', selected)\n }\n\n const load = (category?: string): Promise<{ showForm: boolean }> => {\n if (category) selected = category\n if (typeof console !== 'undefined') {\n console.log(\n '[VioKlarna] Klarna.Payments.load calling with payment_method_category:',\n selected,\n 'container:',\n input.container,\n )\n }\n // Clear any previously-rendered iframe before reloading a different\n // category — Klarna's widget doesn't always replace its own markup\n // cleanly on a second load() into the same container.\n if (input.container && 'innerHTML' in input.container) {\n input.container.innerHTML = ''\n }\n return new Promise((resolve, reject) => {\n try {\n // 3-arg form per Klarna docs: (options, data, callback). The empty\n // data object is required — a 2-arg call risks the SDK treating the\n // callback as `data` and never invoking it.\n Klarna.Payments.load(\n { container: input.container, payment_method_category: selected },\n {},\n (res) => {\n if (typeof console !== 'undefined') {\n console.log(\n '[VioKlarna] Klarna.Payments.load response for payment_method_category:',\n selected,\n res,\n )\n }\n if (res?.error) reject(res.error)\n else resolve({ showForm: res?.show_form !== false })\n },\n )\n } catch (err) {\n reject(err)\n }\n })\n }\n\n return {\n categories: input.categories,\n get selected() {\n return selected\n },\n load,\n async authorize(category?: string, data?: Record<string, unknown>): Promise<string> {\n const cat = category || selected\n if (typeof console !== 'undefined') {\n console.log('[DEBUG Klarna] BEFORE AUTHORIZE', {\n argumentCategory: category,\n argumentData: data,\n selected,\n resolvedCategory: cat,\n })\n }\n // If the caller asked for a category different from what's currently\n // loaded, reload the widget first — authorizing against a stale\n // `selected` would charge/confirm the wrong payment method category.\n if (cat && cat !== selected) {\n await load(cat)\n }\n const finalData = { payment_method_category: cat, ...(data ?? {}) }\n if (typeof console !== 'undefined') {\n console.log('[DEBUG Klarna] FINAL AUTHORIZE', { cat, selected, finalData })\n }\n return new Promise<string>((resolve, reject) => {\n try {\n if (typeof console !== 'undefined') {\n console.log('[DEBUG Klarna] ABOUT TO CALL AUTHORIZE')\n }\n Klarna.Payments.authorize(\n { payment_method_category: cat, auto_finalize: true },\n finalData,\n (res) => {\n if (typeof console !== 'undefined') {\n console.log('[DEBUG Klarna] RAW AUTHORIZE RESPONSE:', JSON.stringify(res, null, 2))\n }\n if (res?.approved && res.authorization_token) {\n resolve(res.authorization_token)\n } else if (res?.error) {\n reject(res.error)\n } else if (res?.finalize_required) {\n reject(new Error('Klarna requires a finalize step (multistep)'))\n } else {\n // approved:false without an error == user cancelled / declined.\n reject(new Error('Klarna authorization was not approved'))\n }\n },\n )\n if (typeof console !== 'undefined') {\n console.log('[DEBUG Klarna] AUTHORIZE CALL RETURNED')\n }\n } catch (err) {\n reject(err)\n }\n })\n },\n }\n}\n","/**\n * Kustom (former Klarna Checkout) — embedded KCO v3 checkout.\n *\n * Kustom kept the Klarna Checkout dialect on its own hosts, so the flow is\n * the classic KCO embed:\n *\n * 1. Vio Commerce creates the order (`Payment { CreatePaymentKustom }`,\n * authed with the sponsor's commerce API key; the seller's own\n * kco_*_api_* key lives server-side, per seller, never here). One order\n * per checkout: asking again while it is open UPDATES it.\n * 2. The response's `html_snippet` is injected into a LIGHT-DOM container\n * — it renders Kustom's iframe, which collects address, shipping AND\n * payment by itself (the widget does everything; no Vio address form).\n * 3. While it is open, the widget talks through `window._klarnaCheckout`:\n * we suspend it around a cart change (`Payment { SyncPaymentKustom }`),\n * and listen to its totals so our summary never disagrees with it.\n * 4. On completion Kustom redirects to the confirmation URL\n * (`?order_id=…&payment_processor=KUSTOM&checkout_id=…`), where the SDK\n * re-reads the order (`Payment { GetKustomOrder }`) — the backend\n * completes it right there — and renders Kustom's own receipt.\n *\n * The Commerce order is created server-side, from what Kustom says it\n * charged (Order Management), whether the shopper comes back or not (the\n * push) — the browser never confirms money.\n */\n\nimport { executeCartGraphQL, type CartQueryOptions } from '../../api/cart-queries.js'\n\n/** A Kustom order as shopcart normalizes it (never Kustom's raw order). */\nexport interface KustomOrder {\n order_id: string\n /** `checkout_incomplete` | `checkout_complete`, lower-cased by the backend. */\n status: string\n html_snippet: string\n purchase_country?: string\n purchase_currency?: string\n checkout_id?: string\n environment?: string\n /** Goods + the shipping shown or charged, decimal. */\n total_price?: number\n shipping_name?: string\n shipping_price?: number\n /** Whether the Vio Commerce order exists (after completion). */\n order_created?: boolean\n /** Kustom's short shopper-facing reference (after completion). */\n reference?: string\n}\n\nconst KUSTOM_ORDER_FIELDS = `\n order_id\n status\n html_snippet\n purchase_country\n purchase_currency\n checkout_id\n environment\n total_price\n shipping_name\n shipping_price\n order_created\n reference`\n\nexport const CREATE_PAYMENT_KUSTOM_MUTATION = `\nmutation CreatePaymentKustom($checkoutId: String!, $countryCode: String!, $href: String!, $email: String, $client: String) {\n Payment {\n CreatePaymentKustom(checkout_id: $checkoutId, country_code: $countryCode, href: $href, email: $email, client: $client) {${KUSTOM_ORDER_FIELDS}\n }\n }\n}\n`\n\nexport const GET_KUSTOM_ORDER_QUERY = `\nquery GetKustomOrder($orderId: String!) {\n Payment {\n GetKustomOrder(order_id: $orderId) {${KUSTOM_ORDER_FIELDS}\n }\n }\n}\n`\n\nexport const SYNC_PAYMENT_KUSTOM_MUTATION = `\nmutation SyncPaymentKustom($checkoutId: String!) {\n Payment {\n SyncPaymentKustom(checkout_id: $checkoutId) {${KUSTOM_ORDER_FIELDS}\n }\n }\n}\n`\n\nexport interface CreatePaymentKustomVariables extends Record<string, unknown> {\n checkoutId: string\n countryCode: string\n href: string\n email?: string\n client?: string\n}\n\nexport async function createPaymentKustom(\n variables: CreatePaymentKustomVariables | Record<string, unknown>,\n options?: CartQueryOptions,\n): Promise<KustomOrder | null> {\n const json = await executeCartGraphQL(CREATE_PAYMENT_KUSTOM_MUTATION, variables, options)\n return (json?.data?.Payment?.CreatePaymentKustom as KustomOrder) ?? null\n}\n\nexport async function getKustomOrder(\n orderId: string,\n options?: CartQueryOptions,\n): Promise<KustomOrder | null> {\n const json = await executeCartGraphQL(GET_KUSTOM_ORDER_QUERY, { orderId }, options)\n return (json?.data?.Payment?.GetKustomOrder as KustomOrder) ?? null\n}\n\n/** Push the current cart into the checkout's open Kustom order. */\nexport async function syncPaymentKustom(\n checkoutId: string,\n options?: CartQueryOptions,\n): Promise<KustomOrder | null> {\n const json = await executeCartGraphQL(SYNC_PAYMENT_KUSTOM_MUTATION, { checkoutId }, options)\n return (json?.data?.Payment?.SyncPaymentKustom as KustomOrder) ?? null\n}\n\n/**\n * The page URL Kustom appends its redirect params to. shopcart builds the\n * confirmation URL as `${href}?order_id={checkout.order.id}&…`, so the href\n * MUST NOT already carry a query string — origin + pathname only.\n */\nexport function kustomCleanHref(): string {\n if (typeof window === 'undefined' || !window.location) return ''\n return `${window.location.origin}${window.location.pathname}`\n}\n\n/**\n * Inject a KCO html_snippet and EXECUTE its inline scripts — innerHTML alone\n * leaves <script> tags inert, so each one is recreated node-by-node. This is\n * the standard Klarna Checkout embed technique, unchanged under Kustom.\n */\nexport function renderKustomSnippet(container: HTMLElement, htmlSnippet: string): void {\n container.innerHTML = htmlSnippet\n const scripts = Array.from(container.querySelectorAll('script'))\n for (const oldScript of scripts) {\n const newScript = document.createElement('script')\n for (const attr of Array.from(oldScript.attributes)) {\n newScript.setAttribute(attr.name, attr.value)\n }\n newScript.text = oldScript.text\n oldScript.parentNode?.replaceChild(newScript, oldScript)\n }\n}\n\n/* ── The widget's JavaScript API (`window._klarnaCheckout`) ─────────────── */\n\n/**\n * The slice of Kustom's client-side API this SDK uses. Kustom kept the\n * `_klarnaCheckout` name: the snippet defines it, and it queues callbacks\n * until the iframe has rendered.\n */\nexport interface KustomApi {\n suspend(options?: { autoResume?: { enabled: boolean } }): void\n resume(): void\n on(listeners: Record<string, (data: any, callback?: (r: any) => void) => void>): void\n}\n\ntype KustomApiFn = (cb: (api: KustomApi) => void) => void\n\n/** The widget's API, or null when no snippet has defined it yet. */\nexport function kustomApi(): KustomApiFn | null {\n if (typeof window === 'undefined') return null\n const fn = (window as any)._klarnaCheckout\n return typeof fn === 'function' ? (fn as KustomApiFn) : null\n}\n\n/**\n * Lock the widget while the order is being changed server-side. Kustom\n * auto-resumes after 10 s unless told otherwise; the sync is one call, so\n * the automatic resume stays as the safety net.\n */\nexport function suspendKustom(): boolean {\n const api = kustomApi()\n if (!api) return false\n api((a) => a.suspend())\n return true\n}\n\n/** Refresh the widget with the order as it now is at Kustom. */\nexport function resumeKustom(): boolean {\n const api = kustomApi()\n if (!api) return false\n api((a) => a.resume())\n return true\n}\n\nexport interface KustomShippingChange {\n id?: string\n name?: string\n description?: string\n /** Minor units, as the widget reports them. */\n price?: number\n tax_amount?: number\n tax_rate?: number\n}\n\nexport interface KustomListenerHandlers {\n /** The iframe rendered. */\n onLoad?: (data: any) => void\n /** The order total the widget shows, in MINOR units. */\n onOrderTotalChange?: (orderTotalMinor: number) => void\n /** The shopper picked a rate inside the widget. */\n onShippingOptionChange?: (option: KustomShippingChange) => void\n /** The shopper could not pay (declined credit…): show another way. */\n onCannotComplete?: () => void\n onNetworkError?: () => void\n /** The shopper is about to leave for the confirmation page. */\n onRedirectInitiated?: () => void\n}\n\n/**\n * Subscribe to the widget's events. Kustom has no `off`, so the returned\n * `destroy` disarms the handlers: a widget torn down and re-rendered must not\n * keep driving a summary that no longer exists.\n */\nexport function installKustomListeners(handlers: KustomListenerHandlers): { destroy(): void } {\n let alive = true\n const api = kustomApi()\n if (api) {\n api((a) => {\n a.on({\n load: (data) => alive && handlers.onLoad?.(data),\n order_total_change: (data) => {\n const total = Number(data?.order_total)\n if (alive && Number.isFinite(total)) handlers.onOrderTotalChange?.(total)\n },\n shipping_option_change: (data) => alive && handlers.onShippingOptionChange?.(data ?? {}),\n can_not_complete_order: () => alive && handlers.onCannotComplete?.(),\n network_error: () => alive && handlers.onNetworkError?.(),\n redirect_initiated: () => alive && handlers.onRedirectInitiated?.(),\n })\n })\n }\n return {\n destroy() {\n alive = false\n },\n }\n}\n\n/* ── The return trip ────────────────────────────────────────────────────── */\n\n/** Query keys Kustom's redirects and our own rejection page add to the URL. */\nexport const KUSTOM_RETURN_QUERY_KEYS = [\n 'order_id',\n 'payment_processor',\n 'checkout_id',\n 'vio_payment',\n 'vio_method',\n] as const\n\n/**\n * What a URL says about a Kustom round trip:\n * - `confirmation`: Kustom sent the shopper back paid (`payment_processor=KUSTOM`);\n * - `rejected`: our validation callback refused the purchase and Kustom\n * showed the shopper the reason inside the widget — nothing to read;\n * - null: not a Kustom return.\n */\nexport function kustomReturnOutcome(\n params: URLSearchParams,\n): { kind: 'confirmation'; orderId: string; checkoutId?: string } | { kind: 'rejected'; checkoutId?: string } | null {\n const orderId = params.get('order_id') || ''\n if (params.get('payment_processor') === 'KUSTOM' && orderId) {\n return { kind: 'confirmation', orderId, checkoutId: params.get('checkout_id') || undefined }\n }\n if (params.get('vio_payment') === 'rejected' && params.get('vio_method') === 'kustom') {\n return { kind: 'rejected', checkoutId: params.get('checkout_id') || undefined }\n }\n return null\n}\n","/**\n * Qliro Checkout — embedded checkout via Vio Commerce.\n *\n * Same embed philosophy as Kustom (the widget collects address, shipping\n * AND payment), different provider API underneath — shopcart normalizes\n * Qliro's Merchant API (OrderId / CustomerCheckoutStatus / OrderHtmlSnippet)\n * to the { order_id, status, html_snippet } shape both flows share:\n *\n * 1. `Payment { CreatePaymentQliro }` creates the order and returns the\n * snippet (sponsor-key authed; the seller's MerchantApiKey/Secret live\n * server-side, per seller, never here).\n * 2. The snippet is injected (script-executing embed, shared with Kustom).\n * 3. On completion Qliro redirects to the confirmation URL\n * (`?checkout_id=…&payment_processor=QLIRO`); the SDK re-reads the\n * order via `Payment { GetQliroOrder(checkout_id) }` — Qliro\n * correlates by the OWNING CHECKOUT, not the order id — and renders\n * the snippet again, which shows Qliro's own receipt.\n *\n * The Commerce order is created server-side by Qliro's push webhook\n * (shopcart /checkout/payment/qliro/ok) — the browser never confirms money.\n */\n\nimport { executeCartGraphQL, type CartQueryOptions } from '../../api/cart-queries.js'\nimport { kustomCleanHref, renderKustomSnippet } from './kustom.js'\n\n/** Normalized Qliro order (shopcart maps the PascalCase Merchant API). */\nexport interface QliroOrder {\n order_id: string\n /** Qliro CustomerCheckoutStatus: InProcess | Completed | OnHold | Refused. */\n status: string\n html_snippet: string\n purchase_country?: string\n purchase_currency?: string\n total_price?: number\n}\n\n/**\n * The Vio theme tokens Qliro can be dressed with.\n *\n * Qliro fixes its appearance at CREATE ORDER — there is no way to restyle the\n * widget once it has rendered — so the tokens have to travel with the order.\n * They are sent as Vio tokens, not Qliro field names: the mapping and the\n * validation live in shopcart, where they can be tested without a browser.\n */\nexport interface QliroTheme {\n accent?: string\n surface?: string\n radiusMd?: string\n radiusLg?: string\n}\n\n/**\n * The theme as the host page has actually resolved it.\n *\n * Reads the COMPUTED values, not the SDK's defaults: `--vio-*` are custom\n * properties any host — a Vev block, a publisher's stylesheet — is free to\n * override, and the whole point is that Qliro matches what the shopper is\n * looking at. Returns undefined outside a browser, or when nothing resolved.\n */\nexport function readVioTheme(): QliroTheme | undefined {\n if (typeof globalThis === 'undefined') return undefined\n const doc = (globalThis as any).document\n const getComputed = (globalThis as any).getComputedStyle\n if (!doc?.documentElement || typeof getComputed !== 'function') return undefined\n let style: any\n try {\n style = getComputed(doc.documentElement)\n } catch {\n return undefined\n }\n const read = (name: string): string | undefined => {\n const value = style?.getPropertyValue?.(name)?.trim()\n return value || undefined\n }\n const theme: QliroTheme = {\n accent: read('--vio-color-accent'),\n surface: read('--vio-color-surface'),\n radiusMd: read('--vio-radius-md'),\n radiusLg: read('--vio-radius-lg'),\n }\n return Object.values(theme).some(Boolean) ? theme : undefined\n}\n\nexport const CREATE_PAYMENT_QLIRO_MUTATION = `\nmutation CreatePaymentQliro($checkoutId: String!, $countryCode: String!, $href: String!, $email: String, $theme: QliroThemeInput) {\n Payment {\n CreatePaymentQliro(checkout_id: $checkoutId, country_code: $countryCode, href: $href, email: $email, theme: $theme) {\n order_id\n status\n html_snippet\n purchase_country\n purchase_currency\n total_price\n }\n }\n}\n`\n\nexport const GET_QLIRO_ORDER_QUERY = `\nquery GetQliroOrder($checkoutId: String!) {\n Payment {\n GetQliroOrder(checkout_id: $checkoutId) {\n order_id\n status\n html_snippet\n purchase_country\n purchase_currency\n total_price\n }\n }\n}\n`\n\nexport interface CreatePaymentQliroVariables extends Record<string, unknown> {\n checkoutId: string\n countryCode: string\n href: string\n email?: string\n theme?: QliroTheme\n}\n\nexport async function createPaymentQliro(\n variables: CreatePaymentQliroVariables | Record<string, unknown>,\n options?: CartQueryOptions,\n): Promise<QliroOrder | null> {\n const json = await executeCartGraphQL(CREATE_PAYMENT_QLIRO_MUTATION, variables, options)\n return (json?.data?.Payment?.CreatePaymentQliro as QliroOrder) ?? null\n}\n\nexport async function getQliroOrder(\n checkoutId: string,\n options?: CartQueryOptions,\n): Promise<QliroOrder | null> {\n const json = await executeCartGraphQL(GET_QLIRO_ORDER_QUERY, { checkoutId }, options)\n return (json?.data?.Payment?.GetQliroOrder as QliroOrder) ?? null\n}\n\n/** Query-less page URL — shopcart appends ?checkout_id=…&payment_processor=QLIRO. */\nexport const qliroCleanHref = kustomCleanHref\n\n/** Script-executing snippet injection — identical technique to Kustom/KCO. */\nexport const renderQliroSnippet = renderKustomSnippet\n","/**\n * Qliro's browser-side protocol (`q1`).\n *\n * The embedded widget publishes a `q1` object on the window and calls a\n * globally-defined `q1Ready` once it has rendered. Everything the customer\n * does inside the iframe — picking a shipping method, changing their address,\n * having a payment declined — is only observable through these listeners.\n * Without them the widget is a black box: the customer can change the\n * shipping and our own summary keeps showing the old total.\n *\n * Two rules from Qliro's documentation shape this module:\n *\n * 1. **Lock before touching the backend.** Otherwise the customer can\n * complete the purchase while the order is still being synchronized.\n * 2. **Compare before unlocking.** Otherwise a second change interrupts the\n * synchronization of the first.\n *\n * We compare on `MerchantUpdateVersion`, the token Qliro echoes back through\n * `onOrderUpdated`, rather than on totals. Totals cannot be the test here: in\n * the modes where Qliro owns the shipping amount our total and Qliro's\n * legitimately differ, and the customer would sit locked out of a checkout\n * that is in fact up to date.\n */\n\nimport { executeCartGraphQL, type CartQueryOptions } from '../../api/cart-queries.js'\n\nexport const SYNC_PAYMENT_QLIRO_MUTATION = `\nmutation SyncPaymentQliro($checkoutId: String!) {\n Payment {\n SyncPaymentQliro(checkout_id: $checkoutId) {\n order_id\n update_version\n total_price\n }\n }\n}\n`\n\nexport interface QliroSyncResult {\n order_id: string\n /** Token to wait for in `onOrderUpdated` before unlocking. */\n update_version: string\n total_price: number\n}\n\nexport async function syncPaymentQliro(\n checkoutId: string,\n options?: CartQueryOptions,\n): Promise<QliroSyncResult | null> {\n const json = await executeCartGraphQL(SYNC_PAYMENT_QLIRO_MUTATION, { checkoutId }, options)\n return (json?.data?.Payment?.SyncPaymentQliro as QliroSyncResult) ?? null\n}\n\n/** The slice of Qliro's `q1` this module uses. */\nexport interface Q1 {\n lock(): void\n unlock(): void\n onCheckoutLoaded(cb: () => void): void\n onOrderUpdated(cb: (order: any) => void): void\n onShippingMethodChanged(cb: (shipping: any) => void): void\n onShippingPriceChanged(cb: (price: number, totalPrice: number) => void): void\n onCustomerInfoChanged(cb: (customer: any) => void): void\n onPaymentMethodChanged(cb: (paymentMethod: any) => void): void\n onPaymentDeclined(cb: (reason: string, message?: string) => void): void\n onSessionExpired(cb: () => void): void\n}\n\nexport type QliroEvent =\n | { type: 'loaded' }\n | { type: 'shipping-changed'; shipping: any }\n | { type: 'shipping-price-changed'; price: number; totalPrice: number }\n | { type: 'customer-changed'; customer: any }\n | { type: 'payment-method-changed'; paymentMethod: any }\n | { type: 'payment-declined'; reason: string; message?: string }\n | { type: 'session-expired' }\n | { type: 'sync-failed'; error: unknown }\n\nexport interface QliroListenerOptions {\n checkoutId: string\n /** Forwarded to the gateway call (sponsor key, endpoint…). */\n queryOptions?: CartQueryOptions\n /** Everything the customer does inside the iframe, for the host UI. */\n onEvent?: (event: QliroEvent) => void\n /**\n * Safety valve. If Qliro never answers a lock with `onOrderUpdated` the\n * customer would be locked out of paying entirely, so the lock is released\n * anyway after this long. Being briefly out of sync is recoverable; a\n * checkout that cannot be completed is not.\n */\n unlockTimeoutMs?: number\n}\n\nconst DEFAULT_UNLOCK_TIMEOUT_MS = 15_000\n\nexport interface QliroController {\n /**\n * Push the current cart onto the Qliro order, holding the widget locked\n * throughout. Resolves once Qliro confirms it is showing this version, or\n * once the safety timeout releases the lock.\n */\n sync(): Promise<QliroSyncResult | null>\n /** Remove the listeners and release any lock still held. */\n destroy(): void\n}\n\n/**\n * Register the listeners and return a handle to synchronize the order.\n *\n * Must be called BEFORE the Qliro snippet is injected: the widget invokes\n * `window.q1Ready` once, as it finishes rendering, and never again.\n */\nexport function installQliroListeners(options: QliroListenerOptions): QliroController {\n const { checkoutId, queryOptions, onEvent } = options\n const unlockTimeoutMs = options.unlockTimeoutMs ?? DEFAULT_UNLOCK_TIMEOUT_MS\n const win = globalThis as any\n\n let q1: Q1 | null = null\n let destroyed = false\n /** `onOrderUpdated` starts a sync, so it is registered on first lock only. */\n let orderUpdatedRegistered = false\n /**\n * The synchronization in flight.\n *\n * Armed BEFORE the server call, not after. Qliro can push `onOrderUpdated`\n * the instant the PUT lands — before our own `await` continuation runs — and\n * an echo that arrives with no waiter registered is an echo lost, leaving\n * the customer locked out until the safety timeout. So echoes seen since\n * the lock are recorded, and matched against the version once we know it.\n */\n let pending: {\n version: string | null\n echoes: Array<string | null>\n resolve: () => void\n timer: any\n } | null = null\n\n const emit = (event: QliroEvent): void => {\n try {\n onEvent?.(event)\n } catch {\n /* a host listener must never break the checkout */\n }\n }\n\n const settle = (): void => {\n if (!pending) return\n clearTimeout(pending.timer)\n const { resolve } = pending\n pending = null\n try {\n q1?.unlock()\n } catch {\n /* the widget may already be gone */\n }\n resolve()\n }\n\n /**\n * Does an echo acknowledge the version we are waiting for?\n *\n * An echo with no version at all counts: orders created before\n * `MerchantUpdateVersion` existed still report updates, and an update is an\n * update. An echo naming a DIFFERENT version does not — that is someone\n * else's synchronization, or an older one of ours.\n */\n const acknowledges = (echo: string | null, version: string | null): boolean => {\n // Our version is not known until the server answers. An echo that arrives\n // before that is kept, not accepted: accepting it would unlock on a stale\n // update that happens to land in the same window.\n if (version === null) return false\n return !echo || echo === version\n }\n\n /** Settle if anything seen since the lock already acknowledged the version. */\n const settleIfAcknowledged = (): void => {\n if (!pending) return\n if (pending.echoes.some((echo) => acknowledges(echo, pending!.version))) {\n settle()\n }\n }\n\n const previousQ1Ready = win.q1Ready\n win.q1Ready = (instance: Q1) => {\n // Another q1Ready may already be installed on the page (a second widget,\n // or the host's own). Chain rather than clobber.\n try {\n previousQ1Ready?.(instance)\n } catch {\n /* not ours to fix */\n }\n if (destroyed) return\n q1 = instance\n\n instance.onCheckoutLoaded(() => emit({ type: 'loaded' }))\n\n // NOT registered here. Qliro's own words: \"onOrderUpdated() — Requires\n // q1.lock() to have been called first. Initiates the order sync process\n // towards the checkout front end.\" Registering it is not passive: it puts\n // the widget INTO a synchronization it then waits to complete. Registered\n // at ready, with no lock and no update coming, the widget sits on a\n // loading panel and polls its orders endpoint forever — observed on a live\n // page as a request storm and a checkout that never advanced.\n //\n // So it is registered lazily, inside `sync()`, right after the lock — the\n // order their documentation actually describes.\n\n // Qliro owns the shipping choice: it is made inside the widget, and Qliro\n // writes the resulting line onto the order itself. These are reported so\n // the host summary can show the same total the customer is looking at —\n // not to overrule the choice.\n instance.onShippingMethodChanged((shipping: any) =>\n emit({ type: 'shipping-changed', shipping }),\n )\n instance.onShippingPriceChanged((price: number, totalPrice: number) =>\n emit({ type: 'shipping-price-changed', price, totalPrice }),\n )\n instance.onCustomerInfoChanged((customer: any) =>\n emit({ type: 'customer-changed', customer }),\n )\n instance.onPaymentMethodChanged((paymentMethod: any) =>\n emit({ type: 'payment-method-changed', paymentMethod }),\n )\n instance.onPaymentDeclined((reason: string, message?: string) =>\n emit({ type: 'payment-declined', reason, message }),\n )\n\n // A checkout session lasts 90 minutes; the order itself lasts 48 hours.\n // Updating the order mints a new session, which is exactly what `sync`\n // does — so the recovery from an expired session is a sync.\n instance.onSessionExpired(() => {\n emit({ type: 'session-expired' })\n void controller.sync()\n })\n }\n\n const controller: QliroController = {\n async sync(): Promise<QliroSyncResult | null> {\n if (destroyed) return null\n // A synchronization already in flight owns the lock; releasing it here\n // would let the customer pay against a half-updated order.\n if (pending) settle()\n\n // Qliro's first rule: lock before touching our server, so the customer\n // cannot complete the purchase mid-synchronization.\n try {\n q1?.lock()\n // Only now, and only once: see the note where the other listeners are\n // registered. Registering this one starts a synchronization, so it\n // must not exist before there is one.\n if (q1 && !orderUpdatedRegistered) {\n orderUpdatedRegistered = true\n q1.onOrderUpdated((order: any) => {\n if (!pending) return\n const echoed: string | null =\n order?.merchantUpdateVersion ?? order?.MerchantUpdateVersion ?? null\n pending.echoes.push(echoed)\n settleIfAcknowledged()\n })\n }\n } catch {\n /* no widget yet — the sync still has to reach the server */\n }\n // Armed before the call so an echo that races the response is caught.\n const settled = new Promise<void>((resolve) => {\n pending = {\n version: null,\n echoes: [],\n resolve,\n timer: setTimeout(settle, unlockTimeoutMs),\n }\n })\n\n let result: QliroSyncResult | null = null\n try {\n result = await syncPaymentQliro(checkoutId, queryOptions)\n } catch (error) {\n emit({ type: 'sync-failed', error })\n settle()\n await settled\n return null\n }\n if (destroyed || !result?.update_version || !q1) {\n settle()\n await settled\n return result\n }\n // Qliro's second rule: unlock only once the orders match.\n if (pending) {\n pending.version = result.update_version\n settleIfAcknowledged()\n }\n await settled\n return result\n },\n\n destroy(): void {\n destroyed = true\n settle()\n if (win.q1Ready) win.q1Ready = previousQ1Ready\n q1 = null\n },\n }\n\n return controller\n}\n","/**\n * Walley (former Collector) — embedded checkout via Vio Commerce.\n *\n * Third embedded provider, same category as Kustom/Qliro: the widget\n * collects address, shipping AND payment by itself.\n *\n * 1. `Payment { CreatePaymentWalley }` initializes the session (sponsor-key\n * authed; the seller's own Walley credentials live server-side, per\n * seller, never here) and returns a SYNTHESIZED html_snippet — Walley's\n * real embed is a `<script data-token>` loader, so shopcart wraps it\n * in the same shape Kustom/Qliro use, and this module reuses their\n * exact script-executing injection.\n * 2. Walley's own script renders the iframe. On completion it dispatches\n * the DOM event `walleyCheckoutPurchaseCompleted` — the PRIMARY success\n * signal, no page reload needed. `redirectPageUri` is registered too\n * (`?checkout_id=…&payment_processor=WALLEY`, same contract as\n * Kustom/Qliro) as a safety net in case the event is missed (tab\n * backgrounded, page reload).\n * 3. Either path re-reads the session (`Payment { GetWalleyOrder }`) BY\n * OWNING CHECKOUT — same as Qliro — and re-renders Walley's own\n * receipt.\n *\n * The Commerce order itself is created server-side by Walley's notification\n * webhook (shopcart /checkout/payment/walley/ok) — the browser never\n * confirms money.\n */\n\nimport { executeCartGraphQL, type CartQueryOptions } from '../../api/cart-queries.js'\nimport { kustomCleanHref, renderKustomSnippet } from './kustom.js'\n\n/** Normalized Walley session (shopcart maps privateId/publicToken/status). */\nexport interface WalleyOrder {\n order_id: string\n /** Walley status: Initialized | CustomerIdentified | CommittedToPurchase | PurchaseCompleted | Aborted. */\n status: string\n html_snippet: string\n public_token?: string\n purchase_country?: string\n purchase_currency?: string\n total_price?: number\n}\n\nexport const CREATE_PAYMENT_WALLEY_MUTATION = `\nmutation CreatePaymentWalley($checkoutId: String!, $countryCode: String!, $href: String!, $email: String) {\n Payment {\n CreatePaymentWalley(checkout_id: $checkoutId, country_code: $countryCode, href: $href, email: $email) {\n order_id\n status\n html_snippet\n public_token\n purchase_country\n purchase_currency\n total_price\n }\n }\n}\n`\n\nexport const GET_WALLEY_ORDER_QUERY = `\nquery GetWalleyOrder($checkoutId: String!) {\n Payment {\n GetWalleyOrder(checkout_id: $checkoutId) {\n order_id\n status\n html_snippet\n public_token\n purchase_country\n purchase_currency\n total_price\n }\n }\n}\n`\n\nexport interface CreatePaymentWalleyVariables extends Record<string, unknown> {\n checkoutId: string\n countryCode: string\n href: string\n email?: string\n}\n\nexport async function createPaymentWalley(\n variables: CreatePaymentWalleyVariables | Record<string, unknown>,\n options?: CartQueryOptions,\n): Promise<WalleyOrder | null> {\n const json = await executeCartGraphQL(CREATE_PAYMENT_WALLEY_MUTATION, variables, options)\n return (json?.data?.Payment?.CreatePaymentWalley as WalleyOrder) ?? null\n}\n\nexport async function getWalleyOrder(\n checkoutId: string,\n options?: CartQueryOptions,\n): Promise<WalleyOrder | null> {\n const json = await executeCartGraphQL(GET_WALLEY_ORDER_QUERY, { checkoutId }, options)\n return (json?.data?.Payment?.GetWalleyOrder as WalleyOrder) ?? null\n}\n\n/** Query-less page URL — shopcart appends ?checkout_id=…&payment_processor=WALLEY. */\nexport const walleyCleanHref = kustomCleanHref\n\n/** Script-executing snippet injection — identical technique to Kustom/Qliro. */\nexport const renderWalleySnippet = renderKustomSnippet\n\n/** Name of the DOM event Walley's own embed script dispatches on success. */\nexport const WALLEY_PURCHASE_COMPLETED_EVENT = 'walleyCheckoutPurchaseCompleted'\n","/**\n * Nexi Checkout (formerly Nets Easy) — embedded checkout via Vio Commerce.\n *\n * Fourth embedded provider, same category as Kustom/Qliro/Walley: the widget\n * collects email, phone, addresses AND payment. Two things set it apart and\n * shape this module:\n *\n * 1. There is no html_snippet. `Payment { CreatePaymentNexi }` creates the\n * payment server-side (the seller's SECRET key never leaves shopcart)\n * and returns the paymentId plus the PUBLIC checkout key; the browser\n * loads Nexi's `checkout.js` and mounts `new Dibs.Checkout({…})` in a\n * LIGHT-DOM container — Nexi refuses a container inside a shadow root\n * or another iframe.\n * 2. Nexi has no shipping picker. The payment is created with\n * `merchantHandlesShippingCost`, so Nexi holds its pay button until we\n * price the address the shopper typed: on `address-changed` the widget\n * is frozen, `Payment { UpdateNexiShipping }` re-prices for that country\n * and pushes the SHIPPING line, and the widget is thawed.\n *\n * Completion arrives as the `payment-completed` event — Nexi neither\n * redirects nor renders a receipt of its own, so the component shows Vio's\n * confirmation. Some methods inside Nexi (Vipps, Swish, MobilePay) leave the\n * page and come back to the SAME url with `?paymentId=…` appended; the\n * pending session is remembered in sessionStorage so the widget can be\n * re-mounted on that paymentId and finish.\n *\n * The Commerce order itself is created server-side by Nexi's webhook\n * (shopcart /checkout/payment/nexi/ok) — the browser never confirms money.\n */\n\nimport { executeCartGraphQL, type CartQueryOptions } from '../../api/cart-queries.js'\nimport { kustomCleanHref } from './kustom.js'\nimport type { QliroTheme } from './qliro.js'\n\n/** Normalized Nexi payment (shopcart maps the Payment API). */\nexport interface NexiOrder {\n /** Nexi paymentId (32 hex). */\n order_id: string\n /** Created | Reserved | Charged | Cancelled | Terminated | Unknown. */\n status: string\n /** Public checkout key for Dibs.Checkout. */\n checkout_key: string\n /** checkout.js of the seller's environment (test or live). */\n checkout_js_url: string\n purchase_country?: string\n purchase_currency?: string\n total_price?: number\n /**\n * Shipping to show next to the widget: the purchase country's rates while\n * no address is known (`reason: AWAITING_ADDRESS`, nothing charged), or what\n * the payment carries once one was priced (a resumed widget does not\n * announce its address again).\n */\n shipping?: NexiShippingUpdate | null\n /** How it was paid (\"Visa\", \"Vipps\"…) — once Nexi has the details. */\n payment_method?: string | null\n /** Last four digits of the card. */\n card_last4?: string | null\n /** Where the receipt goes. */\n email?: string | null\n}\n\nexport interface NexiShippingUpdate {\n ok: boolean\n /**\n * When !ok: NO_SHIPPING — Vio does not ship to that country; or\n * AWAITING_ADDRESS — nothing charged yet, `options` are the purchase\n * country's rates and `shipping_id` the suggested one.\n */\n reason?: string\n order_id: string\n total_price?: number\n shipping_name?: string\n shipping_price?: number\n /** The rate on the payment now. */\n shipping_id?: string\n /**\n * Every rate the shopper may pick for this address, best first. Nexi has\n * no shipping picker of its own, so the checkout shows these.\n */\n options?: NexiShippingOption[]\n /** The address it was priced for (alpha-2 country). */\n country?: string\n postal_code?: string\n /** market — the checkout's country, priced at creation; consumer — the shopper's address. */\n address_source?: 'market' | 'consumer' | null\n /** Whether this call changed the amount on the payment. */\n changed?: boolean | null\n /**\n * Client-side only: set when the amount changed as the shopper pressed pay,\n * so the payment was stopped and the widget reloaded.\n */\n repriced_at_pay?: boolean\n}\n\nexport interface NexiShippingOption {\n id: string\n name: string\n /** Incl. VAT, decimal. */\n price: number\n}\n\nconst NEXI_SHIPPING_FIELDS = `\n ok\n reason\n order_id\n total_price\n shipping_name\n shipping_price\n shipping_id\n options { id name price }\n country\n postal_code\n address_source\n changed`\n\nconst NEXI_ORDER_FIELDS = `\n order_id\n status\n checkout_key\n checkout_js_url\n purchase_country\n purchase_currency\n total_price\n payment_method\n card_last4\n email\n shipping {${NEXI_SHIPPING_FIELDS}\n }`\n\nexport const CREATE_PAYMENT_NEXI_MUTATION = `\nmutation CreatePaymentNexi($checkoutId: String!, $countryCode: String!, $href: String!, $email: String) {\n Payment {\n CreatePaymentNexi(checkout_id: $checkoutId, country_code: $countryCode, href: $href, email: $email) {${NEXI_ORDER_FIELDS}\n }\n }\n}\n`\n\nexport const GET_NEXI_ORDER_QUERY = `\nquery GetNexiOrder($checkoutId: String!) {\n Payment {\n GetNexiOrder(checkout_id: $checkoutId) {${NEXI_ORDER_FIELDS}\n }\n }\n}\n`\n\nexport const UPDATE_NEXI_SHIPPING_MUTATION = `\nmutation UpdateNexiShipping($checkoutId: String!, $countryCode: String!, $postalCode: String, $shippingId: String) {\n Payment {\n UpdateNexiShipping(checkout_id: $checkoutId, country_code: $countryCode, postal_code: $postalCode, shipping_id: $shippingId) {${NEXI_SHIPPING_FIELDS}\n }\n }\n}\n`\n\nexport interface CreatePaymentNexiVariables extends Record<string, unknown> {\n checkoutId: string\n countryCode: string\n href: string\n email?: string\n}\n\nexport interface UpdateNexiShippingVariables extends Record<string, unknown> {\n checkoutId: string\n countryCode: string\n postalCode?: string\n /** A rate from `options` of an earlier answer. */\n shippingId?: string\n}\n\nexport async function createPaymentNexi(\n variables: CreatePaymentNexiVariables | Record<string, unknown>,\n options?: CartQueryOptions,\n): Promise<NexiOrder | null> {\n const json = await executeCartGraphQL(CREATE_PAYMENT_NEXI_MUTATION, variables, options)\n return (json?.data?.Payment?.CreatePaymentNexi as NexiOrder) ?? null\n}\n\nexport async function getNexiOrder(\n checkoutId: string,\n options?: CartQueryOptions,\n): Promise<NexiOrder | null> {\n const json = await executeCartGraphQL(GET_NEXI_ORDER_QUERY, { checkoutId }, options)\n return (json?.data?.Payment?.GetNexiOrder as NexiOrder) ?? null\n}\n\nexport async function updateNexiShipping(\n variables: UpdateNexiShippingVariables | Record<string, unknown>,\n options?: CartQueryOptions,\n): Promise<NexiShippingUpdate | null> {\n const json = await executeCartGraphQL(UPDATE_NEXI_SHIPPING_MUTATION, variables, options)\n return (json?.data?.Payment?.UpdateNexiShipping as NexiShippingUpdate) ?? null\n}\n\n/**\n * Query-less page URL. Nexi validates `checkout.url` against the page that\n * loads checkout.js (protocol + host + path) — same helper the other\n * embedded methods use for their confirmation redirect.\n */\nexport const nexiCleanHref = kustomCleanHref\n\n/** Reserved (or already charged, with auto-capture) = the shopper paid. */\nexport const NEXI_PAID_STATUSES = new Set(['Reserved', 'Charged'])\n\nexport function isNexiPaid(status: string | undefined | null): boolean {\n return NEXI_PAID_STATUSES.has(String(status ?? ''))\n}\n\n/** Nexi's language tags, by the market the checkout runs in. */\nconst NEXI_LANGUAGES: Record<string, string> = {\n NO: 'nb-NO',\n SE: 'sv-SE',\n DK: 'da-DK',\n FI: 'fi-FI',\n DE: 'de-DE',\n NL: 'nl-NL',\n PL: 'pl-PL',\n FR: 'fr-FR',\n ES: 'es-ES',\n IT: 'it-IT',\n EE: 'ee-EE',\n LV: 'lv-LV',\n LT: 'lt-LT',\n SK: 'sk-SK',\n}\n\nexport function nexiLanguageFor(countryCode?: string | null): string {\n return NEXI_LANGUAGES[String(countryCode ?? '').toUpperCase()] ?? 'en-GB'\n}\n\n/**\n * Vio theme tokens → Nexi's `theme` object. Nexi accepts colours as hex\n * strings (primaryColor drives the pay button, panelColor the form panels);\n * `buttonRadius` is passed only as a plain px value. No effect when the\n * seller has set a theme in Nexi's portal styler — Nexi says so itself.\n */\nexport function nexiThemeFrom(theme?: QliroTheme): Record<string, string> | undefined {\n if (!theme) return undefined\n const out: Record<string, string> = {}\n if (theme.accent) out.primaryColor = theme.accent\n if (theme.surface) out.panelColor = theme.surface\n if (theme.radiusMd && /^\\d+(\\.\\d+)?px$/.test(theme.radiusMd)) out.buttonRadius = theme.radiusMd\n return Object.keys(out).length ? out : undefined\n}\n\n/** The subset of Dibs.Checkout this SDK relies on. */\nexport interface NexiCheckoutHandle {\n on(event: string, handler: (payload?: any) => void): void\n send?(event: string, value?: unknown): void\n setLanguage?(language: string): void\n setTheme?(theme: Record<string, string>): void\n freezeCheckout(): void\n thawCheckout(): void\n cleanup(): void\n}\n\nconst scriptLoads = new Map<string, Promise<void>>()\n\n/**\n * Load Nexi's checkout.js once per URL (test and live are different\n * scripts). Resolves when `Dibs.Checkout` is available.\n */\nexport function loadNexiCheckoutJs(url: string): Promise<void> {\n const g = globalThis as any\n if (g.Dibs?.Checkout && g.__vioNexiCheckoutJs === url) return Promise.resolve()\n const inFlight = scriptLoads.get(url)\n if (inFlight) return inFlight\n const load = new Promise<void>((resolve, reject) => {\n const doc = g.document\n if (!doc?.head) {\n reject(new Error('[Nexi] no document to load checkout.js into'))\n return\n }\n const script = doc.createElement('script')\n script.src = url\n script.async = true\n script.onload = () => {\n if (g.Dibs?.Checkout) {\n g.__vioNexiCheckoutJs = url\n resolve()\n } else {\n scriptLoads.delete(url)\n reject(new Error('[Nexi] checkout.js loaded but Dibs.Checkout is missing'))\n }\n }\n script.onerror = () => {\n scriptLoads.delete(url)\n reject(new Error(`[Nexi] could not load ${url}`))\n }\n doc.head.appendChild(script)\n })\n scriptLoads.set(url, load)\n return load\n}\n\nexport interface MountNexiOptions {\n language?: string\n theme?: Record<string, string>\n}\n\n/**\n * Mount the widget. The container must be in the LIGHT DOM and have an id\n * (Nexi resolves it from the document); one is assigned when missing.\n */\nexport async function mountNexi(\n container: HTMLElement,\n order: NexiOrder,\n options: MountNexiOptions = {},\n): Promise<NexiCheckoutHandle> {\n if (!order?.order_id || !order.checkout_key || !order.checkout_js_url) {\n throw new Error('[Nexi] order is missing paymentId, checkout_key or checkout_js_url')\n }\n await loadNexiCheckoutJs(order.checkout_js_url)\n if (!container.id) container.id = 'vio-nexi-checkout-container'\n const Dibs = (globalThis as any).Dibs\n const checkout = new Dibs.Checkout({\n checkoutKey: order.checkout_key,\n paymentId: order.order_id,\n containerId: container.id,\n language: options.language ?? 'en-GB',\n ...(options.theme ? { theme: options.theme } : {}),\n })\n return checkout as NexiCheckoutHandle\n}\n\n/* ── Pending session (survives a third-party redirect inside Nexi) ─────── */\n\nexport const NEXI_PENDING_KEY = 'vio.nexi.pending.v1'\n\n/** Nexi sessions live 48 h; a remembered one older than that is stale. */\nconst NEXI_PENDING_TTL_MS = 48 * 60 * 60 * 1000\n\nexport interface NexiPending {\n checkoutId: string\n sponsorId: number\n paymentId: string\n createdAt: number\n}\n\nfunction storage(): Storage | null {\n try {\n const s = (globalThis as any).sessionStorage as Storage | undefined\n return s ?? null\n } catch {\n return null\n }\n}\n\nexport function rememberNexiPending(pending: Omit<NexiPending, 'createdAt'>): void {\n try {\n storage()?.setItem(NEXI_PENDING_KEY, JSON.stringify({ ...pending, createdAt: Date.now() }))\n } catch {\n /* storage unavailable — the redirect safety net is simply off */\n }\n}\n\nexport function readNexiPending(): NexiPending | null {\n try {\n const raw = storage()?.getItem(NEXI_PENDING_KEY)\n if (!raw) return null\n const p = JSON.parse(raw) as Partial<NexiPending>\n if (!p?.checkoutId || !p?.paymentId) return null\n if (Date.now() - Number(p.createdAt ?? 0) > NEXI_PENDING_TTL_MS) {\n clearNexiPending()\n return null\n }\n return {\n checkoutId: String(p.checkoutId),\n sponsorId: Number(p.sponsorId ?? 0),\n paymentId: String(p.paymentId),\n createdAt: Number(p.createdAt ?? 0),\n }\n } catch {\n return null\n }\n}\n\nexport function clearNexiPending(): void {\n try {\n storage()?.removeItem(NEXI_PENDING_KEY)\n } catch {\n /* noop */\n }\n}\n\n/**\n * The `?paymentId=` Nexi appends when a third-party method (Vipps, Swish,\n * MobilePay) returns the shopper to the checkout page.\n */\nexport function nexiReturnPaymentId(search?: string): string | null {\n try {\n const s = search ?? ((globalThis as any).location?.search as string | undefined) ?? ''\n const id = new URLSearchParams(s).get('paymentId')\n return id && /^[0-9a-f]{32}$/i.test(id) ? id : null\n } catch {\n return null\n }\n}\n","/**\n * Adyen — payment via Vio Commerce, rendered with Adyen's own Drop-in.\n *\n * Adyen is NOT an embedded checkout like Kustom/Qliro/Walley/Nexi: Drop-in\n * lists payment methods (cards, Vipps, Klarna, Swish…) and charges, and that\n * is all. It collects no email, address or shipping, so it belongs with the\n * FORM-FIRST methods (Stripe, Klarna Payments): the shopper fills Vio's form\n * and picks Vio's shipping first, and only then is there a session. Three\n * things shape this module:\n *\n * 1. A session is an immutable PHOTO of the purchase. `Payment {\n * CreatePaymentAdyen }` creates it server-side (the seller's API key\n * never leaves shopcart) from the saved checkout, with the final amount,\n * and returns the session plus the PUBLIC client key. It is never\n * updated: after any change the caller discards it and creates another.\n * At \"Pay\", `ConfirmAdyenPayment` only VERIFIES (lesson 2026-09-17: the\n * amount does not change while the PSP charges).\n * 2. Adyen Web is loaded from Adyen's CDN, version-pinned and with\n * Subresource Integrity — never bundled: it weighs more than this whole\n * SDK, and publisher pages must only pay for it when Adyen is used.\n * Drop-in is real DOM styled by a real stylesheet (not an iframe), so it\n * mounts in the LIGHT DOM and its stylesheet goes in `document.head`.\n * 3. Vipps, Klarna, Trustly and redirect-3DS leave the page and come back\n * to `return_url` with `redirectResult` appended. The return is\n * finalised on the SERVER (`GetAdyenPayment(redirect_result)`), and the\n * return URL names the checkout, so nothing depends on this tab's\n * storage — a shopper sent from an in-app browser to Safari still lands\n * on a confirmation. Nothing is resumed from storage on a plain open,\n * which is how Nexi once opened one cart's payment on another (0.12.2).\n *\n * The page's origin must be in the \"Allowed origins\" of the credential whose\n * client key is used, or Adyen refuses to render — see `AdyenOriginError`.\n *\n * The Commerce order itself is created server-side by Adyen's webhook —\n * the browser never confirms money.\n */\n\nimport { executeCartGraphQL, type CartQueryOptions } from '../../api/cart-queries.js'\n\n/** What `CreatePaymentAdyen` answers: everything Drop-in is created with. */\nexport interface AdyenSession {\n order_id: string\n session_id: string\n session_data: string\n client_key: string\n environment: 'test' | 'live' | string\n country_code: string\n /** As ADYEN names it: Norwegian is `no-NO` (`nb-NO` renders in English). */\n shopper_locale: string\n purchase_currency: string\n /** Minor units — Drop-in's Pay button. */\n amount: number\n /** Major units, shipping included. */\n total_price: number\n shipping_name?: string | null\n shipping_price?: number | null\n expires_at?: string | null\n}\n\nexport type AdyenOutcome = 'authorised' | 'pending' | 'refused' | 'cancelled' | 'error' | 'unknown'\n\n/** Outcome of the session a checkout owns, as Adyen reported it. */\nexport interface AdyenPayment {\n order_id: string\n status: AdyenOutcome | string\n result_code?: string | null\n psp_reference?: string | null\n payment_method?: string | null\n purchase_country?: string | null\n purchase_currency?: string | null\n total_price?: number | null\n shipping_name?: string | null\n shipping_price?: number | null\n email?: string | null\n order_created: boolean\n}\n\nexport interface AdyenConfirm {\n ok: boolean\n /** SESSION_REPLACED | AMOUNT_CHANGED | CART_CHANGED | ALREADY_PAID | NO_SESSION */\n reason?: string | null\n}\n\nconst ADYEN_SESSION_FIELDS = `\n order_id\n session_id\n session_data\n client_key\n environment\n country_code\n shopper_locale\n purchase_currency\n amount\n total_price\n shipping_name\n shipping_price\n expires_at`\n\nconst ADYEN_PAYMENT_FIELDS = `\n order_id\n status\n result_code\n psp_reference\n payment_method\n purchase_country\n purchase_currency\n total_price\n shipping_name\n shipping_price\n email\n order_created`\n\nexport const CREATE_PAYMENT_ADYEN_MUTATION = `\nmutation CreatePaymentAdyen($checkoutId: String!, $returnUrl: String!, $countryCode: String, $channel: String, $email: String, $client: String) {\n Payment {\n CreatePaymentAdyen(checkout_id: $checkoutId, return_url: $returnUrl, country_code: $countryCode, channel: $channel, email: $email, client: $client) {${ADYEN_SESSION_FIELDS}\n }\n }\n}\n`\n\nexport const GET_ADYEN_PAYMENT_QUERY = `\nquery GetAdyenPayment($checkoutId: String!, $sessionResult: String, $redirectResult: String) {\n Payment {\n GetAdyenPayment(checkout_id: $checkoutId, session_result: $sessionResult, redirect_result: $redirectResult) {${ADYEN_PAYMENT_FIELDS}\n }\n }\n}\n`\n\nexport const CONFIRM_ADYEN_PAYMENT_MUTATION = `\nmutation ConfirmAdyenPayment($checkoutId: String!, $sessionId: String!) {\n Payment {\n ConfirmAdyenPayment(checkout_id: $checkoutId, session_id: $sessionId) {\n ok\n reason\n }\n }\n}\n`\n\nexport interface CreatePaymentAdyenVariables extends Record<string, unknown> {\n checkoutId: string\n returnUrl: string\n countryCode?: string\n channel?: 'Web' | 'iOS' | 'Android'\n email?: string\n client?: string\n}\n\nexport async function createPaymentAdyen(\n variables: CreatePaymentAdyenVariables | Record<string, unknown>,\n options?: CartQueryOptions,\n): Promise<AdyenSession | null> {\n const json = await executeCartGraphQL(CREATE_PAYMENT_ADYEN_MUTATION, variables, options)\n return (json?.data?.Payment?.CreatePaymentAdyen as AdyenSession) ?? null\n}\n\nexport async function getAdyenPayment(\n variables: { checkoutId: string; sessionResult?: string; redirectResult?: string },\n options?: CartQueryOptions,\n): Promise<AdyenPayment | null> {\n const json = await executeCartGraphQL(GET_ADYEN_PAYMENT_QUERY, variables, options)\n return (json?.data?.Payment?.GetAdyenPayment as AdyenPayment) ?? null\n}\n\nexport async function confirmAdyenPayment(\n variables: { checkoutId: string; sessionId: string },\n options?: CartQueryOptions,\n): Promise<AdyenConfirm | null> {\n const json = await executeCartGraphQL(CONFIRM_ADYEN_PAYMENT_MUTATION, variables, options)\n return (json?.data?.Payment?.ConfirmAdyenPayment as AdyenConfirm) ?? null\n}\n\n/* ── Adyen Web from Adyen's CDN, pinned + Subresource Integrity ────────── */\n\n/**\n * The Adyen Web release this SDK was tested against. Bumping it is a\n * deliberate change: the two hashes below are the SRI values Adyen publishes\n * in the release notes of THAT version (\"Updating to this version\"), and the\n * browser refuses a file that does not match them.\n */\nexport const ADYEN_WEB_VERSION = '6.45.0'\nconst ADYEN_WEB_JS_SRI = 'sha384-7KW64UN6T0xZoacpNpRg2KVxMMVwfqwUNTDmalkE1roPBtjOpWe8JuJoUU7OCMvF'\nconst ADYEN_WEB_CSS_SRI = 'sha384-A4V58Hp1NTZmMvKn29pBh7249tw4TmfdL2szCtpKvaYfR/ARbXlXRYU20SLp/1VW'\n\n/** Adyen serves the library per environment/region; only these are known. */\nconst ADYEN_ENVIRONMENTS = ['test', 'live', 'live-us', 'live-au', 'live-apse', 'live-in']\n\nexport function adyenAssetUrls(environment: string): { js: string; css: string } {\n const env = ADYEN_ENVIRONMENTS.includes(environment) ? environment : 'test'\n const base = `https://checkoutshopper-${env}.cdn.adyen.com/checkoutshopper/sdk/${ADYEN_WEB_VERSION}`\n return { js: `${base}/adyen.js`, css: `${base}/adyen.css` }\n}\n\nconst assetLoads = new Map<string, Promise<void>>()\n\n/**\n * Load Adyen Web (script + stylesheet) once per environment. Resolves when\n * `window.AdyenWeb` exposes AdyenCheckout and Dropin.\n */\nexport function loadAdyenWeb(environment: string): Promise<void> {\n const g = globalThis as any\n const { js, css } = adyenAssetUrls(environment)\n if (g.AdyenWeb?.AdyenCheckout && g.__vioAdyenWeb === js) return Promise.resolve()\n const inFlight = assetLoads.get(js)\n if (inFlight) return inFlight\n const load = new Promise<void>((resolve, reject) => {\n const doc = g.document\n if (!doc?.head) {\n reject(new Error('[Adyen] no document to load Adyen Web into'))\n return\n }\n if (!doc.head.querySelector(`link[data-vio-adyen=\"${ADYEN_WEB_VERSION}\"]`)) {\n const link = doc.createElement('link')\n link.rel = 'stylesheet'\n link.href = css\n link.integrity = ADYEN_WEB_CSS_SRI\n link.crossOrigin = 'anonymous'\n link.setAttribute('data-vio-adyen', ADYEN_WEB_VERSION)\n doc.head.appendChild(link)\n }\n const script = doc.createElement('script')\n script.src = js\n script.async = true\n script.integrity = ADYEN_WEB_JS_SRI\n script.crossOrigin = 'anonymous'\n script.onload = () => {\n if (g.AdyenWeb?.AdyenCheckout && g.AdyenWeb?.Dropin) {\n g.__vioAdyenWeb = js\n resolve()\n } else {\n reject(new Error('[Adyen] adyen.js loaded but AdyenWeb.AdyenCheckout is missing'))\n }\n }\n script.onerror = () => {\n reject(new Error(`[Adyen] could not load ${js}`))\n }\n doc.head.appendChild(script)\n }).finally(() => {\n // Only IN-FLIGHT loads are remembered: once settled, the check at the top\n // (AdyenWeb present for this URL) answers, and a failure can be retried.\n assetLoads.delete(js)\n })\n assetLoads.set(js, load)\n return load\n}\n\n/* ── Mount ─────────────────────────────────────────────────────────────── */\n\n/**\n * The page is not an allowed origin of the client key. Adyen's own message\n * (\"Invalid client key or unknown origin\") reads like a bad key; the cause\n * is a missing entry under Allowed origins, and this says which.\n */\nexport class AdyenOriginError extends Error {\n constructor(public readonly origin: string) {\n super(\n `[Adyen] ${origin} is not an allowed origin of this Adyen client key — add it under Developers > API credentials > Client settings > Allowed origins.`,\n )\n this.name = 'AdyenOriginError'\n }\n}\n\nconst looksLikeOriginProblem = (err: unknown): boolean =>\n /origin|client\\s?key|14_0381|401|403/i.test(String((err as any)?.message ?? err ?? ''))\n\nexport interface AdyenResult {\n resultCode?: string\n sessionResult?: string\n}\n\nexport interface MountAdyenHandlers {\n /**\n * \"Pay\" was pressed. Resolve `true` to let Adyen charge, `false` to stop:\n * the session no longer pays for the checkout and must be replaced.\n */\n onBeforePay(): Promise<boolean>\n onCompleted(result: AdyenResult): void\n /** Refused, cancelled or errored — the shopper may try again. */\n onFailed(result: AdyenResult): void\n onError?(error: unknown): void\n}\n\nexport interface AdyenDropinHandle {\n sessionId: string\n unmount(): void\n}\n\nexport interface MountAdyenOptions {\n /** Vio tokens for the Pay button and the corners — scoped to the container. */\n theme?: { accent?: string; radiusMd?: string }\n}\n\n/**\n * Mount Drop-in on a session. The container must be in the LIGHT DOM:\n * Drop-in is styled by the stylesheet in `document.head`, which does not\n * reach into a shadow root.\n */\nexport async function mountAdyen(\n container: HTMLElement,\n session: AdyenSession,\n handlers: MountAdyenHandlers,\n options: MountAdyenOptions = {},\n): Promise<AdyenDropinHandle> {\n if (!session?.session_id || !session.session_data || !session.client_key) {\n throw new Error('[Adyen] session is missing session_id, session_data or client_key')\n }\n await loadAdyenWeb(session.environment)\n const { AdyenCheckout, Dropin } = (globalThis as any).AdyenWeb\n\n if (options.theme?.accent) {\n container.style.setProperty('--adyen-sdk-color-background-always-dark', options.theme.accent)\n }\n if (options.theme?.radiusMd && /^\\d+(\\.\\d+)?px$/.test(options.theme.radiusMd)) {\n container.style.setProperty('--adyen-sdk-border-radius-m', options.theme.radiusMd)\n }\n\n // A shopper can submit twice (Enter + click): the second one is refused\n // while the first is in flight — Adyen's own best practice.\n let paying = false\n let checkout: any\n try {\n checkout = await AdyenCheckout({\n session: { id: session.session_id, sessionData: session.session_data },\n clientKey: session.client_key,\n environment: session.environment,\n locale: session.shopper_locale,\n countryCode: session.country_code,\n amount: { value: session.amount, currency: session.purchase_currency },\n beforeSubmit: async (data: unknown, _component: unknown, actions: any) => {\n if (paying) {\n actions.reject()\n return\n }\n paying = true\n let proceed = false\n try {\n proceed = await handlers.onBeforePay()\n } catch {\n proceed = false\n }\n if (proceed) {\n actions.resolve(data)\n } else {\n paying = false\n actions.reject()\n }\n },\n onPaymentCompleted: (result: AdyenResult) => {\n paying = false\n handlers.onCompleted(result ?? {})\n },\n onPaymentFailed: (result: AdyenResult) => {\n paying = false\n handlers.onFailed(result ?? {})\n },\n onError: (error: unknown) => {\n paying = false\n handlers.onError?.(error)\n },\n })\n } catch (err) {\n // Creating the checkout is when Adyen checks client key + origin.\n if (looksLikeOriginProblem(err)) {\n throw new AdyenOriginError((globalThis as any).location?.origin ?? 'this page')\n }\n throw err\n }\n\n const dropin = new Dropin(checkout, {\n // Vio's own confirmation follows; Adyen's success animation would sit\n // between the payment and it.\n disableFinalAnimation: true,\n instantPaymentTypes: ['applepay', 'googlepay'],\n }).mount(container)\n\n return {\n sessionId: session.session_id,\n unmount: () => {\n try {\n dropin.unmount()\n } catch {\n /* already gone */\n }\n },\n }\n}\n\n/* ── Return from a redirect (Vipps, Klarna, Trustly, redirect-3DS) ─────── */\n\n/** `vio_method` value that marks OUR return URL as an Adyen one. */\nexport const ADYEN_RETURN_METHOD = 'adyen'\n\n/**\n * What Adyen appended to the return URL. Only a real return carries\n * `redirectResult`; without it there is nothing to finalise.\n */\nexport function adyenReturnParams(\n search: string = (globalThis as any)?.location?.search ?? '',\n): { redirectResult: string; sessionId: string | null } | null {\n try {\n const params = new URLSearchParams(search)\n const redirectResult = params.get('redirectResult')\n if (!redirectResult) return null\n return { redirectResult, sessionId: params.get('sessionId') }\n } catch {\n return null\n }\n}\n\n/** Every query parameter of an Adyen return — ours and Adyen's. */\nexport const ADYEN_RETURN_QUERY_KEYS = [\n 'vio_payment',\n 'vio_method',\n 'vio_sponsor',\n 'checkout_id',\n 'sessionId',\n 'redirectResult',\n]\n\n/** Adyen's outcome → the three answers the checkout's return flow knows. */\nexport function adyenReturnOutcome(payment: AdyenPayment | null): 'paid' | 'failed' | 'pending' {\n switch (payment?.status) {\n case 'authorised':\n return 'paid'\n case 'refused':\n case 'cancelled':\n case 'error':\n return 'failed'\n // pending (Swish, Trustly…) and anything unrecognised: the webhook\n // decides, and offering to pay again is the one thing not to do.\n default:\n return 'pending'\n }\n}\n","/**\n * CheckoutManager — orchestrates the checkout flow.\n *\n * Stable contract: open / setAddress / selectPaymentMethod / close.\n * Per-vendor payment integrations plug into the corresponding method:\n * - Apple Pay → `startApplePay()` (Stripe Payment Request, this iteration)\n * - Klarna / Vipps / Card → land in subsequent iterations\n *\n * Dispatches `change` (state changes) and `payment-select` (user picked\n * a method) and `payment-complete` (vendor sheet completed successfully).\n */\n\nimport type { CartLineItem } from '../cart/types.js'\nimport type { CartManager } from '../cart/cart-manager.js'\nimport {\n checkoutSponsorOf,\n rememberCheckoutSponsor,\n rememberedCheckoutSponsor,\n type CheckoutSponsor,\n type SponsorIdentity,\n} from '../sponsor-identity.js'\nimport { Configuration } from '../configuration.js'\nimport {\n createStripeIntent,\n mountStripeElement,\n type StripeElementHandle,\n type StripeIntent,\n} from './payments/stripe-embedded.js'\nimport {\n checkApplePayAvailability,\n prepareApplePay,\n preloadStripeJs,\n showApplePaySheet,\n type ApplePayResult,\n} from './payments/apple-pay.js'\nimport {\n cleanUrlParams,\n isKlarnaAvailable,\n listenForKlarnaCompletion,\n mountKlarnaExpressButton,\n readKlarnaTokenFromUrl,\n type KlarnaAuthorizeResult,\n type KlarnaButtonHandle,\n type KlarnaLineItem,\n type KlarnaPaymentRequestData,\n} from './payments/klarna.js'\nimport {\n createKlarnaPaymentsWidget,\n isKlarnaPaymentsAvailable,\n type KlarnaPaymentsCategory,\n} from './payments/klarna-payments.js'\nimport {\n createPaymentVipps as gqlCreatePaymentVipps,\n getVippsStatus as gqlGetVippsStatus,\n} from './payments/vipps.js'\nimport {\n createPaymentKustom as gqlCreatePaymentKustom,\n getKustomOrder as gqlGetKustomOrder,\n syncPaymentKustom as gqlSyncPaymentKustom,\n installKustomListeners,\n suspendKustom,\n resumeKustom,\n type KustomListenerHandlers,\n kustomCleanHref,\n renderKustomSnippet,\n type KustomOrder,\n} from './payments/kustom.js'\nimport {\n createPaymentQliro as gqlCreatePaymentQliro,\n readVioTheme,\n getQliroOrder as gqlGetQliroOrder,\n type QliroOrder,\n} from './payments/qliro.js'\nimport {\n installQliroListeners,\n type QliroController,\n type QliroEvent,\n type QliroSyncResult,\n} from './payments/qliro-sync.js'\nimport {\n createPaymentWalley as gqlCreatePaymentWalley,\n getWalleyOrder as gqlGetWalleyOrder,\n WALLEY_PURCHASE_COMPLETED_EVENT,\n type WalleyOrder,\n} from './payments/walley.js'\nimport {\n createPaymentNexi as gqlCreatePaymentNexi,\n getNexiOrder as gqlGetNexiOrder,\n updateNexiShipping as gqlUpdateNexiShipping,\n mountNexi,\n nexiLanguageFor,\n nexiThemeFrom,\n isNexiPaid,\n rememberNexiPending,\n readNexiPending,\n clearNexiPending,\n type NexiOrder,\n type NexiCheckoutHandle,\n type NexiShippingUpdate,\n} from './payments/nexi.js'\nimport {\n createPaymentAdyen as gqlCreatePaymentAdyen,\n getAdyenPayment as gqlGetAdyenPayment,\n confirmAdyenPayment as gqlConfirmAdyenPayment,\n mountAdyen,\n ADYEN_RETURN_METHOD,\n ADYEN_RETURN_QUERY_KEYS,\n type AdyenSession,\n type AdyenPayment,\n type AdyenResult,\n type AdyenDropinHandle,\n} from './payments/adyen.js'\nimport { SDK_VERSION } from '../version.js'\nimport { normalizeBuyerRef } from '../buyer-ref.js'\nimport {\n BUYER_REF_FIELD,\n withBuyerRef,\n getCheckoutReference as gqlGetCheckoutReference,\n type CheckoutReference,\n confirmPaymentApplePay as gqlConfirmPaymentApplePay,\n createCheckout as gqlCreateCheckout,\n createPaymentApplePay as gqlCreatePaymentApplePay,\n createPaymentStripe as gqlCreatePaymentStripe,\n executeCartGraphQL,\n getAvailablePaymentMethods as gqlGetAvailablePaymentMethods,\n getCartGraphQLOptions,\n getCheckout as gqlGetCheckout,\n getLineItemsBySupplier as gqlGetLineItemsBySupplier,\n updateCheckout as gqlUpdateCheckout,\n updateShippingsBySupplier as gqlUpdateShippingsBySupplier,\n type CartQueryOptions,\n} from '../api/cart-queries.js'\nimport { getGlobalCountryCode, getGlobalCurrency, getGlobalLocale } from '../types.js'\n\n/**\n * Best-effort human-readable string for an unknown thrown/rejected value.\n * Klarna's SDK rejects with plain objects, so `String(err)` would collapse to\n * \"[object Object]\"; we pull a known message field or JSON-serialise so the\n * real reason stays visible.\n */\nfunction describeError(err: unknown): string {\n if (err instanceof Error) return err.message\n if (typeof err === 'string') return err\n if (err && typeof err === 'object') {\n const o = err as Record<string, unknown>\n for (const k of ['message', 'error', 'reason', 'description']) {\n if (typeof o[k] === 'string' && o[k]) return o[k] as string\n }\n try {\n return JSON.stringify(err)\n } catch {\n return String(err)\n }\n }\n return String(err)\n}\n\n/** sessionStorage key for a pending Klarna purchase (survives redirect). */\nconst KLARNA_PENDING_KEY = 'vio.klarna.pending.v1'\n\ninterface KlarnaPendingContext {\n sponsorId: number\n currency: string\n orderAmount: number\n orderLines: Array<{\n name: string\n quantity: number\n unit_price: number\n total_amount: number\n reference?: string\n /** Klarna line type, e.g. \"shipping_fee\". */\n type?: string\n }>\n /** Backend checkout id (native GraphQL flow). */\n checkoutId?: string\n /** Klarna Payments session id (native GraphQL flow). */\n sessionId?: string\n /** Klarna Payments client token (native GraphQL flow). */\n clientToken?: string\n}\n\n/** A shipping option offered in the checkout. `price` in minor units (øre). */\nexport interface KlarnaShippingOption {\n id: string\n method: string\n description: string\n price: number\n tax_amount: number\n tax_rate: number\n preselected: boolean\n /** Backend supplier the option belongs to (server-side shippings). */\n supplierId?: string\n /** Display name from the backend (mirror of `method`). */\n name?: string\n country_code?: string\n /** Price in MAJOR units, as delivered by the backend. */\n priceMajor?: number\n currency?: string\n}\n\n/**\n * Shipping options offered for express purchases. Amounts in minor units (øre).\n * The chosen one is added to the order total + as a `shipping_fee` line so the\n * Klarna order reconciles. (Klarna Payments doesn't render a shipping picker —\n * KCO/KSA would, but the account isn't provisioned — so the picker is ours.)\n */\nexport const KLARNA_SHIPPING_OPTIONS: KlarnaShippingOption[] = [\n {\n id: 'standard',\n method: 'Standard',\n description: '3–5 virkedager',\n price: 4900,\n tax_amount: 0,\n tax_rate: 0,\n preselected: true,\n },\n {\n id: 'express',\n method: 'Express',\n description: '1–2 virkedager',\n price: 9900,\n tax_amount: 0,\n tax_rate: 0,\n preselected: false,\n },\n]\nimport type { CheckoutAddress, CheckoutState, PaymentMethod } from './types.js'\nimport type { CheckoutAttributionWire } from './attribution.js'\n\n// MARK: - Klarna native (Vio Commerce GraphQL Payment mutations)\n\nconst CREATE_PAYMENT_KLARNA_NATIVE_MUTATION = `\nmutation CreatePaymentKlarnaNative($checkoutId: String!, $countryCode: String, $currency: String, $locale: String, $returnUrl: String, $intent: String, $customer: KlarnaNativeCustomerInput, $billingAddress: KlarnaNativeAddressInput, $shippingAddress: KlarnaNativeAddressInput, $autoCapture: Boolean) {\n Payment {\n CreatePaymentKlarnaNative(checkout_id: $checkoutId, country_code: $countryCode, currency: $currency, locale: $locale, return_url: $returnUrl, intent: $intent, customer: $customer, billing_address: $billingAddress, shipping_address: $shippingAddress, auto_capture: $autoCapture) {\n client_token\n session_id\n purchase_country\n purchase_currency\n cart_id\n checkout_id\n payment_method_categories {\n identifier\n name\n asset_urls {\n descriptive\n standard\n }\n }\n }\n }\n}\n`\n\n/** With `buyer_ref` (new on the gateway, see cart-queries `withBuyerRef`) or without it, for a gateway that predates it. */\nconst confirmPaymentKlarnaNativeMutation = (withRef: boolean) => `\nmutation ConfirmPaymentKlarnaNative($checkoutId: String!, $authorizationToken: String!, $autoCapture: Boolean, $billingAddress: KlarnaNativeAddressInput, $shippingAddress: KlarnaNativeAddressInput, $customer: KlarnaNativeCustomerInput) {\n Payment {\n ConfirmPaymentKlarnaNative(checkout_id: $checkoutId, authorization_token: $authorizationToken, auto_capture: $autoCapture, billing_address: $billingAddress, shipping_address: $shippingAddress, customer: $customer) {\n order_id\n checkout_id\n fraud_status${withRef ? `\\n ${BUYER_REF_FIELD}` : ''}\n order {\n order_id\n status\n purchase_country\n purchase_currency\n locale\n billing_address {\n given_name\n family_name\n email\n street_address\n postal_code\n city\n country\n }\n shipping_address {\n given_name\n family_name\n email\n street_address\n postal_code\n city\n country\n }\n order_amount\n order_tax_amount\n total_line_items_price\n order_lines {\n type\n name\n quantity\n unit_price\n tax_rate\n total_amount\n total_discount_amount\n total_tax_amount\n merchant_data\n }\n merchant_urls {\n terms\n checkout\n confirmation\n push\n }\n html_snippet\n started_at\n last_modified_at\n options {\n allow_separate_shipping_address\n date_of_birth_mandatory\n require_validate_callback_success\n phone_mandatory\n auto_capture\n }\n shipping_options {\n id\n name\n price\n tax_amount\n tax_rate\n preselected\n }\n merchant_data\n selected_shipping_option {\n id\n name\n price\n tax_amount\n tax_rate\n preselected\n }\n }\n }\n }\n}\n`\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nfunction buildKlarnaCustomer(address: any): Record<string, unknown> | null {\n if (!address) return null\n return {\n dob: address.dob || address.date_of_birth || null,\n email: address.email || null,\n organization_registration_id:\n address.organization_registration_id || address.org_id || null,\n phone: address.phone || address.telephone || null,\n type: address.type || 'person',\n }\n}\n\nfunction buildKlarnaAddress(address: any): Record<string, unknown> | null {\n if (!address) return null\n return {\n city: address.city || null,\n country: address.country || address.countryCode || getGlobalCountryCode(),\n email: address.email || null,\n family_name:\n address.familyName || address.family_name || address.last_name || address.lastName || null,\n given_name:\n address.givenName || address.given_name || address.first_name || address.firstName || null,\n phone: address.phone || null,\n postal_code: address.postalCode || address.postal_code || address.zip || null,\n region: address.region || address.state || null,\n street_address:\n address.streetAddress ||\n address.street_address ||\n address.address1 ||\n address.street ||\n address.address || // CheckoutAddress uses plain `address` for the street\n null,\n // street_address2 intentionally omitted — the KlarnaNativeAddressInput\n // backend type rejects it.\n }\n}\n\n/** Map any address-ish object to the backend checkout address input shape. */\nfunction buildCheckoutAddress(address: any): Record<string, unknown> | null {\n if (!address) return null\n const firstName =\n address.firstName || address.first_name || address.givenName || address.given_name || null\n const lastName =\n address.lastName || address.last_name || address.familyName || address.family_name || null\n const address1 =\n address.address || address.address1 || address.street || address.street_address || null\n const city = address.city || null\n const zip = address.postalCode || address.postal_code || address.zip || null\n const country_code = address.countryCode || address.country_code || address.country || getGlobalCountryCode()\n\n if (!firstName && !lastName && !address1 && !city && !zip) return null\n\n return {\n first_name: firstName,\n last_name: lastName,\n address1: address1,\n city: city,\n zip: zip,\n country_code: country_code,\n }\n}\n\n/**\n * Klarna/Stripe/Vipps require an https return_url — normalise whatever the\n * page has, optionally appending query params (used to detect the redirect\n * return and show the confirmation).\n */\n/**\n * Where Adyen sends the shopper back after a redirect: THIS page, naming the\n * checkout, so the return can be finalised from a browser that never saw the\n * session. Adyen appends `sessionId` and `redirectResult` itself, so a\n * leftover pair from an earlier return is dropped first; a page URL too long\n * for Adyen (1024) loses its own query rather than the payment.\n */\nfunction adyenReturnUrl(params: Record<string, unknown>): string {\n let page: URL | null = null\n if (typeof window !== 'undefined' && window.location?.href) {\n try {\n page = new URL(window.location.href)\n ADYEN_RETURN_QUERY_KEYS.forEach((k) => page?.searchParams.delete(k))\n } catch {\n page = null\n }\n }\n // Adyen's TEST environment accepts a plain-http localhost return; the\n // shared helper would turn it into an https URL nothing serves.\n const local = page?.protocol === 'http:' && /^(localhost|127\\.0\\.0\\.1)$/.test(page.hostname)\n const build = (base: URL | null): string => {\n if (base && local) {\n const url = new URL(base.toString())\n Object.entries(params).forEach(([k, v]) => url.searchParams.set(k, String(v)))\n return url.toString()\n }\n return resolveHttpsReturnUrl(base ? base.toString() : null, params)\n }\n const full = build(page)\n if (full.length <= 1024 || !page) return full\n const bare = new URL(page.toString())\n bare.search = ''\n return build(bare)\n}\n\nfunction resolveHttpsReturnUrl(\n overrideUrl?: string | null,\n params: Record<string, unknown> | null = null,\n): string {\n let url = overrideUrl ?? undefined\n if (!url && typeof window !== 'undefined' && window.location) {\n url = window.location.href\n }\n if (!url || typeof url !== 'string' || url.startsWith('about:') || url.startsWith('file:')) {\n url = 'https://vev.design/checkout/confirmation'\n }\n if (url.startsWith('http://')) {\n url = 'https://' + url.slice(7)\n } else if (!url.startsWith('https://')) {\n url = 'https://' + url.replace(/^[a-zA-Z]+:\\/\\//, '')\n }\n\n if (params && typeof params === 'object') {\n try {\n const parsed = new URL(url)\n Object.keys(params).forEach((k) => {\n if (params[k] !== undefined && params[k] !== null) {\n parsed.searchParams.set(k, String(params[k]))\n }\n })\n return parsed.toString()\n } catch {\n const queryStr = Object.keys(params)\n .filter((k) => params[k] !== undefined && params[k] !== null)\n .map((k) => `${encodeURIComponent(k)}=${encodeURIComponent(String(params[k]))}`)\n .join('&')\n if (queryStr) {\n url += (url.includes('?') ? '&' : '?') + queryStr\n }\n }\n }\n\n return url\n}\n\n/** Execute a Payment.* mutation with the sponsor's commerce key. */\nasync function executeKlarnaGraphQL(\n query: string,\n variables: Record<string, unknown>,\n sponsorId?: number,\n): Promise<any> {\n return executeCartGraphQL(query, variables, await getCartGraphQLOptions(sponsorId))\n}\n\n/* eslint-enable @typescript-eslint/no-explicit-any */\n\nexport interface CheckoutChangeDetail {\n state: CheckoutState | null\n}\n\nexport interface PaymentSelectDetail {\n method: PaymentMethod\n state: CheckoutState\n}\n\nexport interface PaymentCompleteDetail {\n method: PaymentMethod\n state: CheckoutState\n result: ApplePayResult | KlarnaAuthorizeResult | unknown\n}\n\nexport interface PaymentErrorDetail {\n method: PaymentMethod\n error: string\n}\n\n/** Handle for the Klarna Payments (classic widget) flow. */\nexport interface KlarnaPaymentsHandle {\n /** Categories offered by the session (pay_now / pay_later / pay_over_time). */\n categories: KlarnaPaymentsCategory[]\n /** Shipping options in effect (backend per-supplier, or the static fallback). */\n shippings: KlarnaShippingOption[]\n /** Currently selected category. */\n readonly selected: string\n /** (Re)load the widget for a category. */\n load(category?: string): Promise<{ showForm: boolean }>\n /** Authorize a category (defaults to whatever's currently selected) and,\n * on approval, create the order. */\n authorize(category?: string): Promise<void>\n /** Tear down the mounted widget. */\n unmount(): void\n}\n\n/**\n * What the facade lends the manager. `orderAttribution` answers the\n * attribution of the order about to be created for a sponsor's cart\n * (`Vio.orderAttribution`, ADR-0035 phase B) — the surface, the page's\n * campaign, the page and the entry; sent as `attribution` on `CreateCheckout`\n * and on the `UpdateCheckout` before paying. Optional: without it (a manager\n * built apart from the facade) nothing is sent and nothing changes.\n */\nexport interface CheckoutManagerDeps {\n orderAttribution?: (\n sponsorId: number,\n ) => Promise<CheckoutAttributionWire | undefined> | CheckoutAttributionWire | undefined\n /**\n * Who a sponsor is (`Vio.sponsorIdentity`): remembered per checkout when one\n * is created, and answered with `getOrderReference`. Optional: without it\n * the memory keeps only whose checkout it is, and the cart's name.\n */\n sponsorIdentity?: (\n sponsorId: number | undefined,\n opts?: { checkoutId?: string | null },\n ) => SponsorIdentity | null\n}\n\n/** What `getOrderReference` answers: the checkout's reference plus, when it can be named, its sponsor. */\nexport type OrderReference = CheckoutReference & {\n /** The sponsor the order is with — the checkout's, by the `Vio.sponsorIdentity` rule. */\n sponsor?: CheckoutSponsor\n}\n\nexport class CheckoutManager extends EventTarget {\n private currentStateValue: CheckoutState | null = null\n /**\n * Every write of the state goes through here: a state that names its\n * backend checkout is remembered with its sponsor (see\n * `rememberSponsorOfCheckout`), whatever path created the checkout.\n */\n private get state(): CheckoutState | null {\n return this.currentStateValue\n }\n private set state(next: CheckoutState | null) {\n this.currentStateValue = next\n if (next?.checkoutId && next.sponsorId) this.rememberSponsorOfCheckout(next.checkoutId, next.sponsorId)\n }\n /** The last checkout + identity written to the memory — the state is set on every keystroke of the form. */\n private lastRememberedSponsor = ''\n /** Counts `open()` calls — see CheckoutState.session. */\n private sessionSeq = 0\n private applePayAvailableCache: boolean | null = null\n\n /** Gateway hints learned from CreatePaymentApplePay (per session). The\n * backend's gateway_merchant_id may be a publishable key (pk_…) or a Stripe\n * Connect account (acct_…) — stored defensively by prefix. */\n private applePayPublishableKey: string | null = null\n private applePayConnectedAccount: string | null = null\n /** Stripe Connect account of the channel, from its Stripe config. */\n private stripeConnectAccount: string | null = null\n private klarnaAvailableCache: boolean | null = null\n /** Live q1 listeners while a Qliro widget is mounted. */\n private qliroController: QliroController | null = null\n /** Live Dibs.Checkout handle while a Nexi widget is mounted. */\n private nexiHandle: NexiCheckoutHandle | null = null\n /** Live Drop-in while an Adyen session is mounted. */\n private adyenHandle: AdyenDropinHandle | null = null\n private stripeHandle: StripeElementHandle | null = null\n /**\n * The rate the shopper wants. Before an address it is only remembered (the\n * suggested one, or their pick); every re-pricing asks for it, and the\n * backend charges it if it reaches the address.\n */\n private nexiPreferredShipping: string | null = null\n /** The rates offered before an address was typed. */\n private nexiShippingPreview: NexiShippingUpdate | null = null\n /** What the last `address-changed` was priced with — a picked rate re-prices the same address. */\n private nexiShippingContext: {\n handle: NexiCheckoutHandle\n checkoutId: string\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n address: any\n /** The address is the shopper's (from the widget or Nexi), not the market default. */\n fromShopper?: boolean\n opts: CartQueryOptions\n onShipping?: (result: NexiShippingUpdate | null, error?: unknown) => void\n } | null = null\n private klarnaOrderInFlight = false\n /** Last backend shippings fetched (per-supplier), for UI reuse. */\n private lastFetchedShippings: KlarnaShippingOption[] = []\n /** See `lastShippingsResolved`. */\n private shippingsResolved = false\n /** Per-sponsor payment methods cache + in-flight dedupe. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private paymentMethodsCache = new Map<number, any>()\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private paymentMethodsPromises = new Map<number, Promise<any>>()\n\n constructor(\n private readonly cartManager: CartManager,\n private readonly deps: CheckoutManagerDeps = {},\n ) {\n super()\n // Warm Stripe.js early: Apple Pay's sheet must open synchronously inside\n // the tap gesture, so the library can't be lazy-loaded at click time.\n preloadStripeJs()\n }\n\n open(sponsorId: number): CheckoutState {\n const cart = this.cartManager.getCart(sponsorId)\n if (!cart || cart.items.length === 0) {\n throw new Error(`[VioCheckout] sponsor ${sponsorId} has no cart items`)\n }\n this.state = {\n sponsorId,\n session: ++this.sessionSeq,\n subtotal: this.cartManager.subtotalForSponsor(sponsorId),\n // Page-level currency wins over whatever the persisted cart carries —\n // the host may have switched currency since the cart was created.\n currency: getGlobalCurrency(),\n }\n this.emit()\n return this.state\n }\n\n close(): void {\n this.state = null\n this.applePayAvailableCache = null\n this.klarnaAvailableCache = null\n this.emit()\n }\n\n // MARK: - Backend checkout (Vio Commerce GraphQL)\n\n /* eslint-disable @typescript-eslint/no-explicit-any */\n\n /**\n * The attribution of the order this sponsor's cart is about to become\n * (ADR-0035 phase B), through the facade; `undefined` when there is none\n * to give or it fails — attribution never costs a checkout.\n */\n private async attributionFor(sponsorId: number | undefined): Promise<CheckoutAttributionWire | undefined> {\n if (!sponsorId || typeof this.deps.orderAttribution !== 'function') return undefined\n try {\n return (await this.deps.orderAttribution(sponsorId)) ?? undefined\n } catch {\n return undefined\n }\n }\n\n /** Create the backend checkout for the sponsor's cart (auto-accepts terms); born attributed when the facade knows the attribution. */\n async createCheckout(sponsorId: number): Promise<any> {\n // A line changed a moment ago may still be syncing — the checkout must be\n // built on the cart that change produced, not on the one before it.\n await this.cartManager.waitForCartMutations(sponsorId)\n const cart = this.cartManager.getCart(sponsorId)\n let cartId = cart?.cartId\n if (!cartId) {\n cartId = await this.cartManager.ensureCartId(sponsorId, cart?.currency)\n if (!cartId) {\n throw new Error(`[CheckoutManager] Failed to obtain cart_id for sponsor ${sponsorId}`)\n }\n }\n const opts = await getCartGraphQLOptions(sponsorId)\n const attribution = await this.attributionFor(sponsorId)\n const checkout = attribution\n ? await gqlCreateCheckout(cartId, opts, { attribution })\n : await gqlCreateCheckout(cartId, opts)\n if (checkout?.id) {\n this.state = {\n ...(this.state ?? { sponsorId, subtotal: 0, currency: getGlobalCurrency() }),\n sponsorId,\n checkoutId: checkout.id,\n checkout,\n }\n this.emit()\n try {\n const updated = await gqlUpdateCheckout(\n {\n checkoutId: checkout.id,\n buyerAcceptsPurchaseConditions: true,\n buyerAcceptsTermsConditions: true,\n },\n opts,\n )\n if (updated?.id) {\n this.state = { ...this.state, checkout: updated }\n this.emit()\n return updated\n }\n } catch (err) {\n if (typeof console !== 'undefined') {\n console.warn('[CheckoutManager] Failed to auto-accept terms & purchase conditions:', err)\n }\n }\n }\n return checkout\n }\n\n /** Update the backend checkout (terms are re-asserted unless overridden; the attribution rides along unless the caller gives its own). */\n async updateCheckout(variables: Record<string, unknown>, sponsorId?: number): Promise<any> {\n const spId = sponsorId ?? this.state?.sponsorId\n const opts = await getCartGraphQLOptions(spId)\n const attribution = 'attribution' in variables ? undefined : await this.attributionFor(spId)\n const fullVars = {\n buyerAcceptsPurchaseConditions: true,\n buyerAcceptsTermsConditions: true,\n ...(attribution ? { attribution } : {}),\n ...variables,\n }\n const updated = await gqlUpdateCheckout(fullVars, opts)\n if (updated?.id && this.state) {\n this.state = { ...this.state, checkoutId: updated.id, checkout: updated }\n this.emit()\n }\n return updated\n }\n\n async getCheckout(checkoutId: string, sponsorId?: number): Promise<any> {\n const opts = await getCartGraphQLOptions(sponsorId ?? this.state?.sponsorId)\n return gqlGetCheckout(checkoutId, opts)\n }\n\n /**\n * The Vio order number (#4497) a checkout became, or null: not born yet,\n * or an API that does not say it. Never throws — it is a line on a\n * receipt, and a receipt does not fail for it.\n */\n async getOrderNumber(checkoutId: string, sponsorId?: number): Promise<number | null> {\n return (await this.getOrderReference(checkoutId, sponsorId)).orderNumber\n }\n\n /**\n * What a paid checkout says of itself: the order number (as above) and the\n * buyer reference — shopcart's keyed hash of the buyer's email, what the\n * `vio:payment-success` detail carries as `buyerRef` and analytics sends as\n * `buyer_id`. Never throws; `null` for whatever the API does not say.\n */\n async getOrderReference(checkoutId: string, sponsorId?: number): Promise<OrderReference> {\n if (!checkoutId) return this.withSponsor({ orderNumber: null, buyerRef: null }, checkoutId, sponsorId)\n // Concurrent asks for the same checkout (the receipt's order number and\n // the payment event's buyer reference start together) share one request.\n let request = this.referenceInFlight.get(checkoutId)\n if (!request) {\n const asked = (async (): Promise<CheckoutReference> => {\n try {\n const opts = await getCartGraphQLOptions(\n sponsorId ?? this.sponsorIdOfCheckout(checkoutId) ?? this.state?.sponsorId,\n )\n return await gqlGetCheckoutReference(checkoutId, opts)\n } catch {\n return { orderNumber: null, buyerRef: null }\n } finally {\n this.referenceInFlight.delete(checkoutId)\n }\n })()\n this.referenceInFlight.set(checkoutId, asked)\n request = asked\n }\n // After the answer: asking awaited the bootstrap, which names the sponsor.\n return this.withSponsor(await request, checkoutId, sponsorId)\n }\n\n /**\n * The sponsor of a checkout as `getOrderReference` carries it\n * (`{ id, name, logoUrl }`): the given sponsor, else the one this tab\n * remembered for the checkout, else the open checkout's when it IS that\n * checkout — named by the `Vio.sponsorIdentity` rule. `undefined` when\n * nothing names it; never throws.\n */\n private checkoutSponsor(checkoutId?: string | null, sponsorId?: number | string | null): CheckoutSponsor | undefined {\n try {\n const id = sponsorId ?? this.sponsorIdOfCheckout(checkoutId ?? undefined)\n const numeric = id === undefined || id === null || id === '' ? undefined : Number(id)\n if (typeof this.deps.sponsorIdentity === 'function') {\n return checkoutSponsorOf(this.deps.sponsorIdentity(numeric, { checkoutId: checkoutId ?? undefined }))\n }\n const memo = rememberedCheckoutSponsor(checkoutId ?? undefined)\n if (memo && (numeric === undefined || memo.sponsorId === numeric) && (memo.name || memo.logoUrl)) {\n return { id: memo.sponsorId, name: memo.name, logoUrl: memo.logoUrl }\n }\n return undefined\n } catch {\n return undefined\n }\n }\n\n /** The sponsor id of a checkout: this tab's memory of it, else the open checkout's when it is that one. */\n private sponsorIdOfCheckout(checkoutId: string | undefined): number | undefined {\n if (!checkoutId) return undefined\n const memo = rememberedCheckoutSponsor(checkoutId)\n if (memo) return memo.sponsorId\n return this.state?.checkoutId === checkoutId ? this.state.sponsorId : undefined\n }\n\n private withSponsor(reference: CheckoutReference, checkoutId: string, sponsorId?: number): OrderReference {\n const sponsor = this.checkoutSponsor(checkoutId || undefined, sponsorId)\n return sponsor ? { ...reference, sponsor } : reference\n }\n\n /**\n * Remember whose checkout this is (`rememberCheckoutSponsor`), with the\n * sponsor's name and logo as known now — so a confirmation after a redirect\n * or a reload can name the brand. Written again only when something changed.\n */\n private rememberSponsorOfCheckout(checkoutId: string, sponsorId: number): void {\n try {\n let identity: SponsorIdentity | null = null\n try {\n identity = this.deps.sponsorIdentity?.(sponsorId, { checkoutId }) ?? null\n } catch {\n identity = null\n }\n const name = identity?.name || this.cartManager.getCart(sponsorId)?.sponsorName || ''\n const logoUrl = identity?.logoUrl ?? null\n const key = JSON.stringify([checkoutId, sponsorId, name, logoUrl])\n if (key === this.lastRememberedSponsor) return\n this.lastRememberedSponsor = key\n rememberCheckoutSponsor(checkoutId, { sponsorId, name, logoUrl })\n } catch {\n /* the memory never costs a checkout */\n }\n }\n\n /** In-flight `getOrderReference` per checkout id (see there). */\n private referenceInFlight = new Map<string, Promise<CheckoutReference>>()\n\n /**\n * Payment methods enabled for the sponsor (backend-configured). Memoised per\n * sponsor with in-flight dedupe — several UI components ask on every open.\n */\n async getAvailablePaymentMethods(sponsorId?: number): Promise<any> {\n const spId = sponsorId ?? this.state?.sponsorId\n if (!spId) return null\n\n if (this.paymentMethodsCache.has(spId)) {\n return this.paymentMethodsCache.get(spId)\n }\n const inFlight = this.paymentMethodsPromises.get(spId)\n if (inFlight) return inFlight\n\n const promise = (async () => {\n try {\n const opts = await getCartGraphQLOptions(spId)\n const res = await gqlGetAvailablePaymentMethods(opts)\n // Never cache empty/failed responses — a transient blip would freeze\n // the payment grid for the whole page session.\n if (res) this.paymentMethodsCache.set(spId, res)\n return res\n } finally {\n this.paymentMethodsPromises.delete(spId)\n }\n })()\n\n this.paymentMethodsPromises.set(spId, promise)\n return promise\n }\n\n clearPaymentMethodsCache(): void {\n this.paymentMethodsCache.clear()\n this.paymentMethodsPromises.clear()\n }\n\n /**\n * Real shipping options from the backend cart (per supplier), mapped to the\n * KlarnaShippingOption shape (minor units). Empty array on failure/no\n * options — Klarna callers use that as-is (no static fallback anymore, see\n * 2026-08-18: it only ever papered over a race, now fixed via\n * `waitForCartMutations`). `KLARNA_SHIPPING_OPTIONS` is still used\n * separately by Apple Pay's synchronous sheet setup, which can't await\n * this at all.\n */\n async fetchAvailableShippings(sponsorId?: number): Promise<KlarnaShippingOption[]> {\n this.shippingsResolved = false\n try {\n const spId = sponsorId ?? this.state?.sponsorId\n if (!spId) return []\n // A quick add-then-checkout can race an in-flight AddItem — wait for it\n // to settle so this reads the cart it actually produced, not a stale\n // pre-add snapshot (Alan, 2026-08-18: shippings came back empty this way).\n await this.cartManager.waitForCartMutations(spId)\n const cart = this.cartManager.getCart(spId)\n let cartId = cart?.cartId\n if (!cartId) {\n cartId = await this.cartManager.ensureCartId(spId)\n }\n if (!cartId) return []\n const opts = await getCartGraphQLOptions(spId)\n const supplierGroups = await gqlGetLineItemsBySupplier(cartId, opts)\n this.shippingsResolved = Array.isArray(supplierGroups)\n const firstGroup = Array.isArray(supplierGroups) ? supplierGroups[0] : null\n const shippings = firstGroup?.available_shippings ?? []\n if (Array.isArray(shippings) && shippings.length > 0) {\n const supplierId = firstGroup?.supplier?.id\n const mapped: KlarnaShippingOption[] = shippings.map((s: any, idx: number) => {\n const priceObj = s.price ?? {}\n const amount =\n typeof priceObj.amount_incl_taxes === 'number'\n ? priceObj.amount_incl_taxes\n : typeof priceObj.amount === 'number'\n ? priceObj.amount\n : 0\n return {\n id: String(s.id),\n supplierId: supplierId != null ? String(supplierId) : undefined,\n method: s.name || 'Default Shipping',\n name: s.name || 'Default Shipping',\n description: s.description || '',\n country_code: s.country_code || 'NO',\n price: Math.round(amount * 100),\n priceMajor: amount,\n currency: priceObj.currency_code || getGlobalCurrency(),\n tax_amount: Math.round((priceObj.tax_amount ?? 0) * 100),\n tax_rate: Math.round((priceObj.tax_rate ?? 0) * 100),\n preselected: idx === 0,\n }\n })\n // Cheapest first, and that one preselected. The backend lists them in\n // database order, which on 2026-09-14 made the dearest rate the\n // default — and, since the checkout saves the preselected one on the\n // cart, the rate Qliro opened with. Stable: equal prices keep their\n // order.\n mapped.sort((a, b) => a.price - b.price)\n mapped.forEach((m, idx) => {\n m.preselected = idx === 0\n })\n this.lastFetchedShippings = mapped\n return mapped\n }\n } catch (err) {\n if (typeof console !== 'undefined') {\n console.warn('[CheckoutManager] fetchAvailableShippings failed:', err)\n }\n }\n return []\n }\n\n /**\n * Whether the last `fetchAvailableShippings` got an answer from the backend,\n * possibly an empty one, rather than failing or finding no cart. The two\n * return the same empty list, and only an answer means the cart has\n * nothing it can ship with.\n */\n get lastShippingsResolved(): boolean {\n return this.shippingsResolved\n }\n\n /** Set the chosen shipping per supplier on the backend cart. */\n async updateShippingsBySupplier(\n data: Array<{ shipping_id: string; supplier_id: number }>,\n sponsorId?: number,\n ): Promise<any> {\n const spId = sponsorId ?? this.state?.sponsorId\n if (!spId) return null\n const cart = this.cartManager.getCart(spId)\n if (!cart?.cartId) return null\n const opts = await getCartGraphQLOptions(spId)\n const updated = await gqlUpdateShippingsBySupplier(cart.cartId, data, opts)\n if (updated) {\n this.cartManager.updateFromBackendCart(spId, updated)\n }\n return updated\n }\n\n /**\n * Shared setup for the redirect payment links (Stripe / Vipps): ensure the\n * backend cart + checkout exist, push email/address onto the checkout, and\n * return everything the payment mutation needs.\n */\n private async prepareRedirectPayment(\n sponsorId: number | undefined,\n formData: unknown,\n extraUpdateVars: Record<string, unknown> = {},\n ): Promise<{ spId: number; checkoutId: string; emailVal: string; opts: CartQueryOptions }> {\n const spId = sponsorId ?? this.state?.sponsorId\n if (!spId) throw new Error('[CheckoutManager] no sponsor for payment')\n // The payment link is minted for the cart as it is AFTER any in-flight\n // quantity change — never for the one before it.\n await this.cartManager.waitForCartMutations(spId)\n const cart = this.cartManager.getCart(spId)\n let cartId = cart?.cartId\n if (!cartId) {\n cartId = await this.cartManager.ensureCartId(spId)\n }\n if (!cartId) {\n throw new Error(`[CheckoutManager] Failed to obtain cart_id for sponsor ${spId}`)\n }\n\n const opts = await getCartGraphQLOptions(spId)\n // The order's attribution (ADR-0035 phase B): on the checkout when it is\n // created here, and again on the update right before paying.\n const attribution = await this.attributionFor(spId)\n let checkoutId = this.state?.checkoutId\n if (!checkoutId) {\n const checkoutRes = attribution\n ? await gqlCreateCheckout(cartId, opts, { attribution })\n : await gqlCreateCheckout(cartId, opts)\n checkoutId = checkoutRes?.id\n }\n if (!checkoutId) {\n throw new Error('[CheckoutManager] no backend checkout — cannot start the payment')\n }\n\n // Vipps collects the address in its own flow — never push one onto the\n // checkout for it (the backend rejects partial Vipps addresses).\n const isVipps = extraUpdateVars?.paymentMethod === 'Vipps'\n const addr =\n typeof formData === 'object' && formData !== null ? formData : this.state?.address\n const addressObj = !isVipps ? buildCheckoutAddress(addr) : null\n const emailVal =\n (typeof formData === 'string'\n ? formData\n : (formData as { email?: string } | undefined)?.email) ||\n this.state?.address?.email ||\n ''\n const hasEmail = !!emailVal && emailVal.includes('@')\n if (!hasEmail && !isVipps) {\n // Never mint a payment link with a fabricated email — the order's\n // receipt/contact would be wrong forever.\n throw new Error('[CheckoutManager] email is required to start the payment')\n }\n // Vipps hands the email back with the payment (Express, or the profile\n // it shares), so none is needed up front — and none is invented.\n\n const updateVars: Record<string, unknown> = {\n checkoutId,\n ...(hasEmail ? { email: emailVal } : {}),\n buyerAcceptsPurchaseConditions: true,\n buyerAcceptsTermsConditions: true,\n ...(attribution ? { attribution } : {}),\n ...extraUpdateVars,\n }\n if (addressObj) {\n updateVars.shippingAddress = addressObj\n updateVars.billingAddress = addressObj\n }\n\n try {\n const updated = await gqlUpdateCheckout(updateVars, opts)\n if (updated?.id) {\n this.state = {\n ...(this.state ?? { sponsorId: spId, subtotal: 0, currency: getGlobalCurrency() }),\n sponsorId: spId,\n checkoutId: updated.id,\n checkout: updated,\n }\n this.emit()\n checkoutId = updated.id\n }\n } catch (err) {\n // Redirecting after a failed UpdateCheckout would charge with a stale\n // (or missing) address/email — abort instead.\n throw new Error(\n `[CheckoutManager] could not persist checkout details: ${describeError(err)}`,\n )\n }\n\n // (Narrowing: the assignment inside the try widens the type again.)\n if (!checkoutId) {\n throw new Error('[CheckoutManager] no backend checkout — cannot start the payment')\n }\n return { spId, checkoutId, emailVal, opts }\n }\n\n /** Redirect the top window to a payment provider URL. */\n private static redirectTo(url: string): void {\n if (typeof window === 'undefined') return\n try {\n if (window.top && window.top !== window) {\n window.top.location.href = url\n } else {\n window.location.href = url\n }\n } catch {\n window.open(url, '_top') || window.open(url, '_blank')\n }\n }\n\n /**\n * Stripe payment link: create/refresh the backend checkout, mint the Stripe\n * Checkout URL (CreatePaymentStripe) and redirect. The return URL carries\n * vio_payment/vio_method/checkout_id so the page can show the confirmation.\n */\n async startStripePayment(sponsorId?: number, formData?: unknown): Promise<any> {\n const { spId, checkoutId, emailVal, opts } = await this.prepareRedirectPayment(\n sponsorId,\n formData,\n { paymentMethod: 'Stripe' },\n )\n const successUrl = resolveHttpsReturnUrl(null, {\n vio_payment: 'success',\n vio_method: 'stripe',\n vio_sponsor: spId,\n checkout_id: checkoutId,\n })\n const stripeRes = await gqlCreatePaymentStripe(\n { checkoutId, successUrl, paymentMethod: 'Stripe', email: emailVal },\n opts,\n )\n if (stripeRes?.checkout_url) {\n CheckoutManager.redirectTo(stripeRes.checkout_url)\n return stripeRes\n }\n throw new Error('Stripe payment link generation failed: missing checkout_url')\n }\n\n /**\n * Vipps: create the payment via Vio Commerce and redirect to Vipps'\n * landing page (on a phone it opens the app; on a desktop it offers to\n * send the payment to the phone).\n *\n * `express: true` asks for Vipps Express — address and delivery chosen\n * inside the app, the email handed back with the payment — which is what\n * the Vipps buttons on the product and the cart ask for. When the cart\n * cannot have it (several suppliers, digital goods, no rate for the\n * country) the backend creates NO payment and answers `express: false`\n * with the reason; this resolves with that answer, without redirecting,\n * so the caller can open the ordinary checkout instead. Without the flag\n * the backend decides: Express while the cart has no delivery yet, a\n * plain payment once the shopper chose one in our form.\n */\n async startVippsPayment(\n sponsorId?: number,\n formData?: unknown,\n options: { express?: boolean } = {},\n ): Promise<any> {\n const waitFor = sponsorId ?? this.state?.sponsorId\n if (waitFor) await this.cartManager.waitForCartMutations(waitFor)\n const { spId, checkoutId, emailVal, opts } = await this.prepareRedirectPayment(\n sponsorId,\n formData,\n { paymentMethod: 'Vipps' },\n )\n const returnUrl = resolveHttpsReturnUrl(null, {\n vio_payment: 'success',\n vio_method: 'vipps',\n vio_sponsor: spId,\n checkout_id: checkoutId,\n })\n const vippsRes = await gqlCreatePaymentVipps(\n {\n checkoutId,\n ...(emailVal && emailVal.includes('@') ? { email: emailVal } : {}),\n returnUrl,\n ...(options.express !== undefined ? { express: options.express } : {}),\n },\n opts,\n )\n if (vippsRes?.payment_url) {\n CheckoutManager.redirectTo(vippsRes.payment_url)\n return vippsRes\n }\n if (options.express === true && vippsRes?.express === false) {\n return vippsRes\n }\n throw new Error('Vipps payment link generation failed: missing payment_url')\n }\n\n /**\n * The Vipps Express button: the shopper taps it and the app opens with\n * address and delivery already there. Resolves with `{ express: false,\n * reason }` — and nothing redirected — when this cart cannot have it.\n */\n async startVippsExpress(sponsorId?: number): Promise<any> {\n return this.startVippsPayment(sponsorId, undefined, { express: true })\n }\n\n /** Vipps' own payment state for the checkout — see getVippsStatus in\n * cart-queries.ts for why this exists instead of trusting GetCheckout. */\n async getVippsStatus(checkoutId: string, sponsorId?: number): Promise<{ state?: string; duplicate_of?: string | null } | null> {\n const opts = await getCartGraphQLOptions(sponsorId ?? this.state?.sponsorId)\n return gqlGetVippsStatus({ checkoutId }, opts)\n }\n\n /**\n * Kustom (former Klarna Checkout) — create the KCO order via Vio Commerce\n * and render its html_snippet into `container`. The widget collects\n * address, shipping and payment by itself; the SDK renders nothing else.\n */\n async mountKustomCheckout(\n container: HTMLElement,\n sponsorId?: number,\n handlers: KustomListenerHandlers = {},\n ): Promise<KustomOrder> {\n const spId = sponsorId ?? this.state?.sponsorId\n if (!spId) throw new Error('[CheckoutManager] no sponsor for Kustom')\n const cart = this.cartManager.getCart(spId)\n let cartId = cart?.cartId\n if (!cartId) cartId = await this.cartManager.ensureCartId(spId)\n if (!cartId) {\n throw new Error(`[CheckoutManager] Failed to obtain cart_id for sponsor ${spId}`)\n }\n const opts = await getCartGraphQLOptions(spId)\n let checkoutId = this.state?.checkoutId\n if (!checkoutId) {\n // createCheckout(), NOT the raw mutation: shopcart refuses to start a\n // payment on a checkout whose buyer has not accepted the purchase\n // conditions (\"Is required that customer accepted purchase conditions\"),\n // and that acceptance is part of createCheckout(). Creating it raw here\n // made every embedded method fail whenever IT was the one to create the\n // checkout — which is the normal path when the shopper picks the method\n // straight from the cart.\n const checkoutRes = await this.createCheckout(spId)\n checkoutId = checkoutRes?.id\n if (checkoutId && this.state) {\n this.state = { ...this.state, checkoutId }\n }\n }\n if (!checkoutId) {\n throw new Error('[CheckoutManager] no backend checkout for the Kustom order')\n }\n // href MUST be query-less: shopcart appends ?order_id=…&payment_processor=KUSTOM\n const href = kustomCleanHref()\n const order = await gqlCreatePaymentKustom(\n {\n checkoutId,\n countryCode: getGlobalCountryCode(),\n href,\n email: this.state?.address?.email || undefined,\n client: `web-sdk ${SDK_VERSION}`,\n },\n opts,\n )\n if (!order?.html_snippet) {\n throw new Error('Kustom order creation failed: missing html_snippet')\n }\n // The snippet defines window._klarnaCheckout; listeners registered right\n // after it are queued until the iframe has rendered.\n this.destroyKustomListeners()\n renderKustomSnippet(container, order.html_snippet)\n this.kustomController = installKustomListeners(handlers)\n return order\n }\n\n private kustomController: { destroy(): void } | null = null\n\n /** Disarm the widget's listeners with the widget they belong to. */\n destroyKustomListeners(): void {\n this.kustomController?.destroy()\n this.kustomController = null\n }\n\n /**\n * The cart changed under an open Kustom widget: lock it, push the cart\n * into the SAME order, and let the widget refresh itself. Kustom's own\n * rule — never a new order for a cart change. The widget auto-resumes\n * after 10 s if the sync never comes back.\n */\n async syncKustomOrder(sponsorId?: number): Promise<KustomOrder | null> {\n const spId = sponsorId ?? this.state?.sponsorId\n const checkoutId = this.state?.checkoutId\n if (!spId || !checkoutId) return null\n const opts = await getCartGraphQLOptions(spId)\n suspendKustom()\n try {\n return await gqlSyncPaymentKustom(checkoutId, opts)\n } finally {\n resumeKustom()\n }\n }\n\n /** Re-read a Kustom order — used on the confirmation return trip. */\n async getKustomOrder(orderId: string, sponsorId?: number): Promise<KustomOrder | null> {\n const opts = await getCartGraphQLOptions(sponsorId ?? this.state?.sponsorId)\n return gqlGetKustomOrder(orderId, opts)\n }\n\n /** Render a Kustom html_snippet (e.g. the confirmation receipt) into a container. */\n renderKustomSnippet(container: HTMLElement, htmlSnippet: string): void {\n renderKustomSnippet(container, htmlSnippet)\n }\n\n /**\n * Qliro Checkout — create the order via Vio Commerce and render its\n * html_snippet into `container` (widget-does-everything, like Kustom).\n */\n async mountQliroCheckout(\n container: HTMLElement,\n sponsorId?: number,\n ): Promise<QliroOrder> {\n const spId = sponsorId ?? this.state?.sponsorId\n if (!spId) throw new Error('[CheckoutManager] no sponsor for Qliro')\n const cart = this.cartManager.getCart(spId)\n let cartId = cart?.cartId\n if (!cartId) cartId = await this.cartManager.ensureCartId(spId)\n if (!cartId) {\n throw new Error(`[CheckoutManager] Failed to obtain cart_id for sponsor ${spId}`)\n }\n const opts = await getCartGraphQLOptions(spId)\n let checkoutId = this.state?.checkoutId\n if (!checkoutId) {\n // createCheckout(), NOT the raw mutation: shopcart refuses to start a\n // payment on a checkout whose buyer has not accepted the purchase\n // conditions (\"Is required that customer accepted purchase conditions\"),\n // and that acceptance is part of createCheckout(). Creating it raw here\n // made every embedded method fail whenever IT was the one to create the\n // checkout — which is the normal path when the shopper picks the method\n // straight from the cart.\n const checkoutRes = await this.createCheckout(spId)\n checkoutId = checkoutRes?.id\n if (checkoutId && this.state) {\n this.state = { ...this.state, checkoutId }\n }\n }\n if (!checkoutId) {\n throw new Error('[CheckoutManager] no backend checkout for the Qliro order')\n }\n // href MUST be query-less: shopcart appends ?checkout_id=…&payment_processor=QLIRO\n const href = kustomCleanHref()\n const order = await gqlCreatePaymentQliro(\n {\n checkoutId,\n countryCode: getGlobalCountryCode(),\n href,\n email: this.state?.address?.email || undefined,\n // Qliro cannot be restyled once rendered, so the host page's theme has\n // to travel with the order.\n theme: readVioTheme(),\n },\n opts,\n )\n if (!order?.html_snippet) {\n throw new Error('Qliro order creation failed: missing html_snippet')\n }\n // BEFORE the snippet: Qliro calls `window.q1Ready` once, as the widget\n // finishes rendering, and never again. Installed after the injection, the\n // listeners would simply never fire.\n this.qliroController?.destroy()\n this.qliroController = installQliroListeners({\n checkoutId,\n queryOptions: opts,\n onEvent: (event) => this.onQliroEvent(event),\n })\n renderKustomSnippet(container, order.html_snippet)\n return order\n }\n\n /**\n * Everything the customer does inside the Qliro iframe, re-published as a\n * DOM event so a host page can follow a checkout it cannot see into.\n */\n private onQliroEvent(event: QliroEvent): void {\n this.dispatchEvent(\n new CustomEvent<QliroEvent>('qliro-event', {\n detail: event,\n bubbles: true,\n composed: true,\n }),\n )\n // Qliro owns the shipping choice — this only keeps our own summary\n // showing the same total the customer is looking at.\n if (event.type === 'shipping-changed' || event.type === 'shipping-price-changed') {\n this.emit()\n }\n }\n\n /**\n * Push the current cart onto the open Qliro order.\n *\n * Call it after changing the cart while the widget is open: it holds\n * `q1.lock()` across the round trip and unlocks once Qliro confirms it is\n * showing the new version. A no-op when no Qliro widget is mounted.\n */\n async syncQliroOrder(): Promise<QliroSyncResult | null> {\n return (await this.qliroController?.sync()) ?? null\n }\n\n /** Drop the Qliro listeners and release any lock still held. */\n destroyQliroListeners(): void {\n this.qliroController?.destroy()\n this.qliroController = null\n }\n\n /** Re-read the Qliro order owned by a checkout — the confirmation trip. */\n async getQliroOrder(checkoutId: string, sponsorId?: number): Promise<QliroOrder | null> {\n const opts = await getCartGraphQLOptions(sponsorId ?? this.state?.sponsorId)\n return gqlGetQliroOrder(checkoutId, opts)\n }\n\n /**\n * Mount the Walley embedded checkout. `onPurchaseCompleted` fires as soon\n * as Walley's own script dispatches its success event INSIDE the widget —\n * no redirect needed. `getWalleyOrder`/the confirmation-URL fallback\n * remain for the case the event is missed (tab backgrounded, reload).\n */\n async mountWalleyCheckout(\n container: HTMLElement,\n sponsorId?: number,\n onPurchaseCompleted?: (order: WalleyOrder) => void,\n ): Promise<WalleyOrder> {\n const spId = sponsorId ?? this.state?.sponsorId\n if (!spId) throw new Error('[CheckoutManager] no sponsor for Walley')\n const cart = this.cartManager.getCart(spId)\n let cartId = cart?.cartId\n if (!cartId) cartId = await this.cartManager.ensureCartId(spId)\n if (!cartId) {\n throw new Error(`[CheckoutManager] Failed to obtain cart_id for sponsor ${spId}`)\n }\n const opts = await getCartGraphQLOptions(spId)\n let checkoutId = this.state?.checkoutId\n if (!checkoutId) {\n // createCheckout(), NOT the raw mutation: shopcart refuses to start a\n // payment on a checkout whose buyer has not accepted the purchase\n // conditions (\"Is required that customer accepted purchase conditions\"),\n // and that acceptance is part of createCheckout(). Creating it raw here\n // made every embedded method fail whenever IT was the one to create the\n // checkout — which is the normal path when the shopper picks the method\n // straight from the cart.\n const checkoutRes = await this.createCheckout(spId)\n checkoutId = checkoutRes?.id\n if (checkoutId && this.state) {\n this.state = { ...this.state, checkoutId }\n }\n }\n if (!checkoutId) {\n throw new Error('[CheckoutManager] no backend checkout for the Walley order')\n }\n // href MUST be query-less: shopcart appends ?checkout_id=…&payment_processor=WALLEY\n const href = kustomCleanHref()\n const order = await gqlCreatePaymentWalley(\n {\n checkoutId,\n countryCode: getGlobalCountryCode(),\n href,\n email: this.state?.address?.email || undefined,\n },\n opts,\n )\n if (!order?.html_snippet) {\n throw new Error('Walley order creation failed: missing html_snippet')\n }\n renderKustomSnippet(container, order.html_snippet)\n if (onPurchaseCompleted) {\n const handler = () => {\n document.removeEventListener(WALLEY_PURCHASE_COMPLETED_EVENT, handler)\n onPurchaseCompleted(order)\n }\n document.addEventListener(WALLEY_PURCHASE_COMPLETED_EVENT, handler, { once: true })\n }\n return order\n }\n\n /** Re-read the Walley session owned by a checkout — the confirmation trip. */\n async getWalleyOrder(checkoutId: string, sponsorId?: number): Promise<WalleyOrder | null> {\n const opts = await getCartGraphQLOptions(sponsorId ?? this.state?.sponsorId)\n return gqlGetWalleyOrder(checkoutId, opts)\n }\n\n /**\n * Mount the Nexi embedded checkout — Nexi's own JS SDK, not a snippet.\n *\n * `onCompleted` fires on Nexi's `payment-completed` (no redirect: Nexi\n * renders no receipt, the component shows Vio's confirmation). Shipping is\n * Vio's: Nexi holds its pay button until `address-changed` has been\n * re-priced through `UpdateNexiShipping` — the widget is frozen meanwhile\n * and `onShipping` reports the outcome (NO_SHIPPING keeps it held).\n *\n * A session interrupted by a third-party redirect inside Nexi (Vipps,\n * Swish, MobilePay) is remembered in sessionStorage and resumed on the\n * same paymentId instead of creating a new payment — only when `resume`\n * names it. Every other opening creates a payment for the cart as it is.\n */\n async mountNexiCheckout(\n container: HTMLElement,\n sponsorId?: number,\n handlers: {\n onCompleted?: (order: NexiOrder) => void\n onShipping?: (result: NexiShippingUpdate | null, error?: unknown) => void\n } = {},\n /**\n * Set ONLY when the page came back from a redirect inside Nexi\n * (Vipps/Swish/MobilePay) with `?paymentId=`: resume that payment.\n */\n resume?: { paymentId: string },\n ): Promise<NexiOrder> {\n const spId = sponsorId ?? this.state?.sponsorId\n if (!spId) throw new Error('[CheckoutManager] no sponsor for Nexi')\n const cart = this.cartManager.getCart(spId)\n let cartId = cart?.cartId\n if (!cartId) cartId = await this.cartManager.ensureCartId(spId)\n if (!cartId) {\n throw new Error(`[CheckoutManager] Failed to obtain cart_id for sponsor ${spId}`)\n }\n const opts = await getCartGraphQLOptions(spId)\n // The remembered session is resumed only on the redirect return it exists\n // for. Read on every opening, it put the NEXT purchase in the same tab on\n // the previous cart's payment — its lines and its total (2026-09-16: an\n // armchair for 4 999 opened Nexi asking for three lamps at 2 247).\n const stored = resume ? readNexiPending() : null\n const pending = stored && stored.paymentId === resume?.paymentId ? stored : null\n let checkoutId = this.state?.checkoutId\n // Back from a redirect inside Nexi: the page reloaded and the state is\n // fresh, but the checkout and its payment still exist.\n if (!checkoutId && pending && pending.sponsorId === spId) {\n checkoutId = pending.checkoutId\n if (this.state) this.state = { ...this.state, checkoutId }\n }\n if (!checkoutId) {\n // createCheckout(), NOT the raw mutation — see mountWalleyCheckout.\n const checkoutRes = await this.createCheckout(spId)\n checkoutId = checkoutRes?.id\n if (checkoutId && this.state) {\n this.state = { ...this.state, checkoutId }\n }\n }\n if (!checkoutId) {\n throw new Error('[CheckoutManager] no backend checkout for the Nexi payment')\n }\n const ownedCheckoutId: string = checkoutId\n\n let order: NexiOrder | null = null\n if (pending && pending.checkoutId === ownedCheckoutId) {\n try {\n order = await gqlGetNexiOrder(ownedCheckoutId, opts)\n } catch {\n order = null\n }\n if (order && isNexiPaid(order.status)) {\n // Paid while we were away (the redirect completed it): nothing to\n // mount, just confirm.\n clearNexiPending()\n handlers.onCompleted?.(order)\n return order\n }\n if (order && (order.status !== 'Created' || order.order_id !== pending.paymentId)) {\n order = null\n }\n }\n if (!order) {\n // href MUST be the page's own URL, query-less: Nexi checks it.\n const created = await gqlCreatePaymentNexi(\n {\n checkoutId: ownedCheckoutId,\n countryCode: getGlobalCountryCode(),\n href: kustomCleanHref(),\n email: this.state?.address?.email || undefined,\n },\n opts,\n )\n if (!created?.order_id || !created.checkout_key) {\n throw new Error('Nexi payment creation failed: missing paymentId/checkout key')\n }\n order = created\n rememberNexiPending({ checkoutId: ownedCheckoutId, sponsorId: spId, paymentId: order.order_id })\n }\n\n this.destroyNexi()\n const handle = await mountNexi(container, order, {\n language: nexiLanguageFor(getGlobalCountryCode()),\n theme: nexiThemeFrom(readVioTheme()),\n })\n this.nexiHandle = handle\n const mounted = order\n // Resumed with an address already priced: Nexi will not announce it again,\n // so hand the checkout the rate and the choices, and let a pick re-price\n // that same address.\n const carried = order.shipping\n this.nexiPreferredShipping = carried?.shipping_id ?? null\n this.nexiShippingPreview = null\n if (carried?.ok && carried.country) {\n this.nexiShippingContext = {\n handle,\n checkoutId: ownedCheckoutId,\n address: { countryCode: carried.country, postalCode: carried.postal_code },\n fromShopper: carried.address_source !== 'market',\n opts,\n onShipping: handlers.onShipping,\n }\n handlers.onShipping?.(carried)\n } else if (carried?.reason === 'AWAITING_ADDRESS') {\n // The rates are shown from the start; nothing is charged until Nexi\n // announces the address.\n this.nexiShippingPreview = carried\n this.nexiShippingContext = {\n handle,\n checkoutId: ownedCheckoutId,\n address: null,\n opts,\n onShipping: handlers.onShipping,\n }\n handlers.onShipping?.(carried)\n }\n const onAddress = (address: any) => {\n this.nexiShippingContext = {\n handle,\n checkoutId: ownedCheckoutId,\n address,\n fromShopper: true,\n opts,\n onShipping: handlers.onShipping,\n }\n void this.repriceNexiShipping(\n handle,\n ownedCheckoutId,\n address,\n opts,\n handlers.onShipping,\n this.nexiPreferredShipping ?? undefined,\n )\n }\n handle.on('address-changed', onAddress)\n // The same, from the Apple Pay sheet inside the widget.\n handle.on('applepay-contact-updated', onAddress)\n // Nexi does not charge until we answer: set the shipping first. Needed\n // because Nexi can fill in a recognised shopper's address without\n // announcing it, and then nothing would ever have been priced.\n handle.on('pay-initialized', () => {\n void this.finalizeNexiPayment(handle, ownedCheckoutId, opts, handlers.onShipping)\n })\n handle.on('payment-completed', (result: any) => {\n clearNexiPending()\n handlers.onCompleted?.({\n ...mounted,\n order_id: String(result?.paymentId ?? mounted.order_id),\n status: 'Reserved',\n })\n })\n return order\n }\n\n /**\n * The shopper picked another rate from the `options` Nexi's last\n * re-pricing returned: charge that one instead. Nexi has no shipping picker,\n * so the checkout shows the rates and calls this. A no-op until an address\n * has been typed in the widget.\n */\n async pickNexiShipping(shippingId: string): Promise<void> {\n const ctx = this.nexiShippingContext\n if (!ctx || ctx.handle !== this.nexiHandle) return\n this.nexiPreferredShipping = shippingId\n if (!ctx.address) {\n // No address yet: remember the pick and show it; it is charged once the\n // address is priced.\n const preview = this.nexiShippingPreview\n const picked = preview?.options?.find((o) => o.id === shippingId)\n if (preview && picked) {\n this.nexiShippingPreview = {\n ...preview,\n shipping_id: picked.id,\n shipping_name: picked.name,\n shipping_price: picked.price,\n }\n ctx.onShipping?.(this.nexiShippingPreview)\n }\n return\n }\n await this.repriceNexiShipping(ctx.handle, ctx.checkoutId, ctx.address, ctx.opts, ctx.onShipping, shippingId)\n }\n\n /**\n * `pay-initialized` → confirm the shipping for the address Nexi will ship\n * to → `payment-order-finalized`.\n *\n * The payment already carries a shipping (set at creation, re-priced on\n * every address and pick), so normally nothing changes and Nexi charges.\n * When the shopper's address was never announced — Nexi fills it in for a\n * shopper it recognises — the backend reads it from the payment. If that\n * changes the amount, the payment is STOPPED and the widget reloaded: an\n * amount that changes while Nexi charges is what failed on 2026-09-16/17\n * (payments 085277846ae44f7498ae94e112435d63, f6116e6d68294a88927d35b05d907f10).\n */\n private async finalizeNexiPayment(\n handle: NexiCheckoutHandle,\n checkoutId: string,\n opts: CartQueryOptions,\n onShipping?: (result: NexiShippingUpdate | null, error?: unknown) => void,\n ): Promise<void> {\n const ctx = this.nexiShippingContext?.handle === handle ? this.nexiShippingContext : null\n // Only the shopper's own address is trusted here; otherwise the backend\n // reads the one Nexi holds.\n const address = ctx?.fromShopper ? ctx.address : null\n let proceed = false\n let reload = false\n try {\n const result = await gqlUpdateNexiShipping(\n {\n checkoutId,\n countryCode: String(address?.countryCode ?? address?.country ?? ''),\n postalCode: address?.postalCode ? String(address.postalCode) : undefined,\n shippingId: this.nexiPreferredShipping ?? undefined,\n },\n opts,\n )\n if (result?.ok) {\n if (result.shipping_id) this.nexiPreferredShipping = result.shipping_id\n if (ctx && result.country) {\n ctx.address = { countryCode: result.country, postalCode: result.postal_code }\n ctx.fromShopper = true\n }\n reload = result.changed === true\n proceed = !reload\n }\n onShipping?.(result ? { ...result, ...(reload ? { repriced_at_pay: true } : {}) } : result)\n } catch (err) {\n onShipping?.(null, err)\n }\n try {\n handle.send?.('payment-order-finalized', proceed)\n } catch {\n /* widget already gone */\n }\n if (reload) {\n try {\n // Show the amount the payment now carries before the shopper pays.\n handle.thawCheckout()\n } catch {\n /* widget already gone */\n }\n }\n }\n\n /** address-changed → freeze → UpdateNexiShipping → thaw. */\n private async repriceNexiShipping(\n handle: NexiCheckoutHandle,\n checkoutId: string,\n address: any,\n opts: CartQueryOptions,\n onShipping?: (result: NexiShippingUpdate | null, error?: unknown) => void,\n shippingId?: string,\n ): Promise<void> {\n const countryCode = String(address?.countryCode ?? address?.country ?? '')\n if (!countryCode) return\n try {\n handle.freezeCheckout()\n } catch {\n /* widget already gone */\n }\n try {\n const result = await gqlUpdateNexiShipping(\n {\n checkoutId,\n countryCode,\n postalCode: address?.postalCode ? String(address.postalCode) : undefined,\n shippingId,\n },\n opts,\n )\n if (result?.ok && result.shipping_id) this.nexiPreferredShipping = result.shipping_id\n onShipping?.(result)\n } catch (err) {\n onShipping?.(null, err)\n } finally {\n try {\n handle.thawCheckout()\n } catch {\n /* widget already gone */\n }\n }\n }\n\n /** Release the Dibs.Checkout listeners with the widget they belong to. */\n destroyNexi(): void {\n try {\n this.nexiHandle?.cleanup()\n } catch {\n /* noop */\n }\n this.nexiHandle = null\n this.nexiShippingContext = null\n this.nexiPreferredShipping = null\n this.nexiShippingPreview = null\n }\n\n /** Re-read the Nexi payment owned by a checkout. */\n async getNexiOrder(checkoutId: string, sponsorId?: number): Promise<NexiOrder | null> {\n const opts = await getCartGraphQLOptions(sponsorId ?? this.state?.sponsorId)\n return gqlGetNexiOrder(checkoutId, opts)\n }\n\n /**\n * Adyen: FORM-FIRST. Saves the shopper's form and shipping pick on the\n * checkout (Adyen collects neither), creates a session with that final\n * amount and mounts Adyen's Drop-in on it. A session is never updated —\n * after ANY change the caller destroys this mount and calls again.\n *\n * At \"Pay\" the backend only confirms that the session still pays for the\n * checkout; when it does not, Adyen is stopped and `onReplaced` tells the\n * caller to remount. Completion is asked of Adyen through the backend\n * (`GetAdyenPayment`) — the browser's own result is never the answer.\n */\n async mountAdyenCheckout(\n container: HTMLElement,\n sponsorId: number | undefined,\n formData: unknown,\n callbacks: {\n onCompleted: (payment: AdyenPayment | null, session: AdyenSession) => void\n onFailed: (result: AdyenResult, session: AdyenSession) => void\n /** The session no longer pays for the checkout (reason from the backend). */\n onReplaced: (reason: string) => void\n onError?: (error: unknown) => void\n },\n ): Promise<AdyenSession> {\n this.destroyAdyen()\n const { spId, checkoutId, emailVal, opts } = await this.prepareRedirectPayment(\n sponsorId,\n formData,\n { paymentMethod: 'Adyen' },\n )\n const session = await gqlCreatePaymentAdyen(\n {\n checkoutId,\n returnUrl: adyenReturnUrl({\n vio_payment: 'return',\n vio_method: ADYEN_RETURN_METHOD,\n vio_sponsor: spId,\n checkout_id: checkoutId,\n }),\n countryCode: getGlobalCountryCode(),\n channel: 'Web',\n email: emailVal,\n client: `web-sdk ${SDK_VERSION}`,\n },\n opts,\n )\n if (!session?.session_id) {\n throw new Error('[CheckoutManager] Adyen session was not created')\n }\n const theme = readVioTheme()\n this.adyenHandle = await mountAdyen(\n container,\n session,\n {\n onBeforePay: async () => {\n const verdict = await gqlConfirmAdyenPayment(\n { checkoutId, sessionId: session.session_id },\n opts,\n )\n if (verdict?.ok === true) return true\n callbacks.onReplaced(String(verdict?.reason ?? 'UNKNOWN'))\n return false\n },\n onCompleted: (result) => {\n void gqlGetAdyenPayment({ checkoutId, sessionResult: result?.sessionResult }, opts)\n .catch(() => null)\n .then((payment) => callbacks.onCompleted(payment, session))\n },\n onFailed: (result) => callbacks.onFailed(result, session),\n onError: (error) => callbacks.onError?.(error),\n },\n { theme: { accent: theme?.accent, radiusMd: theme?.radiusMd } },\n )\n return session\n }\n\n /** Unmount Drop-in. Safe to call when nothing is mounted. */\n destroyAdyen(): void {\n try {\n this.adyenHandle?.unmount()\n } catch {\n /* noop */\n }\n this.adyenHandle = null\n }\n\n /**\n * Outcome of the Adyen session a checkout owns. With `redirectResult` (the\n * return from Vipps, Klarna, Trustly or a redirect-3DS) the redirect is\n * finalised on the server.\n */\n async getAdyenPayment(\n checkoutId: string,\n proof: { sessionResult?: string; redirectResult?: string } = {},\n sponsorId?: number,\n ): Promise<AdyenPayment | null> {\n const opts = await getCartGraphQLOptions(sponsorId ?? this.state?.sponsorId)\n return gqlGetAdyenPayment({ checkoutId, ...proof }, opts)\n }\n\n /* eslint-enable @typescript-eslint/no-explicit-any */\n\n setAddress(address: CheckoutAddress): void {\n if (!this.state) return\n // Immutable update — a fresh object reference so reactive UIs (Lit\n // `@state`, which compares by identity) actually re-render.\n this.state = { ...this.state, address }\n this.emit()\n }\n\n selectPaymentMethod(method: PaymentMethod): void {\n if (!this.state) return\n // New reference (see setAddress) so the selection re-renders.\n this.state = { ...this.state, paymentMethod: method }\n this.emit()\n this.dispatchEvent(\n new CustomEvent<PaymentSelectDetail>('payment-select', {\n detail: { method, state: this.state },\n }),\n )\n }\n\n // MARK: - Apple Pay (Stripe Payment Request)\n\n /**\n * Which Stripe flow this channel offers: `native` pays on our own page,\n * `link` sends the shopper to a page hosted by Stripe. The channel's two\n * toggles decide it and the answer travels in the method's config\n * (api-microservice, `stripe-offer.ts`). A channel that predates that\n * field answers `link`, which is what every client did before.\n */\n /**\n * Does this channel's Vipps offer Express — the buy-now buttons that open\n * the app with address and delivery? Vio Commerce announces it as\n * `config.express` on the Vipps method, the way Stripe announces `mode`;\n * the seller switches it on its Vipps row. Unknown means yes: Express is\n * the default, and the backend refuses it with a reason if it cannot.\n */\n async getVippsExpressEnabled(sponsorId?: number): Promise<boolean> {\n try {\n const methods = await this.getAvailablePaymentMethods(sponsorId)\n const vipps = (\n methods as Array<{ name?: string; config?: Array<{ name?: string; value?: string }> }> | null\n )?.find((m) => String(m?.name ?? '').toLowerCase() === 'vipps')\n const express = vipps?.config?.find((c) => c?.name === 'express')?.value\n return express !== 'false'\n } catch {\n return true\n }\n }\n\n async getStripeMode(sponsorId?: number): Promise<'native' | 'link'> {\n try {\n const methods = await this.getAvailablePaymentMethods(sponsorId)\n const stripe = (\n methods as Array<{ name?: string; config?: Array<{ name?: string; value?: string }> }> | null\n )?.find((m) => String(m?.name ?? '').toLowerCase() === 'stripe')\n const mode = stripe?.config?.find((c) => c?.name === 'mode')?.value\n return mode === 'native' ? 'native' : 'link'\n } catch {\n return 'link'\n }\n }\n\n /**\n * Stripe's Payment Element, mounted on our own page for a checkout that is\n * ready to be paid. Creating it mints a PaymentIntent, so it happens when\n * the shopper asks for the payment step, never while they type.\n *\n * The order is not born here: `confirm()` only says what Stripe told the\n * browser. The `payment_intent.succeeded` webhook creates it server-side,\n * and the caller then reads the checkout to see it land.\n */\n async mountStripeCheckout(\n container: HTMLElement,\n sponsorId: number | undefined,\n formData: unknown,\n callbacks?: { onReady?: () => void; onLoadError?: (message: string) => void },\n ): Promise<{ handle: StripeElementHandle; intent: StripeIntent; checkoutId: string }> {\n this.destroyStripe()\n const { spId, checkoutId, opts } = await this.prepareRedirectPayment(sponsorId, formData, {\n paymentMethod: 'Stripe',\n })\n const minted = await createStripeIntent(checkoutId, opts)\n if (!minted?.client_secret) {\n throw new Error('[CheckoutManager] Stripe payment was not created')\n }\n // Stripe Connect: the account comes with the channel's Stripe config, the\n // same row shopcart charged on. Read from there (not from the mutation)\n // so this SDK works against a gateway that predates the field.\n const account = minted.stripe_account ?? (await this.resolveStripeConnectAccount(spId))\n const intent: StripeIntent = account ? { ...minted, stripe_account: account } : minted\n const theme = readVioTheme()\n const handle = await mountStripeElement(container, intent, {\n returnUrl: resolveHttpsReturnUrl(null, {\n vio_payment: 'success',\n vio_method: 'stripe',\n vio_sponsor: spId,\n checkout_id: checkoutId,\n }),\n theme: { accent: theme?.accent, radiusMd: theme?.radiusMd },\n onReady: callbacks?.onReady,\n onLoadError: callbacks?.onLoadError,\n })\n this.stripeHandle = handle\n return { handle, intent, checkoutId }\n }\n\n /** Unmount the Payment Element. Safe when nothing is mounted. */\n destroyStripe(): void {\n try {\n this.stripeHandle?.unmount()\n } catch {\n /* noop */\n }\n this.stripeHandle = null\n }\n\n /**\n * The Stripe publishable key for a sponsor, taken from its own commerce\n * channel (`GetAvailablePaymentMethods` → Stripe → config.publishableKey).\n *\n * The channel is the right source: the key belongs to the brand's Stripe\n * account, so two brands on one page each get theirs, and a host never has\n * to configure it. `Vio.init({ stripePublishableKey })` still wins when set,\n * which keeps existing integrations working and allows an override.\n */\n private async resolveStripePublishableKey(sponsorId?: number): Promise<string> {\n const cfg = Configuration.isInitialized ? Configuration.get() : null\n if (cfg?.stripePublishableKey) return cfg.stripePublishableKey\n if (this.applePayPublishableKey) return this.applePayPublishableKey\n try {\n // Memoised per sponsor upstream, so this is cheap on repeat calls.\n const methods = await this.getAvailablePaymentMethods(sponsorId)\n const stripe = (methods as Array<{ name?: string; config?: Array<{ name?: string; value?: string }> }> | null)\n ?.find((m) => String(m?.name ?? '').toLowerCase() === 'stripe')\n const key = stripe?.config?.find((c) => c?.name === 'publishableKey')?.value\n const account = stripe?.config?.find((c) => c?.name === 'stripeAccount')?.value\n this.stripeConnectAccount =\n typeof account === 'string' && account.startsWith('acct_') ? account : null\n if (typeof key === 'string' && key.startsWith('pk_')) {\n this.applePayPublishableKey = key\n return key\n }\n } catch {\n /* channel unreachable — treat as \"no Apple Pay\", never throw */\n }\n return ''\n }\n\n /**\n * Returns true if Apple Pay can be shown on this device + Stripe config.\n * Result is memoised — call `clearApplePayCache()` if config changes.\n */\n async isApplePayAvailable(country = 'NO'): Promise<boolean> {\n if (this.applePayAvailableCache !== null) return this.applePayAvailableCache\n const publishableKey = await this.resolveStripePublishableKey(this.state?.sponsorId)\n if (!publishableKey || !this.state) {\n this.applePayAvailableCache = false\n return false\n }\n const amount = toSmallestUnit(this.state.subtotal, this.state.currency)\n const available = await checkApplePayAvailability({\n publishableKey,\n connectedAccount: this.findStripeConnectAccount() ?? undefined,\n amount,\n currency: this.state.currency,\n country,\n label: 'Vio',\n })\n this.applePayAvailableCache = available\n return available\n }\n\n clearApplePayCache(): void {\n this.applePayAvailableCache = null\n }\n\n /**\n * Prepare Apple Pay for the product-page express button (no active checkout\n * needed). Pre-creates the Stripe PaymentRequest + resolves canMakePayment so\n * the returned `show()` can fire synchronously inside the tap (Apple blocks\n * the sheet if `show()` is reached after an await). `show()` resolves the\n * sheet, then dispatches `payment-complete` (→ confirmation) or\n * `payment-error`. `available` is true only when Apple Pay will actually work.\n */\n async prepareApplePayFor(\n amount: number,\n currency: string,\n country = 'NO',\n ): Promise<{ available: boolean; show: () => Promise<void> }> {\n const publishableKey = await this.resolveStripePublishableKey(this.state?.sponsorId)\n if (!publishableKey) return { available: false, show: async () => {} }\n const prepared = await prepareApplePay({\n publishableKey,\n connectedAccount:\n this.applePayConnectedAccount ?? this.findStripeConnectAccount() ?? undefined,\n amount: toSmallestUnit(amount, currency),\n currency,\n country,\n label: 'Vio',\n // Native Apple Pay shipping — same Standard/Express options as Klarna.\n shippingOptions: KLARNA_SHIPPING_OPTIONS.map((o) => ({\n id: o.id,\n label: o.method,\n detail: o.description,\n amount: o.price,\n })),\n // The real backend charge — sponsor resolved at authorize-time (the\n // product-detail button calls checkout.open() before show()).\n onAuthorize: (raw) => {\n const spId =\n this.state?.sponsorId ?? [...this.cartManager.getAllCarts().keys()][0]\n if (spId == null) {\n return Promise.reject(new Error('[VioCheckout] no sponsor for Apple Pay'))\n }\n return this.buildApplePayAuthorize(spId)(raw)\n },\n })\n return {\n available: prepared.available,\n show: async (): Promise<void> => {\n try {\n const result = await prepared.show()\n this.selectPaymentMethod('apple-pay')\n const state: CheckoutState =\n this.state ?? { sponsorId: 0, subtotal: amount, currency }\n this.dispatchEvent(\n new CustomEvent<PaymentCompleteDetail>('payment-complete', {\n detail: { method: 'apple-pay', state, result },\n }),\n )\n } catch (err) {\n if (typeof console !== 'undefined') {\n console.warn('[VioCheckout] Apple Pay express failed:', err)\n }\n this.dispatchEvent(\n new CustomEvent<PaymentErrorDetail>('payment-error', {\n detail: { method: 'apple-pay', error: describeError(err) },\n }),\n )\n }\n },\n }\n }\n\n /**\n * Prepare an Apple Pay express charge for an arbitrary amount (e.g. the whole\n * cart) with NO active checkout. Unlike `prepareApplePayFor`, the returned\n * `show()` RESOLVES with the result (or `null` on cancel/failure) and does\n * NOT dispatch the global `payment-complete` — so no checkout overlay appears.\n * The caller (the cart drawer) renders its own confirmation. `show()` must be\n * called synchronously inside the tap (Apple's user-gesture rule).\n */\n async prepareApplePayExpress(\n amount: number,\n currency: string,\n country = 'NO',\n sponsorId?: number,\n ): Promise<{ available: boolean; show: () => Promise<ApplePayResult | null> }> {\n const publishableKey = await this.resolveStripePublishableKey(sponsorId ?? this.state?.sponsorId)\n if (!publishableKey) return { available: false, show: async () => null }\n const spId =\n sponsorId ?? this.state?.sponsorId ?? [...this.cartManager.getAllCarts().keys()][0]\n const prepared = await prepareApplePay({\n publishableKey,\n connectedAccount:\n this.applePayConnectedAccount ?? this.findStripeConnectAccount() ?? undefined,\n amount: toSmallestUnit(amount, currency),\n currency,\n country,\n label: 'Vio',\n // Native Apple Pay shipping (same Standard/Express options as Klarna) —\n // selected inside the sheet, so it's not a separate checkout step.\n shippingOptions: KLARNA_SHIPPING_OPTIONS.map((o) => ({\n id: o.id,\n label: o.method,\n detail: o.description,\n amount: o.price,\n })),\n // The real backend charge, run inside the sheet's authorize event.\n ...(spId != null ? { onAuthorize: this.buildApplePayAuthorize(spId) } : {}),\n })\n return {\n available: prepared.available,\n show: async (): Promise<ApplePayResult | null> => {\n try {\n return await prepared.show()\n } catch (err) {\n if (typeof console !== 'undefined') {\n console.warn('[VioCheckout] cart Apple Pay express failed:', err)\n }\n return null\n }\n },\n }\n }\n\n /** The charge closure run inside the Apple Pay sheet's authorize event —\n * shared by the checkout button and the cart's express button. Fail-closed:\n * any failure throws and the sheet closes with failure, nothing confirmed. */\n private buildApplePayAuthorize(spId: number): (raw: ApplePayResult) => Promise<unknown> {\n return async (raw: ApplePayResult): Promise<unknown> => {\n let checkoutId = this.state?.checkoutId\n if (!checkoutId) {\n const created = await this.createCheckout(spId)\n checkoutId = created?.id ?? this.state?.checkoutId\n }\n if (!checkoutId) {\n throw new Error('[VioCheckout] could not obtain a checkout for Apple Pay')\n }\n const email = raw.payerEmail || this.state?.address?.email || ''\n // Record the method (+ email) on the checkout. Non-fatal: Confirm carries\n // the email too, and the charge is what decides the outcome.\n try {\n await this.updateCheckout(\n { checkoutId, paymentMethod: 'Apple Pay', ...(email ? { email } : {}) },\n spId,\n )\n } catch (err) {\n if (typeof console !== 'undefined') {\n console.warn('[VioCheckout] updateCheckout before Apple Pay confirm failed:', err)\n }\n }\n const gqlOpts = await getCartGraphQLOptions(spId)\n const createRes = await gqlCreatePaymentApplePay({ checkoutId }, gqlOpts)\n const gatewayId = String(createRes?.gateway_merchant_id ?? '')\n if (gatewayId.startsWith('pk_')) this.applePayPublishableKey = gatewayId\n else if (gatewayId.startsWith('acct_')) this.applePayConnectedAccount = gatewayId\n\n const addr = (raw.shippingAddress ?? {}) as Record<string, unknown>\n const str = (v: unknown): string => (typeof v === 'string' ? v : '')\n const lines = Array.isArray(addr.addressLine) ? (addr.addressLine as string[]) : []\n const fullName = str(addr.name) || raw.payerName || ''\n const shippingAddress = {\n address1: lines[0] || str(addr.line1) || '',\n address2: lines[1] || str(addr.line2) || '',\n city: str(addr.locality) || str(addr.city) || '',\n company: '',\n country: str(addr.country) || '',\n country_code: str(addr.countryCode) || getGlobalCountryCode(),\n first_name: str(addr.givenName) || fullName.split(' ')[0] || '',\n last_name: str(addr.familyName) || fullName.split(' ').slice(1).join(' ') || '',\n phone: str(addr.phone) || str(addr.phoneNumber) || raw.payerPhone || '',\n phone_code: '',\n province: str(addr.administrativeArea) || str(addr.state) || '',\n province_code: '',\n zip: str(addr.postalCode) || str(addr.postal_code) || '',\n }\n\n const confirmRes = await gqlConfirmPaymentApplePay(\n { checkoutId, applePayToken: raw.paymentMethodId, email, shippingAddress },\n gqlOpts,\n )\n const status = String(confirmRes?.status ?? '').toLowerCase()\n if (!confirmRes || CheckoutManager.APPLE_PAY_FAILED_STATUSES.has(status)) {\n throw new Error(\n `[VioCheckout] Apple Pay confirmation failed (status: ${confirmRes?.status ?? 'none'})`,\n )\n }\n // The buyer reference rides along as `result.confirmation.buyerRef` (analytics `buyer_id`),\n // the checkout it paid as `result.confirmation.checkoutId` (analytics `checkout_id`): the\n // cart's express button has no checkout of its own to name.\n const buyerRef = normalizeBuyerRef(confirmRes?.[BUYER_REF_FIELD])\n return {\n orderId: confirmRes?.order_id,\n status: confirmRes?.status,\n checkoutId,\n ...(buyerRef ? { buyerRef } : {}),\n }\n }\n }\n\n /** Backend statuses from ConfirmPaymentApplePay that mean the charge did\n * NOT go through — anything here fails the sheet (fail-closed). */\n private static readonly APPLE_PAY_FAILED_STATUSES = new Set([\n 'failed', 'declined', 'rejected', 'cancelled', 'canceled', 'error', 'expired',\n ])\n\n /**\n * Launches the Apple Pay sheet and charges server-side INSIDE the sheet's\n * authorize event (round-5 wiring, contract from the commerce backend):\n * 1. ensure a backend checkout exists (create if missing)\n * 2. UpdateCheckout(paymentMethod: \"Apple Pay\" + payer email)\n * 3. CreatePaymentApplePay → gateway hints (pk_/acct_ stored by prefix)\n * 4. ConfirmPaymentApplePay(token, email, shipping) → the REAL charge;\n * a failed/absent confirmation throws → the sheet closes with failure\n * Resolves null if the user closes the sheet. On success, dispatches\n * `payment-complete` with the backend order id in `result.confirmation`.\n */\n async startApplePay(options: {\n country?: string\n label?: string\n sponsorId?: number\n } = {}): Promise<ApplePayResult | null> {\n if (!this.state) throw new Error('[VioCheckout] no active checkout — call open() first')\n const spId = options.sponsorId ?? this.state.sponsorId\n const publishableKey = await this.resolveStripePublishableKey(spId)\n if (!publishableKey) {\n throw new Error(\n '[VioCheckout] No Stripe publishable key configured. Pass `stripePublishableKey` to Vio.init({ ... }).',\n )\n }\n const amount = toSmallestUnit(this.state.subtotal, this.state.currency)\n const onAuthorize = this.buildApplePayAuthorize(spId)\n\n const result = await showApplePaySheet({\n publishableKey,\n connectedAccount:\n this.applePayConnectedAccount ?? this.findStripeConnectAccount() ?? undefined,\n amount,\n currency: this.state.currency,\n country: options.country ?? 'NO',\n label: options.label ?? 'Vio',\n onAuthorize,\n })\n if (!result) return null // user closed the sheet — no event, nothing charged\n\n this.selectPaymentMethod('apple-pay')\n this.dispatchEvent(\n new CustomEvent<PaymentCompleteDetail>('payment-complete', {\n detail: { method: 'apple-pay', state: this.state, result },\n }),\n )\n return result\n }\n\n // MARK: - Klarna Express Checkout (Klarna Web SDK v2)\n\n /**\n * True if the Klarna Express button can be offered (clientId configured +\n * SDK loads). Memoised per active checkout. Never throws.\n */\n async isKlarnaExpressAvailable(): Promise<boolean> {\n if (this.klarnaAvailableCache !== null) return this.klarnaAvailableCache\n const cfg = Configuration.isInitialized ? Configuration.get() : null\n const clientId = cfg?.klarnaClientId ?? ''\n if (!clientId || !this.state) {\n this.klarnaAvailableCache = false\n return false\n }\n const available = await isKlarnaAvailable({\n clientId,\n locale: getGlobalLocale(),\n environment: cfg?.klarnaEnvironment,\n })\n this.klarnaAvailableCache = available\n return available\n }\n\n clearKlarnaCache(): void {\n this.klarnaAvailableCache = null\n }\n\n /**\n * Build the Klarna payment request from the active cart — amounts in the\n * currency's minor unit (øre/cents), one line item per cart line.\n */\n buildKlarnaPaymentRequest(): KlarnaPaymentRequestData {\n if (!this.state) throw new Error('[VioCheckout] no active checkout — call open() first')\n const currency = this.state.currency\n const lineItems: KlarnaLineItem[] = this.items.map((item) => {\n const unitPrice = toSmallestUnit(item.unitPrice, currency)\n return {\n name: item.name || item.brand || 'Produkt',\n quantity: item.quantity,\n unitPrice,\n totalAmount: unitPrice * item.quantity,\n reference: String(item.productId),\n ...(item.imageUrl ? { imageUrl: item.imageUrl } : {}),\n }\n })\n return {\n currency,\n amount: toSmallestUnit(this.state.subtotal, currency),\n supplementaryPurchaseData: { lineItems },\n }\n }\n\n /**\n * Mount the Klarna Express button into `container`. On a successful\n * authorization, fires `payment-complete` with the authorization token —\n * the host (or vio-backend) then creates the Klarna order server-side.\n *\n * Returns the button handle so the UI can unmount on teardown.\n */\n async mountKlarnaExpress(container: HTMLElement): Promise<KlarnaButtonHandle> {\n if (!this.state) throw new Error('[VioCheckout] no active checkout — call open() first')\n const cfg = Configuration.get()\n if (!cfg.klarnaClientId) {\n throw new Error(\n '[VioCheckout] No Klarna client id configured. Pass `klarnaClientId` to Vio.init({ ... }).',\n )\n }\n const pendingContext = this.buildKlarnaPendingContext()\n return mountKlarnaExpressButton({\n config: {\n clientId: cfg.klarnaClientId,\n locale: getGlobalLocale(),\n environment: cfg.klarnaEnvironment,\n },\n container,\n paymentRequest: this.buildKlarnaPaymentRequest(),\n pendingKey: KLARNA_PENDING_KEY,\n pendingContext,\n // POPUP path: the initiate() promise resolves in-page with the token.\n onAuthorize: (result) => {\n void this.completeKlarnaOrder(result.authorizationToken, pendingContext, result)\n },\n onError: (err) => {\n if (typeof console !== 'undefined') {\n console.warn('[VioCheckout] Klarna Express cancelled/error:', err)\n }\n // Surface the error in the UI (not just the console). Klarna's reject\n // payload is often a plain object, so serialise it instead of letting\n // String(err) collapse to \"[object Object]\" — we need the real reason\n // (e.g. validation field, unsupported initiationMode, blocked origin)\n // visible on screen while we stabilise the flow.\n this.dispatchEvent(\n new CustomEvent<PaymentErrorDetail>('payment-error', {\n detail: { method: 'klarna', error: describeError(err) },\n }),\n )\n },\n })\n }\n\n /**\n * Klarna Payments — classic widget flow (server client_token). Creates a\n * session on vio-backend, then mounts Klarna's inline widget into\n * `container`. Returns a handle to switch category and to authorize → which\n * on approval creates the order via the same backend /orders route as KEC.\n *\n * Unlike `mountKlarnaExpress`, this needs no public `klarnaClientId` and no\n * origin handshake — auth is the server-side API key.\n */\n async mountKlarnaPayments(\n container: HTMLElement,\n opts?: { withShipping?: boolean; shippingId?: string; category?: string },\n ): Promise<KlarnaPaymentsHandle> {\n if (!this.state) throw new Error('[VioCheckout] no active checkout — call open() first')\n const sponsorId = this.state.sponsorId\n\n // 1. Real per-supplier shippings from the backend cart. No static\n // fallback for Klarna anymore — fetchAvailableShippings now waits for\n // any in-flight cart mutation, so an empty result means the backend\n // genuinely has nothing, not a race; falling back to stale hardcoded\n // prices would be worse than surfacing that honestly.\n const shippings = await this.fetchAvailableShippings(sponsorId)\n\n // With shipping: add the CHOSEN shipping option as a shipping_fee line +\n // bump the total. (Klarna Payments doesn't render a picker; ours lives in\n // the checkout UI and re-mounts this widget with the new total on change.)\n const { ctx } = opts?.withShipping\n ? this.buildKlarnaInstantContext(opts.shippingId, shippings)\n : { ctx: this.buildKlarnaPendingContext() }\n\n // 2. Persist the chosen shipping on the backend cart.\n const selectedOpt = shippings.find((s) => s.id === opts?.shippingId) ?? shippings[0]\n if (selectedOpt?.id && selectedOpt?.supplierId) {\n try {\n await this.updateShippingsBySupplier(\n [{ shipping_id: selectedOpt.id, supplier_id: Number(selectedOpt.supplierId) }],\n sponsorId,\n )\n } catch (err) {\n if (typeof console !== 'undefined') {\n console.warn('[CheckoutManager] updateShippingsBySupplier failed during mount:', err)\n }\n }\n }\n\n // 3. Backend checkout (CreatePaymentKlarnaNative requires a checkout_id).\n let checkoutId = ctx.checkoutId ?? this.state.checkoutId\n try {\n const checkoutRes = await this.createCheckout(sponsorId)\n if (checkoutRes?.id) {\n checkoutId = checkoutRes.id\n ctx.checkoutId = checkoutRes.id\n }\n } catch (err) {\n if (typeof console !== 'undefined') {\n console.warn('[CheckoutManager] CreateCheckout before Klarna init failed:', err)\n }\n }\n if (!checkoutId) {\n throw new Error('[CheckoutManager] no backend checkout for the Klarna session')\n }\n\n // 4. Klarna Payments session via the commerce GraphQL (native flow).\n const address = this.state.address\n const activeCurrency = getGlobalCurrency()\n if (this.state) this.state = { ...this.state, currency: activeCurrency }\n ctx.currency = activeCurrency\n const variables = {\n checkoutId,\n countryCode: getGlobalCountryCode(),\n currency: activeCurrency,\n locale: getGlobalLocale(),\n returnUrl: resolveHttpsReturnUrl(null, {\n vio_payment: 'success',\n vio_method: 'klarna',\n vio_sponsor: sponsorId,\n checkout_id: checkoutId,\n }),\n intent: 'buy',\n customer: buildKlarnaCustomer(address),\n billingAddress: buildKlarnaAddress(address),\n shippingAddress: buildKlarnaAddress(address),\n autoCapture: true,\n }\n\n const json = await executeKlarnaGraphQL(\n CREATE_PAYMENT_KLARNA_NATIVE_MUTATION,\n variables,\n sponsorId,\n )\n const nativeRes = json?.data?.Payment?.CreatePaymentKlarnaNative\n if (!nativeRes || !nativeRes.client_token) {\n throw new Error('Klarna session creation failed: missing client_token')\n }\n if (typeof console !== 'undefined') {\n console.log(\n '[VioCheckout] CreatePaymentKlarnaNative payment_method_categories:',\n nativeRes.payment_method_categories,\n )\n }\n if (nativeRes.checkout_id) {\n ctx.checkoutId = nativeRes.checkout_id\n this.state = { ...this.state, checkoutId: nativeRes.checkout_id }\n }\n if (nativeRes.session_id) {\n ctx.sessionId = nativeRes.session_id\n this.state = { ...this.state, sessionId: nativeRes.session_id }\n }\n ctx.clientToken = nativeRes.client_token\n this.state = { ...this.state, clientToken: nativeRes.client_token }\n\n // 5. Mount the inline widget and load the first category.\n const widget = await createKlarnaPaymentsWidget({\n clientToken: nativeRes.client_token,\n sessionId: nativeRes.session_id,\n categories: nativeRes.payment_method_categories ?? [],\n category: opts?.category,\n container,\n })\n await widget.load()\n\n return {\n categories: widget.categories,\n shippings,\n get selected() {\n return widget.selected\n },\n load: (category?: string) => widget.load(category),\n authorize: async (category?: string): Promise<void> => {\n try {\n // The session already carries the order (country/currency/lines);\n // Klarna collects customer details in its widget. Address/customer\n // are passed as a best-effort supplement when we already have them\n // from the checkout form — Klarna's own widget can still fill gaps.\n const addr = buildKlarnaAddress(this.state?.address)\n const customer = buildKlarnaCustomer(this.state?.address)\n const authData = {\n ...(addr ? { billing_address: addr, shipping_address: addr } : {}),\n ...(customer ? { customer } : {}),\n }\n const token = await widget.authorize(category, authData)\n await this.completeKlarnaOrder(token, ctx, { authorizationToken: token })\n } catch (err) {\n if (typeof console !== 'undefined') {\n console.warn('[VioCheckout] Klarna Payments authorize failed:', err)\n }\n this.dispatchEvent(\n new CustomEvent<PaymentErrorDetail>('payment-error', {\n detail: { method: 'klarna', error: describeError(err) },\n }),\n )\n }\n },\n unmount: () => {\n try {\n container.innerHTML = ''\n } catch {\n /* already gone */\n }\n },\n }\n }\n\n /** True if the Klarna Payments widget lib can load (UI gate). */\n async klarnaPaymentsAvailable(): Promise<boolean> {\n return isKlarnaPaymentsAvailable()\n }\n\n /** Cart snapshot + chosen shipping line/amount, for express purchases. */\n private buildKlarnaInstantContext(\n shippingId?: string,\n availableShippings: KlarnaShippingOption[] = [],\n ): {\n ctx: KlarnaPendingContext\n shippingOptions: KlarnaShippingOption[]\n } {\n const base = this.buildKlarnaPendingContext()\n const options = availableShippings\n const shipping =\n (shippingId ? options.find((o) => o.id === shippingId) : undefined) ??\n options.find((o) => o.preselected) ??\n options[0]\n const orderLines = [...base.orderLines]\n if (shipping) {\n orderLines.push({\n name: `Frakt – ${shipping.method || shipping.name}`,\n quantity: 1,\n unit_price: shipping.price,\n total_amount: shipping.price,\n reference: `shipping:${shipping.id}`,\n type: 'shipping_fee',\n })\n }\n return {\n ctx: {\n ...base,\n orderLines,\n orderAmount: base.orderAmount + (shipping?.price ?? 0),\n },\n shippingOptions: options,\n }\n }\n\n /**\n * Express instant purchase — go straight to Klarna's own modal, no checkout\n * overlay. Creates a session (with shipping options), loads the widget into a\n * hidden container, then authorizes (which opens Klarna's confirm modal). On\n * approval creates the order → `payment-complete` (host shows confirmation);\n * on failure → `payment-error`. Call `open(sponsorId)` first.\n */\n async startKlarnaInstant(): Promise<void> {\n if (!this.state) throw new Error('[VioCheckout] no active checkout — call open() first')\n const sponsorId = this.state.sponsorId\n const shippings = await this.fetchAvailableShippings(sponsorId)\n const { ctx } = this.buildKlarnaInstantContext(undefined, shippings)\n\n // 1. Backend checkout + Klarna Payments session via commerce GraphQL.\n let clientToken: string\n let categories: KlarnaPaymentsCategory[]\n try {\n let checkoutId = ctx.checkoutId ?? this.state.checkoutId\n try {\n const checkoutRes = await this.createCheckout(sponsorId)\n if (checkoutRes?.id) {\n checkoutId = checkoutRes.id\n ctx.checkoutId = checkoutRes.id\n }\n } catch (err) {\n if (typeof console !== 'undefined') {\n console.warn('[CheckoutManager] CreateCheckout before Klarna instant failed:', err)\n }\n }\n if (!checkoutId) {\n throw new Error('[CheckoutManager] no backend checkout for the Klarna session')\n }\n\n const address = this.state.address\n const activeCurrency = getGlobalCurrency()\n this.state = { ...this.state, currency: activeCurrency }\n ctx.currency = activeCurrency\n const variables = {\n checkoutId,\n countryCode: getGlobalCountryCode(),\n currency: activeCurrency,\n locale: getGlobalLocale(),\n returnUrl: resolveHttpsReturnUrl(null, {\n vio_payment: 'success',\n vio_method: 'klarna',\n vio_sponsor: sponsorId,\n checkout_id: checkoutId,\n }),\n intent: 'buy',\n customer: buildKlarnaCustomer(address),\n billingAddress: buildKlarnaAddress(address),\n shippingAddress: buildKlarnaAddress(address),\n autoCapture: true,\n }\n\n const json = await executeKlarnaGraphQL(\n CREATE_PAYMENT_KLARNA_NATIVE_MUTATION,\n variables,\n sponsorId,\n )\n const nativeRes = json?.data?.Payment?.CreatePaymentKlarnaNative\n if (!nativeRes || !nativeRes.client_token) {\n throw new Error('Klarna instant session failed: missing client_token')\n }\n if (nativeRes.checkout_id) {\n ctx.checkoutId = nativeRes.checkout_id\n this.state = { ...this.state, checkoutId: nativeRes.checkout_id }\n }\n if (nativeRes.session_id) {\n ctx.sessionId = nativeRes.session_id\n this.state = { ...this.state, sessionId: nativeRes.session_id }\n }\n ctx.clientToken = nativeRes.client_token\n this.state = { ...this.state, clientToken: nativeRes.client_token }\n clientToken = nativeRes.client_token\n categories = nativeRes.payment_method_categories ?? []\n } catch (err) {\n this.dispatchEvent(\n new CustomEvent<PaymentErrorDetail>('payment-error', {\n detail: { method: 'klarna', error: describeError(err) },\n }),\n )\n return\n }\n\n // 2. Hidden container → load → authorize (opens Klarna's own modal).\n const container = document.createElement('div')\n container.setAttribute('aria-hidden', 'true')\n container.style.cssText =\n 'position:fixed;left:-9999px;top:0;width:1px;height:1px;overflow:hidden;'\n document.body.appendChild(container)\n try {\n const widget = await createKlarnaPaymentsWidget({\n clientToken,\n sessionId: ctx.sessionId,\n categories,\n container,\n })\n await widget.load()\n const token = await widget.authorize()\n await this.completeKlarnaOrder(token, ctx, { authorizationToken: token })\n } catch (err) {\n if (typeof console !== 'undefined') {\n console.warn('[VioCheckout] Klarna instant failed:', err)\n }\n this.dispatchEvent(\n new CustomEvent<PaymentErrorDetail>('payment-error', {\n detail: { method: 'klarna', error: describeError(err) },\n }),\n )\n } finally {\n try {\n container.remove()\n } catch {\n /* already gone */\n }\n }\n }\n\n /**\n * REDIRECT path: call once on app load. If a Klarna purchase was launched\n * (pending context persisted) and we're back with a token — from the URL or\n * the SDK's resumed `complete` event — finish creating the order + confirm.\n */\n async resumeKlarnaReturn(): Promise<void> {\n if (typeof sessionStorage === 'undefined') return\n const raw = sessionStorage.getItem(KLARNA_PENDING_KEY)\n if (!raw) return\n let pending: KlarnaPendingContext\n try {\n pending = JSON.parse(raw) as KlarnaPendingContext\n } catch {\n sessionStorage.removeItem(KLARNA_PENDING_KEY)\n return\n }\n\n // 1) Token already in the URL (most redirect flows append it).\n const fromUrl = readKlarnaTokenFromUrl()\n if (fromUrl) {\n cleanUrlParams([fromUrl.param])\n await this.completeKlarnaOrder(fromUrl.token, pending, { authorizationToken: fromUrl.token })\n return\n }\n\n // No recognised token param — log what Klarna actually returned so the\n // param name can be mapped if the SDK `complete` event doesn't fire.\n if (typeof window !== 'undefined' && typeof console !== 'undefined' && window.location.search) {\n console.warn(\n '[VioCheckout] Klarna return: no known token param. URL was:',\n window.location.search,\n )\n }\n\n // 2) Otherwise let the SDK resume its session and fire `complete`.\n const cfg = Configuration.isInitialized ? Configuration.get() : null\n if (!cfg?.klarnaClientId) return\n await listenForKlarnaCompletion({\n config: { clientId: cfg.klarnaClientId, locale: getGlobalLocale(), environment: cfg.klarnaEnvironment },\n onComplete: (result) => {\n void this.completeKlarnaOrder(result.authorizationToken, pending, result)\n },\n onError: (err) => {\n if (typeof console !== 'undefined') {\n console.warn('[VioCheckout] Klarna resume error:', err)\n }\n },\n })\n }\n\n /** Snapshot of the active cart for redirect recovery (minor units). */\n private buildKlarnaPendingContext(): KlarnaPendingContext {\n if (!this.state) throw new Error('[VioCheckout] no active checkout')\n const currency = this.state.currency\n return {\n sponsorId: this.state.sponsorId,\n currency,\n orderAmount: toSmallestUnit(this.state.subtotal, currency),\n orderLines: this.items.map((item) => {\n const unitPrice = toSmallestUnit(item.unitPrice, currency)\n return {\n name: item.name || item.brand || 'Produkt',\n quantity: item.quantity,\n unit_price: unitPrice,\n total_amount: unitPrice * item.quantity,\n reference: String(item.productId),\n }\n }),\n }\n }\n\n /**\n * POST the token + order lines to vio-backend (it holds the secret API key\n * and creates the real Klarna order). On success → `payment-complete`; on\n * failure → `payment-error`. Idempotent: clears the pending key so the\n * popup and redirect paths can't double-fire.\n */\n private async completeKlarnaOrder(\n authorizationToken: string,\n ctx: KlarnaPendingContext,\n result: KlarnaAuthorizeResult,\n ): Promise<void> {\n // Idempotency guard — first caller wins (also without sessionStorage).\n if (this.klarnaOrderInFlight) return\n this.klarnaOrderInFlight = true\n // A token can only be confirmed once — a retry with an already-confirmed\n // token (network blip after a successful confirm) would create a second\n // order with autoCapture: double charge.\n if (\n typeof sessionStorage !== 'undefined' &&\n sessionStorage.getItem('vio.klarna.confirmed.v1') === authorizationToken\n ) {\n this.klarnaOrderInFlight = false\n return\n }\n try {\n const checkoutId =\n ctx?.checkoutId ?? this.state?.checkoutId ?? String(ctx?.sponsorId ?? this.state?.sponsorId ?? '')\n const address = this.state?.address\n const variables = {\n checkoutId,\n authorizationToken,\n autoCapture: true,\n billingAddress: buildKlarnaAddress(address),\n shippingAddress: buildKlarnaAddress(address),\n customer: buildKlarnaCustomer(address),\n }\n\n // Sent again without `buyer_ref` only when the gateway refused the\n // selection (nothing ran) — a confirmation that ran is never repeated.\n const json = await withBuyerRef((withRef) =>\n executeKlarnaGraphQL(\n confirmPaymentKlarnaNativeMutation(withRef),\n variables,\n ctx?.sponsorId ?? this.state?.sponsorId,\n ),\n )\n const confirmRes = json?.data?.Payment?.ConfirmPaymentKlarnaNative\n if (!confirmRes) {\n throw new Error('Klarna order confirmation failed: missing response data')\n }\n const orderData = confirmRes.order || confirmRes\n // The buyer reference (shopcart's hash of the email), for analytics `buyer_id`.\n const buyerRef = normalizeBuyerRef(confirmRes[BUYER_REF_FIELD])\n\n // Success: only NOW is the pending context consumed (keeping it until\n // here lets the redirect path retry a confirm that never ran).\n if (typeof sessionStorage !== 'undefined') {\n sessionStorage.setItem('vio.klarna.confirmed.v1', authorizationToken)\n sessionStorage.removeItem(KLARNA_PENDING_KEY)\n }\n\n // Synthesize a checkout state for the confirmation if the live one was\n // lost to a redirect reload.\n const state: CheckoutState =\n this.state ?? { sponsorId: ctx.sponsorId, subtotal: ctx.orderAmount, currency: ctx.currency }\n this.dispatchEvent(\n new CustomEvent<PaymentCompleteDetail>('payment-complete', {\n detail: {\n method: 'klarna',\n state,\n // chargedTotal in MAJOR units (incl. shipping for express) for the\n // confirmation screen. ctx.orderAmount is minor (øre) → /100.\n // Prefer the amount Klarna actually charged (includes shipping in\n // every flow); the local ctx misses shipping outside express.\n result: {\n ...result,\n order: orderData,\n chargedTotal:\n typeof orderData?.order_amount === 'number'\n ? orderData.order_amount / 100\n : ctx.orderAmount / 100,\n ...(buyerRef ? { buyerRef } : {}),\n },\n },\n }),\n )\n } catch (err) {\n if (typeof console !== 'undefined') {\n console.error('[VioCheckout] Klarna order creation failed:', err)\n }\n this.dispatchEvent(\n new CustomEvent<PaymentErrorDetail>('payment-error', {\n detail: { method: 'klarna', error: err instanceof Error ? err.message : String(err) },\n }),\n )\n } finally {\n this.klarnaOrderInFlight = false\n }\n }\n\n // MARK: - Accessors\n\n get currentState(): CheckoutState | null {\n return this.state\n }\n\n get items(): CartLineItem[] {\n if (!this.state) return []\n return this.cartManager.getCart(this.state.sponsorId)?.items ?? []\n }\n\n // MARK: - Internals\n\n /**\n * Resolve the Stripe Connect account for the active sponsor — for now\n * pulled from bootstrap cache if present. Returns undefined if not set\n * (Stripe will route to the platform account in that case).\n */\n private findStripeConnectAccount(): string | undefined {\n // Stripe Connect (ADR-0022): recorded from the channel's Stripe config\n // (`stripeAccount`) whenever the publishable key is resolved.\n return this.stripeConnectAccount ?? undefined\n }\n\n /** The sponsor's connected account, read fresh from its channel config. */\n private async resolveStripeConnectAccount(sponsorId?: number): Promise<string | undefined> {\n try {\n const methods = await this.getAvailablePaymentMethods(sponsorId)\n const stripe = (methods as Array<{ name?: string; config?: Array<{ name?: string; value?: string }> }> | null)\n ?.find((m) => String(m?.name ?? '').toLowerCase() === 'stripe')\n const account = stripe?.config?.find((c) => c?.name === 'stripeAccount')?.value\n return typeof account === 'string' && account.startsWith('acct_') ? account : undefined\n } catch {\n return undefined\n }\n }\n\n private emit(): void {\n this.dispatchEvent(\n new CustomEvent<CheckoutChangeDetail>('change', { detail: { state: this.state } }),\n )\n }\n}\n\n/**\n * Stripe expects amounts in the smallest currency unit. NOK/SEK/DKK/EUR/USD\n * are all hundredths (øre, öre, øre, cents, cents). JPY is the exception\n * (no fractional unit).\n */\nfunction toSmallestUnit(amount: number, currency: string): number {\n const zeroDecimal = new Set(['JPY', 'KRW', 'VND'])\n if (zeroDecimal.has(currency.toUpperCase())) return Math.round(amount)\n return Math.round(amount * 100)\n}\n","/**\n * The `client` block — the standard context of the visit (EVENTS_CONTRACT\n * \"client\", 2026-10-19): language, where the session landed from (the\n * referrer and `utm_*` of the LANDING page, remembered for the session),\n * screen size and time zone. What the collector derives from the request\n * itself — device type, OS, browser, country — is NOT sent: no User-Agent\n * parsing here, no duplicate of what the server knows better.\n *\n * Pure like `content.ts`: everything takes the globals it reads (defaults to\n * the real ones), never throws, and answers `{}` where there is no browser\n * (SSR, old engines). Capped to the collector's limits in ONE place: an\n * over-long value is cut — none of these is an identity, so a cut referrer\n * is still the right dimension.\n *\n * Landing memory: the first page of a session writes its referrer and utm\n * parameters to `sessionStorage`; later pages read them back, so an event on\n * page three still says the visit came from the newsletter — their own\n * `document.referrer` (an internal page) is never a source. The referrer is\n * kept as origin + path (no query, no fragment: a referrer's query is its\n * tracking tail, not where the visit came from) and dropped altogether when\n * it is this same host (a self-referral says nothing about the entry). A URL\n * with utm parameters is a new landing (another campaign click) that replaces\n * the memory — unless it was reached from this same host, i.e. an internal\n * link that propagates utm, which keeps the landing that was. Without\n * storage, or without consent to persist, each page stands alone.\n */\n\nimport { originAndPath } from '../content.js'\n\nexport interface ClientContext {\n language?: string\n referrer?: string\n utm_source?: string\n utm_medium?: string\n utm_campaign?: string\n utm_term?: string\n utm_content?: string\n screen_w?: number\n screen_h?: number\n tz?: string\n}\n\nexport const UTM_KEYS = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content'] as const\nexport type UtmKey = (typeof UTM_KEYS)[number]\n\n/** The collector's caps (vio-analytics `analytics-schema.ts`, `analyticsClientSchema`). */\nexport const CLIENT_LANGUAGE_MAX_LENGTH = 16\nexport const CLIENT_REFERRER_MAX_LENGTH = 2_048\nexport const CLIENT_UTM_MAX_LENGTH = 128\nexport const CLIENT_TZ_MAX_LENGTH = 64\nexport const CLIENT_SCREEN_MAX = 65_535\n/** Commerce's cap for the landing page on the order's entry context (`entry.landing_url`, ADR-0035). */\nexport const CLIENT_LANDING_URL_MAX_LENGTH = 2_048\n\n/** Where the session remembers its landing (per tab, like the browser's own session). */\nexport const LANDING_KEY = 'vio.landing.v1'\n\n/**\n * What a session remembers of the page it landed on. `url` is the landing\n * page itself — origin + path, like the referrer: no query (the utm are kept\n * apart, the rest is a tracking tail), no fragment — for the order's entry\n * context; the events do not carry it (the collector derives the landing).\n */\nexport interface Landing {\n referrer?: string\n utm?: Partial<Record<UtmKey, string>>\n url?: string\n}\n\nexport interface StorageLike {\n getItem(key: string): string | null\n setItem(key: string, value: string): void\n removeItem?(key: string): void\n}\n\n/** The globals the block is read from — injectable for tests; defaults to the real ones. */\nexport interface ClientEnvironment {\n navigator?: { language?: unknown } | null\n document?: { referrer?: unknown } | null\n location?: { search?: unknown; host?: unknown; href?: unknown } | null\n screen?: { width?: unknown; height?: unknown } | null\n /** The session memory for the landing; `null` = none (SSR, private mode, blocked). */\n storage?: StorageLike | null\n /** The time zone; defaults to `Intl.DateTimeFormat().resolvedOptions().timeZone`. */\n timeZone?: () => unknown\n}\n\nexport function defaultClientEnvironment(): ClientEnvironment {\n return {\n navigator: typeof navigator !== 'undefined' ? navigator : null,\n document: typeof document !== 'undefined' ? document : null,\n location: typeof location !== 'undefined' ? location : null,\n screen: typeof screen !== 'undefined' ? screen : null,\n storage: sessionStorageOrNull(),\n timeZone: () => Intl.DateTimeFormat().resolvedOptions().timeZone,\n }\n}\n\n/**\n * The landing of this session: what is remembered — unless this page is a\n * landing itself (utm parameters in its URL, reached from outside this host)\n * or nothing is remembered yet, when this page's referrer and utm are taken\n * (and, with `persist`, kept).\n */\nexport function resolveLanding(env: ClientEnvironment = defaultClientEnvironment(), persist = true): Landing {\n try {\n const utm = utmOf(env.location?.search)\n const raw = text(env.document?.referrer)\n const internal = isSameHost(raw, env.location?.host)\n const stored = readLanding(env.storage)\n // An internal link that carries utm is not a new entry to the site.\n if ((utm === undefined || internal) && stored) return stored\n const landing: Landing = {}\n const referrer = internal ? undefined : landingReferrer(raw)\n if (referrer) landing.referrer = referrer\n if (utm) landing.utm = utm\n const url = landingUrl(env.location?.href)\n if (url) landing.url = url\n if (persist) writeLanding(env.storage, landing)\n return landing\n } catch {\n return {}\n }\n}\n\n/** A referrer as the landing keeps it: origin + path, no query, no fragment; capped (`originAndPath`, content.ts). */\nexport function landingReferrer(raw: unknown): string | undefined {\n return originAndPath(raw, CLIENT_REFERRER_MAX_LENGTH)\n}\n\n/** The landing page as the landing keeps it: origin + path, no query, no fragment; capped. */\nexport function landingUrl(raw: unknown): string | undefined {\n return originAndPath(raw, CLIENT_LANDING_URL_MAX_LENGTH)\n}\n\n/**\n * The landing this session REMEMBERS — what was written by the first page —\n * or null when nothing is stored (no storage, no consent, analytics never\n * started). Read only: for the order's entry context, which must not take the\n * page the shopper pays on for the page they came in through.\n */\nexport function storedLanding(storage: StorageLike | null | undefined = defaultClientEnvironment().storage): Landing | null {\n return readLanding(storage)\n}\n\n/** True when the referrer's host is this page's host (`location.host`, port included). */\nexport function isSameHost(referrer: unknown, host: unknown): boolean {\n const value = text(referrer)\n const own = text(host)\n if (!value || !own) return false\n try {\n return new URL(value).host.toLowerCase() === own.toLowerCase()\n } catch {\n return false\n }\n}\n\n/** Remember a landing resolved earlier without persisting (consent granted after the first event). */\nexport function persistLanding(\n landing: Landing,\n storage: StorageLike | null | undefined = defaultClientEnvironment().storage,\n): void {\n writeLanding(storage, landing)\n}\n\n/** Forget the landing (consent withdrawn). */\nexport function removeLanding(storage: StorageLike | null | undefined = defaultClientEnvironment().storage): void {\n try {\n storage?.removeItem?.(LANDING_KEY)\n } catch {\n /* blocked */\n }\n}\n\n/** The block for the wire — read once per page load by the manager and reused on every event. */\nexport function resolveClientContext(\n env: ClientEnvironment = defaultClientEnvironment(),\n landing: Landing = resolveLanding(env),\n): ClientContext {\n const out: ClientContext = {}\n try {\n const language = cut(text(env.navigator?.language), CLIENT_LANGUAGE_MAX_LENGTH)\n if (language) out.language = language\n const referrer = cut(landing.referrer, CLIENT_REFERRER_MAX_LENGTH)\n if (referrer) out.referrer = referrer\n for (const key of UTM_KEYS) {\n const value = cut(landing.utm?.[key], CLIENT_UTM_MAX_LENGTH)\n if (value) out[key] = value\n }\n const w = dimension(env.screen?.width)\n const h = dimension(env.screen?.height)\n if (w !== undefined) out.screen_w = w\n if (h !== undefined) out.screen_h = h\n const tz = cut(text(safeCall(env.timeZone)), CLIENT_TZ_MAX_LENGTH)\n if (tz) out.tz = tz\n } catch {\n /* a getter that throws: what was read so far goes out */\n }\n return out\n}\n\n/** The utm parameters of a URL's query, capped; `undefined` when it has none. */\nexport function utmOf(search: unknown): Partial<Record<UtmKey, string>> | undefined {\n let params: URLSearchParams\n try {\n params = new URLSearchParams(typeof search === 'string' ? search : '')\n } catch {\n return undefined\n }\n const out: Partial<Record<UtmKey, string>> = {}\n let any = false\n for (const key of UTM_KEYS) {\n const value = cut(text(params.get(key)), CLIENT_UTM_MAX_LENGTH)\n if (value) {\n out[key] = value\n any = true\n }\n }\n return any ? out : undefined\n}\n\nfunction readLanding(storage: StorageLike | null | undefined): Landing | null {\n try {\n const raw = storage?.getItem(LANDING_KEY)\n if (!raw) return null\n const parsed = JSON.parse(raw) as unknown\n if (!parsed || typeof parsed !== 'object') return null\n const p = parsed as { referrer?: unknown; utm?: unknown; url?: unknown }\n const landing: Landing = {}\n const referrer = cut(text(p.referrer), CLIENT_REFERRER_MAX_LENGTH)\n if (referrer) landing.referrer = referrer\n const url = cut(text(p.url), CLIENT_LANDING_URL_MAX_LENGTH)\n if (url) landing.url = url\n if (p.utm && typeof p.utm === 'object') {\n const utm: Partial<Record<UtmKey, string>> = {}\n let any = false\n for (const key of UTM_KEYS) {\n const value = cut(text((p.utm as Record<string, unknown>)[key]), CLIENT_UTM_MAX_LENGTH)\n if (value) {\n utm[key] = value\n any = true\n }\n }\n if (any) landing.utm = utm\n }\n return landing\n } catch {\n return null\n }\n}\n\nfunction writeLanding(storage: StorageLike | null | undefined, landing: Landing): void {\n try {\n storage?.setItem(LANDING_KEY, JSON.stringify(landing))\n } catch {\n /* private mode / blocked / quota — the page stands alone */\n }\n}\n\nfunction sessionStorageOrNull(): StorageLike | null {\n try {\n return typeof sessionStorage !== 'undefined' && sessionStorage ? sessionStorage : null\n } catch {\n return null // a sandboxed frame throws on access\n }\n}\n\nfunction text(value: unknown): string | undefined {\n if (value === undefined || value === null) return undefined\n const s = String(value).trim()\n return s ? s : undefined\n}\n\nfunction cut(value: string | undefined, max: number): string | undefined {\n if (value === undefined) return undefined\n return value.length > max ? value.slice(0, max) : value\n}\n\n/** A screen dimension as the collector takes it: a non-negative integer ≤ 65 535. */\nfunction dimension(value: unknown): number | undefined {\n const n = typeof value === 'number' ? value : Number(value)\n if (!Number.isFinite(n) || n < 0) return undefined\n return Math.min(Math.floor(n), CLIENT_SCREEN_MAX)\n}\n\nfunction safeCall(fn: (() => unknown) | undefined): unknown {\n try {\n return fn ? fn() : undefined\n } catch {\n return undefined\n }\n}\n","/**\n * The cart split per campaign (ADR-0034) — ONE rule, shared by the SDK's own\n * `begin_checkout` / `purchase` events, by `Vio.cartSlices()` and so by any\n * host with its own analytics sink (Vev).\n *\n * Every unit of every line goes to the campaign of its origin — the one the\n * place showed when it was added — and units without one to the campaign the\n * caller's rule resolves for the line's sponsor (`resolveCampaign`). One slice\n * per campaign: its items (quantities from the origins, merged per product +\n * variant), its value with two decimals, and `slot` / `contentId` /\n * `sponsorId` only when they are the same for the whole slice. A cart with\n * one campaign is one slice. Pure; never throws on odd lines.\n */\n\nimport type { AnalyticsItemInput } from '../analytics/analytics-manager.js'\nimport { lineOrigins } from './cart-manager.js'\nimport type { CartLineItem } from './types.js'\n\n/** An item of a slice — the analytics item shape (ids as given, normalized on the wire). */\nexport type VioItem = AnalyticsItemInput\n\n/** One campaign's share of the cart. */\nexport interface CartSlice {\n campaignId?: number\n sponsorId?: number\n slot?: string\n contentId?: string\n items: VioItem[]\n value: number\n currency?: string\n /** 1-based position of this slice and how many there are. */\n slice: number\n slices: number\n}\n\n/** The campaign of a unit without an explicit one: the caller's rule (slot assignment → sponsor → default). */\nexport type ResolveCampaign = (slot: string | undefined, sponsorId: number) => number | undefined\n\nexport function cartSlicesFrom(\n lines: ReadonlyArray<CartLineItem>,\n resolveCampaign: ResolveCampaign,\n fallbackCurrency?: string,\n): CartSlice[] {\n if (!Array.isArray(lines) || lines.length === 0) return []\n const slices = new Map<\n string,\n {\n campaignId?: number\n sponsors: Set<number>\n slots: Set<string>\n contents: Set<string>\n items: Map<string, VioItem>\n value: number\n currency?: string\n }\n >()\n for (const line of lines) {\n if (!line || typeof line !== 'object') continue\n const sponsorId = Number(line.sponsorId)\n const unitPrice = Number(line.unitPrice) || 0\n for (const origin of lineOrigins(line)) {\n let campaignId = origin.campaignId\n if (campaignId === undefined) {\n try {\n campaignId = resolveCampaign(origin.slot, sponsorId)\n } catch {\n campaignId = undefined\n }\n }\n const key = campaignId === undefined ? 'default' : String(campaignId)\n let slice = slices.get(key)\n if (!slice) {\n slice = {\n campaignId,\n sponsors: new Set(),\n slots: new Set(),\n contents: new Set(),\n items: new Map(),\n value: 0,\n currency: line.currency || fallbackCurrency,\n }\n slices.set(key, slice)\n }\n if (Number.isFinite(sponsorId)) slice.sponsors.add(sponsorId)\n if (origin.slot) slice.slots.add(origin.slot)\n if (origin.contentId) slice.contents.add(origin.contentId)\n const itemKey = `${line.productId}::${line.variantId ?? ''}`\n const item = slice.items.get(itemKey)\n if (item) item.quantity = (item.quantity ?? 0) + origin.quantity\n else {\n slice.items.set(itemKey, {\n productId: line.productId,\n name: line.name,\n brand: line.brand,\n variantId: line.variantId,\n price: unitPrice,\n quantity: origin.quantity,\n })\n }\n slice.value += unitPrice * origin.quantity\n }\n }\n const list = [...slices.values()]\n return list.map((s, i) => ({\n campaignId: s.campaignId,\n sponsorId: s.sponsors.size === 1 ? [...s.sponsors][0] : undefined,\n slot: s.slots.size === 1 ? [...s.slots][0] : undefined,\n contentId: s.contents.size === 1 ? [...s.contents][0] : undefined,\n items: [...s.items.values()],\n value: Math.round(s.value * 100) / 100,\n currency: s.currency,\n slice: i + 1,\n slices: list.length,\n }))\n}\n\n/** True when at least one unit of these lines names its campaign itself (an origin with `campaignId`). */\nexport function hasExplicitCampaign(lines: ReadonlyArray<CartLineItem>): boolean {\n return lines.some((line) => lineOrigins(line).some((o) => o.campaignId !== undefined))\n}\n","/**\n * Vio.analytics — the web SDK's half of the Vio Analytics pipeline.\n *\n * Events flow to the Vio collector (`POST <eventsBase>/v1/events`, repo\n * vio-live/vio-analytics) which owns raw storage (ClickHouse) and vendor\n * fan-out (Mixpanel today). THE SDK NEVER TALKS TO VENDORS — swapping or\n * dropping a vendor is a server-side change, zero client releases.\n * Wire contract: vio-analytics `docs/EVENTS_CONTRACT.md` (v1, snake_case).\n *\n * Design rules:\n * - SIDE-EFFECT-FREE MODULE. Nothing runs at import time (tsup/tree-shaking\n * contract, see lessons/web-sdk-tsup-singleton-and-build). Listeners are\n * installed by an explicit `Vio.analytics.start()`.\n * - `track()` works BEFORE `Vio.init()` — events queue and flush once the\n * SDK is configured (transport resolves at flush time, not at track time).\n * - SSR-safe: without `window` every call is a silent no-op.\n * - Retries are safe: `event_id` is stable per event, the collector\n * dedupes. Queue is bounded (drop-oldest) so a dead collector can never\n * grow memory unbounded.\n * - Anti-double-count: the SDK only reports what the server can't see.\n * Votes/participations are server truth; `ad_activation`/`cart_intent`\n * are mirrored server-side, never from here.\n *\n * Three sinks, matching the Vev precedent (vio-vev analytics.ts, which\n * becomes an adapter over this in F3):\n * 1. collector (default ON once started)\n * 2. window.dataLayer — GA4/GTM (opt-in `start({ dataLayer: true })`,\n * the publisher-facing feature; NOT part of the Vio pipeline)\n * 3. `vio:analytics` DOM event — always when started (inspector/bridges)\n */\n\nimport { Configuration } from '../configuration.js'\nimport { CONTENT_ID_MAX_LENGTH, CONTENT_TITLE_MAX_LENGTH, capContentUrl, resolveContent, type ContentRef } from '../content.js'\nimport {\n activeCampaignEntry,\n assignmentApplies,\n findSlotAssignmentDetail,\n sponsorCampaignEntry,\n toNumber,\n type CampaignHint,\n} from '../slots.js'\nimport { SDK_VERSION } from '../version.js'\nimport { normalizeBuyerRef } from '../buyer-ref.js'\nimport {\n persistLanding,\n removeLanding,\n resolveClientContext,\n resolveLanding,\n type ClientContext,\n type Landing,\n} from './client-context.js'\nimport type { CartManager, CartChangeDetail } from '../cart/cart-manager.js'\nimport { cartSlicesFrom, hasExplicitCampaign, type CartSlice } from '../cart/slices.js'\nimport type { CartLineItem } from '../cart/types.js'\nimport type { CheckoutReference } from '../api/cart-queries.js'\nimport type { BootstrapCampaignEntry, BootstrapResponse } from '../types.js'\nimport type { CheckoutSponsor } from '../sponsor-identity.js'\n\n// ── Taxonomy (client-side subset of contract v1) ────────────────────────────\n\nexport const ANALYTICS_EVENT_NAMES = [\n // commerce (GA4-compatible)\n 'view_item_list',\n 'select_item',\n 'view_item',\n 'add_to_cart',\n 'remove_from_cart',\n 'view_cart',\n 'begin_checkout',\n 'purchase',\n // engagement\n 'component_impression',\n 'component_click',\n 'ad_impression',\n 'ad_click',\n 'poll_impression',\n 'contest_impression',\n // session\n 'session_start',\n 'session_end',\n // diagnóstico — lo que salió MAL (ver EVENTS_CONTRACT.md)\n 'checkout_error',\n 'sdk_error',\n] as const\n\nexport type AnalyticsEventName = (typeof ANALYTICS_EVENT_NAMES)[number]\n\n/** Camel-case for DX; mapped to the snake_case wire format at build time. */\nexport interface AnalyticsContext {\n campaignId?: number\n broadcastId?: string\n campaignComponentId?: number\n appPlacementId?: number\n locationId?: string\n componentTemplateId?: string\n sponsorId?: number\n activationId?: number\n contentUrl?: string\n /**\n * The host's own id for the piece of content the component sits in — an\n * article id in a CMS, a page id in a site builder. Carried verbatim so the\n * host can join Vio's funnel back onto its own per-article reporting\n * (revenue stops being an estimate). Left alone by the SDK.\n */\n contentId?: string | number\n /** Human-readable content snapshot; auto-filled from document.title. */\n contentTitle?: string\n /** Código corto del fallo (`sdk_error` / `checkout_error`). */\n errorCode?: string\n variant?: string\n /**\n * The slot (ADR-0027) the component sits in — its `vio-slot`. Attribution\n * follows it: the event's `campaign_id` is the campaign assigned to the slot\n * right now, before the sponsor rule. On the wire it fills `location_id`\n * when no explicit `locationId` is given (a slot IS a location id to the\n * campaigns service).\n */\n slot?: string\n}\n\nexport interface AnalyticsItemInput {\n productId: number | string\n name?: string\n brand?: string\n variantId?: number | string\n price?: number\n quantity?: number\n}\n\nexport interface AnalyticsCommerce {\n items?: AnalyticsItemInput[]\n value?: number\n currency?: string\n /**\n * `order_id` on the wire. On a `purchase` it is Vio's order number (`4415`,\n * the number the dashboard and Commerce's cancellations use), else the\n * checkout id standing in for it (`props.order_id_kind` says which).\n */\n orderId?: string\n /** `checkout_id` on the wire: Vio's checkout id (uuid). Always on the SDK's own `purchase`. */\n checkoutId?: string\n paymentMethod?: string\n /**\n * The buyer reference (`buyer_id` on the wire): shopcart's `buyer_ref`, a\n * keyed hash of the buyer's email — one person, one ref across orders and\n * devices, nothing reversible. Never an email (see core/buyer-ref.ts).\n */\n buyerId?: string\n}\n\nexport interface TrackOptions {\n context?: AnalyticsContext\n commerce?: AnalyticsCommerce\n props?: Record<string, unknown>\n}\n\nexport interface AnalyticsStartOptions {\n /** Where the SDK is embedded: 'vev' | 'replit' | 'custom' | … Default 'custom'. */\n host?: string\n /**\n * Arrancar en modo cookieless hasta que el host llame `setConsent(true)`.\n * Default false: el SDK asume que el CMP del publisher ya decidió si nos\n * carga. Los publishers EU que necesitan medir antes del consentimiento\n * (o no pueden persistir sin él) ponen true.\n */\n requireConsent?: boolean\n /**\n * Install the automatic funnel listeners (vio:added-to-cart,\n * vio:checkout-open, vio:open-cart, vio:payment-success). Default true.\n * Hosts with their OWN instrumentation choke point (e.g. the Vev module,\n * which forwards every event through trackEvent()) set false so the same\n * user action is never tracked twice — they keep the session/batching/\n * transport engine and call track() themselves.\n */\n autoTrack?: boolean\n /**\n * Adopt the host's session id instead of minting one. A host that already\n * tracks its readers (its own impressions, dwell, clicks) needs Vio's\n * purchases to land in the SAME session, or the two datasets cannot be\n * joined. Pass the id the host already stores; omit it and the SDK keeps\n * its own rotating session.\n */\n sessionId?: string\n /** Send to the Vio collector. Default true. */\n collector?: boolean\n /** Also push GA4 e-commerce events to window.dataLayer (publisher feature). */\n dataLayer?: boolean\n /** console.debug every event. */\n debug?: boolean\n}\n\n// ── Tunables (contract-aligned) ─────────────────────────────────────────────\n\n/**\n * A `purchase` whose payment event did not bring Vio's order number (a\n * redirect return, an order a webhook creates) waits for it: the checkout is\n * asked at once and again after each of these waits — ~10 s in all.\n */\nconst ORDER_NUMBER_BACKOFF_MS = [500, 1_000, 2_000, 3_000, 3_000] as const\n/** Longest a `purchase` waits for its order number; then it goes out with the checkout id. */\nconst ORDER_NUMBER_MAX_WAIT_MS = 10_000\n\nconst SESSION_TTL_MS = 30 * 60 * 1000 // rolling 30-min session\nconst FLUSH_INTERVAL_MS = 5_000\nconst FLUSH_AT_COUNT = 20\nconst MAX_QUEUE = 500 // drop-oldest beyond this\nconst RETRY_BACKOFF_MS = [2_000, 4_000, 8_000]\nconst ANON_KEY = 'vio.anon.v1'\nconst SESSION_KEY = 'vio.session.v1'\n\n/** Impression rule: ≥50% visible for ≥1s, once per (session, component). */\nconst IMPRESSION_THRESHOLD = 0.5\nconst IMPRESSION_DWELL_MS = 1_000\n\n// ── Wire shape (snake_case, contract v1) ────────────────────────────────────\n\ninterface WireEvent {\n event_id: string\n name: AnalyticsEventName\n ts: string\n surface: 'web'\n host?: string\n sdk_version: string\n session_id: string\n anon_id: string\n external_user_id?: string\n context?: Record<string, unknown>\n commerce?: Record<string, unknown>\n /** The standard context of the visit (contract \"client\"); the same object on every event of a page load. */\n client?: Record<string, unknown>\n props?: Record<string, unknown>\n}\n\n// ── Manager ─────────────────────────────────────────────────────────────────\n\nexport class AnalyticsManager extends EventTarget {\n private started = false\n private options: Required<\n Pick<AnalyticsStartOptions, 'collector' | 'dataLayer' | 'debug' | 'autoTrack'>\n > & {\n host: string\n } = { host: 'custom', collector: true, dataLayer: false, debug: false, autoTrack: true }\n\n private queue: WireEvent[] = []\n private flushTimer: ReturnType<typeof setInterval> | null = null\n private retryAttempt = 0\n private retryNotBefore = 0\n private externalUserId: string | undefined\n\n private sessionId: string | null = null\n private requireConsent = false\n private consentGranted = false\n private anonIdCache: string | null = null\n\n /** Set via start({ sessionId }) — the host owns the session, we follow. */\n private externalSessionId: string | null = null\n private sessionStartedAt = 0\n /** Impression once-per-(session, component) guard; reset on session rotation. */\n private impressedComponents = new Set<string>()\n\n /** Last NON-EMPTY cart snapshot — `purchase` uses it because several flows\n * (Apple Pay) clear the cart BEFORE `vio:payment-success` fires. */\n private lastCartSnapshot: { items: CartLineItem[]; currency?: string } | null = null\n\n /** The `client` block (language, landing referrer / utm, screen, tz): read once per page load, reused on every event. */\n private client: ClientContext | null = null\n /** The landing it was read from — persisted later when consent arrives after the first event. */\n private landing: Landing | null = null\n\n /** Checkouts (`c:<id>`) and orders (`o:<number>`) this page load reported a `purchase` for: one each. */\n private readonly purchased = new Set<string>()\n /** Purchases still waiting for Vio's order number: each sends at once, with what it has, when called. */\n private readonly pendingPurchases = new Set<() => void>()\n /** Between `pagehide` and `pageshow` (bfcache): nothing waits, it all goes out now. */\n private pageHiding = false\n\n /** The landing this manager resolved on this page load (the first event's), or null before it; read only — for the order's entry context when nothing is stored yet. */\n get currentLanding(): Landing | null {\n return this.landing\n }\n\n private teardown: Array<() => void> = []\n\n // MARK: - Public API\n\n /**\n * Install listeners + begin flushing. Explicit on purpose (no module\n * side-effects). Safe to call twice (second call only updates options).\n */\n /**\n * Consentimiento (ePrivacy/GDPR). Por defecto el SDK asume que el host ya\n * lo gestionó — su CMP decide si nos carga. Con `requireConsent: true`\n * arranca en modo **cookieless**: mide la visita con ids efímeros en\n * memoria y NO escribe nada en localStorage hasta que el host llame\n * `setConsent(true)`. Retirarlo borra lo persistido.\n */\n setConsent(granted: boolean): void {\n this.consentGranted = granted\n if (granted) {\n // Promueve los ids efímeros a persistentes: la visita en curso no se\n // parte en dos por haber aceptado a mitad de camino.\n if (this.anonIdCache) safeStorageSet(ANON_KEY, this.anonIdCache)\n if (this.sessionId) this.persistSession()\n // And the landing (referrer / utm), so the next pages of the session inherit it.\n if (this.landing) persistLanding(this.landing)\n return\n }\n safeStorageRemove(ANON_KEY)\n safeStorageRemove(SESSION_KEY)\n removeLanding()\n }\n\n /** ¿Podemos escribir en el dispositivo? */\n private get canPersist(): boolean {\n return !this.requireConsent || this.consentGranted\n }\n\n start(options: AnalyticsStartOptions = {}): void {\n this.requireConsent = options.requireConsent === true\n this.options = {\n host: options.host ?? this.options.host,\n collector: options.collector ?? this.options.collector,\n dataLayer: options.dataLayer ?? this.options.dataLayer,\n debug: options.debug ?? this.options.debug,\n autoTrack: options.autoTrack ?? this.options.autoTrack,\n }\n // A host-supplied session id wins over our own: it is the only way the\n // host can join Vio's funnel onto the events it already collects.\n if (options.sessionId) this.externalSessionId = options.sessionId\n\n if (this.started || !hasDom()) return\n this.started = true\n\n this.ensureSession() // emits session_start\n\n this.flushTimer = setInterval(() => void this.flush(), FLUSH_INTERVAL_MS)\n\n const onPageHide = () => {\n this.pageHiding = true\n // A purchase still waiting for its order number goes out now, with the\n // checkout id: the page will not wait for it.\n this.settlePendingPurchases()\n this.trackSessionEnd()\n this.flushWithBeacon()\n }\n const onPageShow = () => {\n this.pageHiding = false\n }\n window.addEventListener('pagehide', onPageHide)\n window.addEventListener('pageshow', onPageShow)\n this.teardown.push(() => window.removeEventListener('pagehide', onPageHide))\n this.teardown.push(() => window.removeEventListener('pageshow', onPageShow))\n // On a phone the page may never see `pagehide`: hidden is the last word it\n // is sure to get. A waiting purchase leaves then — and only it, by beacon.\n if (typeof document !== 'undefined' && typeof document.addEventListener === 'function') {\n const onVisibility = () => {\n if (document.visibilityState !== 'hidden' || this.pendingPurchases.size === 0) return\n this.settlePendingPurchases()\n this.flushWithBeacon()\n }\n document.addEventListener('visibilitychange', onVisibility)\n this.teardown.push(() => document.removeEventListener('visibilitychange', onVisibility))\n }\n\n if (this.options.autoTrack) this.installAutoListeners()\n }\n\n /** Stop timers + listeners (tests / SPA unmount). Queue survives — a purchase still waiting for its order number joins it now. */\n stop(): void {\n this.settlePendingPurchases()\n if (this.flushTimer) clearInterval(this.flushTimer)\n this.flushTimer = null\n for (const fn of this.teardown.splice(0)) fn()\n this.started = false\n }\n\n /** Attach the partner's user id (opaque) to all subsequent events. */\n identify(externalUserId: string | null): void {\n this.externalUserId = externalUserId ?? undefined\n }\n\n /** Queue one event. Works pre-init and pre-start (SSR: no-op). */\n track(name: AnalyticsEventName, opts: TrackOptions = {}): void {\n if (!hasDom()) return\n this.record(this.buildEvent(name, opts))\n }\n\n /** The sinks and the queue for one built event — `track`'s second half. */\n private record(event: WireEvent | null): void {\n if (!event) return\n\n if (this.options.debug) {\n console.debug('[Vio.analytics]', event.name, event)\n }\n // DOM sink — inspector/bridges (always once started; harmless before).\n try {\n window.dispatchEvent(new CustomEvent('vio:analytics', { detail: event }))\n } catch {\n /* CustomEvent unavailable — ignore */\n }\n if (this.options.dataLayer) pushGa4(event)\n\n this.queue.push(event)\n if (this.queue.length > MAX_QUEUE) this.queue.splice(0, this.queue.length - MAX_QUEUE)\n if (this.queue.length >= FLUSH_AT_COUNT) void this.flush()\n }\n\n /**\n * Impression helper: observes an element and tracks ONE\n * `component_impression` per (session, campaignComponentId) when the\n * contract's rule is met (≥50% visible, ≥1s dwell). Returns an\n * unobserve function.\n */\n observeImpression(\n element: Element,\n context: AnalyticsContext = {},\n opts: {\n name?: Extract<AnalyticsEventName, 'component_impression' | 'ad_impression'>\n /** Dedupe key override. Defaults to the strongest id available:\n * campaignComponentId → locationId → componentTemplateId. */\n key?: string\n /** Called the one time the impression is tracked (e.g. to fire a\n * companion view_item_list). */\n onImpression?: () => void\n } = {},\n ): () => void {\n if (!hasDom() || typeof IntersectionObserver === 'undefined') return () => {}\n const name = opts.name ?? 'component_impression'\n const dedupe =\n opts.key ??\n String(\n context.campaignComponentId ??\n context.locationId ??\n context.componentTemplateId ??\n 'component',\n )\n let dwellTimer: ReturnType<typeof setTimeout> | null = null\n\n const observer = new IntersectionObserver(\n (entries) => {\n for (const entry of entries) {\n if (entry.isIntersecting && entry.intersectionRatio >= IMPRESSION_THRESHOLD) {\n if (dwellTimer) continue\n dwellTimer = setTimeout(() => {\n const key = `${name}:${dedupe}`\n this.ensureSession()\n if (this.impressedComponents.has(key)) return\n this.impressedComponents.add(key)\n this.track(name, { context })\n opts.onImpression?.()\n observer.disconnect()\n }, IMPRESSION_DWELL_MS)\n } else if (dwellTimer) {\n clearTimeout(dwellTimer) // left the viewport before the dwell — not an impression\n dwellTimer = null\n }\n }\n },\n { threshold: [IMPRESSION_THRESHOLD] },\n )\n observer.observe(element)\n return () => {\n if (dwellTimer) clearTimeout(dwellTimer)\n observer.disconnect()\n }\n }\n\n /** Force a flush (mostly for tests). */\n async flush(): Promise<void> {\n if (!this.options.collector) {\n this.queue = []\n return\n }\n if (this.queue.length === 0) return\n if (!Configuration.isInitialized) return // transport unknown — hold the queue\n if (Date.now() < this.retryNotBefore) return\n\n const batch = this.queue.splice(0, MAX_QUEUE)\n const apiKey = Configuration.get().apiKey\n const body = JSON.stringify({\n apiKey,\n sent_at: new Date().toISOString(),\n events: batch,\n })\n try {\n // The key travels in the body too (sendBeacon can't set headers), but\n // the collector rate-limits by X-Api-Key and only falls back to the IP:\n // without the header every publisher behind one NAT shares a bucket.\n const res = await fetch(`${eventsBase()}/v1/events`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', 'X-Api-Key': apiKey },\n body,\n keepalive: batch.length <= 20, // keepalive caps payload at ~64KB\n })\n if (res.status === 401 || res.status === 400) {\n // Config problem, not transient — drop, don't loop forever.\n console.warn(`[Vio.analytics] collector rejected batch (HTTP ${res.status}) — dropped`)\n this.retryAttempt = 0\n return\n }\n if (!res.ok) throw new Error(`HTTP ${res.status}`)\n this.retryAttempt = 0\n } catch {\n // Requeue at the FRONT (same event_ids — server dedupes) + backoff.\n this.queue.unshift(...batch)\n const backoff =\n RETRY_BACKOFF_MS[Math.min(this.retryAttempt, RETRY_BACKOFF_MS.length - 1)] ?? 8_000\n this.retryAttempt++\n this.retryNotBefore = Date.now() + backoff\n }\n }\n\n // MARK: - Internals\n\n private buildEvent(name: AnalyticsEventName, opts: TrackOptions): WireEvent | null {\n this.ensureSession()\n if (!this.sessionId) return null\n const anonId = this.anonId()\n if (!anonId) return null\n\n const boot = vioBootstrapCache()\n const ctx = opts.context ?? {}\n // The article/page this instance renders in — resolved by the SDK when the\n // event brings no explicit content, or when the explicit id does not fit\n // the collector (see core/content.ts). The ONE place the collector's caps\n // are enforced: it rejects a whole event over a long id, silently.\n const explicitContentId = fitsId(ctx.contentId)\n const content =\n explicitContentId === undefined || ctx.contentTitle === undefined ? vioContent() : {}\n const context: Record<string, unknown> = compact({\n campaign_id: resolveCampaignId(ctx, boot),\n broadcast_id: ctx.broadcastId,\n campaign_component_id: ctx.campaignComponentId,\n app_placement_id: ctx.appPlacementId,\n // A slot is a location id to the campaigns service (ADR-0027). An\n // explicit location id that does not fit gives way to the slot.\n location_id: fitsId(ctx.locationId) ?? fitsId(ctx.slot),\n component_template_id: ctx.componentTemplateId,\n sponsor_id: ctx.sponsorId,\n activation_id: ctx.activationId,\n // Cut to the collector's 2 048 — the query string first, since a long\n // one is usually the tracking tail, not the page. The other host-given\n // fields (broadcastId, componentTemplateId, errorCode, variant, …) are\n // the host's responsibility: the SDK does not touch them.\n content_url: capContentUrl(ctx.contentUrl ?? (typeof location !== 'undefined' ? location.href : undefined)),\n // The host's own content id — its join key back onto its reporting.\n // Explicit on the event when it fits, else what the SDK resolved for\n // the page (already capped per source), else nothing.\n content_id: explicitContentId ?? fitsId(content.id),\n // Deletion-proof reporting: sources have no trash bin — the title\n // snapshotted at event time keeps reports legible if content dies.\n error_code: ctx.errorCode,\n content_title: capTitle(\n ctx.contentTitle ??\n content.title ??\n (typeof document !== 'undefined' && document.title ? document.title : undefined),\n ),\n variant: ctx.variant,\n })\n\n const com = opts.commerce\n const commerce = com\n ? compact({\n items: com.items?.map((i) =>\n compact({\n product_id: String(i.productId),\n name: i.name,\n brand: i.brand,\n variant_id: i.variantId !== undefined ? String(i.variantId) : undefined,\n price: i.price,\n quantity: i.quantity,\n }),\n ),\n value: com.value,\n currency: com.currency,\n order_id: com.orderId,\n // A uuid always fits; anything over the collector's 128 is left out, not cut.\n checkout_id: fitsId(com.checkoutId),\n payment_method: com.paymentMethod,\n // Only a reference survives — never an email, whatever a host passes —\n // and only with consent to persist: a visit measured with ephemeral\n // ids does not carry a stable identifier of a person either.\n buyer_id: this.canPersist ? normalizeBuyerRef(com.buyerId) : undefined,\n })\n : undefined\n const client = this.clientBlock()\n\n return {\n event_id: uuid(),\n name,\n ts: new Date().toISOString(),\n surface: 'web',\n host: this.options.host,\n sdk_version: SDK_VERSION,\n session_id: this.sessionId,\n anon_id: anonId,\n ...(this.externalUserId ? { external_user_id: this.externalUserId } : {}),\n ...(Object.keys(context).length ? { context } : {}),\n ...(commerce ? { commerce } : {}),\n ...(client ? { client } : {}),\n ...(opts.props ? { props: opts.props } : {}),\n }\n }\n\n /**\n * The `client` block: read once — the landing is remembered for the session\n * only when we may persist — then the same (frozen) object on every event.\n * `null` when there is nothing to say (no browser).\n */\n private clientBlock(): Record<string, unknown> | null {\n if (!this.client) {\n this.landing = resolveLanding(undefined, this.canPersist)\n this.client = Object.freeze(resolveClientContext(undefined, this.landing))\n }\n return Object.keys(this.client).length ? (this.client as Record<string, unknown>) : null\n }\n\n /** Guarda la sesión solo si podemos escribir en el dispositivo. */\n private persistSession(now: number = Date.now()): void {\n if (!this.canPersist || !this.sessionId) return\n safeStorageSet(\n SESSION_KEY,\n JSON.stringify({\n id: this.sessionId,\n ts: now,\n startedAt: this.sessionStartedAt ?? now,\n }),\n )\n }\n\n private anonId(): string | null {\n if (this.anonIdCache) return this.anonIdCache\n const stored = this.canPersist ? safeStorageGet(ANON_KEY) : null\n if (stored) {\n this.anonIdCache = stored\n return stored\n }\n const id = `a-${uuid()}`\n // Sin consentimiento el id vive solo en memoria: se mide la visita, no\n // queda rastro en el dispositivo.\n if (this.canPersist) safeStorageSet(ANON_KEY, id)\n this.anonIdCache = (this.canPersist ? safeStorageGet(ANON_KEY) : null) ?? id\n return this.anonIdCache\n }\n\n /** Rolling session: renewed by activity, rotated after 30 min idle. */\n private ensureSession(): void {\n const now = Date.now()\n if (!this.sessionId) {\n const stored = this.canPersist ? safeStorageGet(SESSION_KEY) : null\n if (stored) {\n try {\n const parsed = JSON.parse(stored) as { id: string; ts: number; startedAt: number }\n if (now - parsed.ts < SESSION_TTL_MS) {\n this.sessionId = parsed.id\n this.sessionStartedAt = parsed.startedAt ?? now\n }\n } catch {\n /* corrupted — rotate */\n }\n }\n } else {\n const stored = this.canPersist ? safeStorageGet(SESSION_KEY) : null\n if (stored) {\n try {\n if (now - (JSON.parse(stored) as { ts: number }).ts >= SESSION_TTL_MS) {\n this.sessionId = null // idle too long — rotate\n }\n } catch {\n this.sessionId = null\n }\n }\n }\n\n if (this.externalSessionId) {\n // The host rotates its own session; we never expire or replace it.\n if (this.sessionId !== this.externalSessionId) {\n this.sessionId = this.externalSessionId\n this.sessionStartedAt = now\n this.impressedComponents.clear()\n }\n }\n\n if (!this.sessionId) {\n this.sessionId = `s-${uuid()}`\n this.sessionStartedAt = now\n this.impressedComponents.clear()\n this.persistSession(now)\n this.track('session_start')\n } else {\n this.persistSession(now)\n }\n }\n\n private trackSessionEnd(): void {\n if (!this.sessionId) return\n this.track('session_end', {\n props: { duration_ms: Date.now() - this.sessionStartedAt },\n })\n }\n\n private flushWithBeacon(): void {\n if (!this.options.collector || this.queue.length === 0) return\n if (!Configuration.isInitialized) return\n const batch = this.queue.splice(0, MAX_QUEUE)\n const body = JSON.stringify({\n apiKey: Configuration.get().apiKey,\n sent_at: new Date().toISOString(),\n events: batch,\n })\n // text/plain skips the CORS preflight a beacon can't perform; the\n // collector parses it as JSON (contract §transport).\n const ok =\n typeof navigator !== 'undefined' &&\n typeof navigator.sendBeacon === 'function' &&\n navigator.sendBeacon(`${eventsBase()}/v1/events`, new Blob([body], { type: 'text/plain' }))\n if (!ok) this.queue.unshift(...batch) // beacon refused — keep for a live flush\n }\n\n /**\n * Auto-instrumentation over the SDK's own DOM events — the host app\n * writes ZERO tracking code for the commerce funnel.\n */\n private installAutoListeners(): void {\n const on = (type: string, handler: (ev: Event) => void) => {\n window.addEventListener(type, handler)\n this.teardown.push(() => window.removeEventListener(type, handler))\n }\n\n // Cart snapshot — kept fresh so `purchase` survives the pre-success\n // cart clear (Apple Pay flow).\n const cart = vioCart()\n if (cart) {\n const onChange = (ev: Event) => {\n const detail = (ev as CustomEvent<CartChangeDetail>).detail\n if (!detail) return\n const items: CartLineItem[] = []\n detail.cartsBySponsor?.forEach((state) => items.push(...state.items))\n if (items.length > 0) {\n this.lastCartSnapshot = { items: items.map((i) => ({ ...i })), currency: items[0]?.currency }\n }\n }\n cart.addEventListener('change', onChange)\n this.teardown.push(() => cart.removeEventListener('change', onChange))\n }\n\n on('vio:added-to-cart', (ev) => {\n const d = (ev as CustomEvent<{ productId?: number | string; sponsorId?: number; campaignId?: number; quantity?: number; variantId?: number | string; slot?: string; contentId?: string | number; contentTitle?: string; componentTemplateId?: string }>).detail ?? {}\n const line = this.findLine(d.productId, d.variantId)\n this.track('add_to_cart', {\n context: { sponsorId: d.sponsorId !== undefined ? Number(d.sponsorId) : undefined, campaignId: campaignOf(d), slot: slotOf(d), componentTemplateId: templateOf(d), ...contentOf(d) },\n commerce: {\n items: [\n {\n productId: d.productId ?? line?.productId ?? '',\n name: line?.name,\n brand: line?.brand,\n variantId: d.variantId ?? line?.variantId,\n price: line?.unitPrice,\n quantity: d.quantity ?? 1,\n },\n ],\n value: line ? line.unitPrice * (d.quantity ?? 1) : undefined,\n currency: line?.currency,\n },\n })\n })\n\n on('vio:removed-from-cart', (ev) => {\n const d = (ev as CustomEvent<{\n productId?: number | string\n variantId?: number | string\n name?: string\n brand?: string\n price?: number\n quantity?: number\n currency?: string\n sponsorId?: number\n campaignId?: number\n slot?: string\n contentId?: string | number\n contentTitle?: string\n }>).detail ?? {}\n if (d.productId === undefined) return\n this.track('remove_from_cart', {\n context: { sponsorId: d.sponsorId, campaignId: campaignOf(d), slot: slotOf(d), ...contentOf(d) },\n commerce: {\n items: [\n {\n productId: d.productId,\n variantId: d.variantId,\n name: d.name,\n brand: d.brand,\n price: d.price,\n quantity: d.quantity,\n },\n ],\n value: (d.price ?? 0) * (d.quantity ?? 1),\n currency: d.currency,\n },\n })\n })\n\n // Diagnóstico: sin esto, \"el carrito falló\" es indistinguible de\n // \"el usuario se fue\".\n on('vio:cart-error', (ev) => {\n const d = (ev as CustomEvent<{ message?: string }>).detail ?? {}\n this.track('sdk_error', {\n context: { errorCode: 'cart_error' },\n props: d.message ? { message: String(d.message).slice(0, 500) } : undefined,\n })\n })\n\n on('vio:product-click', (ev) => {\n const d = (ev as CustomEvent<{\n productId?: number | string\n sponsorId?: number\n name?: string\n brand?: string\n price?: number | string\n campaignId?: number\n slot?: string\n contentId?: string | number\n contentTitle?: string\n componentTemplateId?: string\n }>).detail ?? {}\n if (d.productId === undefined) return\n const price = Number(d.price)\n this.track('select_item', {\n context: { sponsorId: d.sponsorId !== undefined ? Number(d.sponsorId) : undefined, campaignId: campaignOf(d), slot: slotOf(d), componentTemplateId: templateOf(d), ...contentOf(d) },\n commerce: {\n items: [\n {\n productId: d.productId,\n name: d.name,\n brand: d.brand,\n price: Number.isFinite(price) ? price : undefined,\n },\n ],\n },\n })\n })\n\n on('vio:open-cart', () => {\n const snap = this.cartCommerce()\n this.track('view_cart', snap ? { commerce: snap } : {})\n })\n\n on('vio:checkout-open', (ev) => {\n const d = (ev as CustomEvent<{ sponsorId?: number; campaignId?: number; slot?: string; contentId?: string | number; contentTitle?: string; componentTemplateId?: string; buyerRef?: string }>).detail ?? {}\n const base: AnalyticsContext = { sponsorId: d.sponsorId, campaignId: campaignOf(d), slot: slotOf(d), componentTemplateId: templateOf(d), ...contentOf(d) }\n // The buyer reference only when the emitter already has it (a host's checkout); the SDK's own has none this early.\n const buyerId = buyerRefOf(d)\n const buyer = buyerId !== undefined ? { buyerId } : {}\n const { slices, explicit } = this.cartSlices(d.sponsorId)\n if (slices.length > 1) {\n // Several campaigns in the cart: one begin_checkout per campaign, each\n // with its own items and value (see cart/slices.ts).\n for (const slice of slices) {\n this.track('begin_checkout', {\n context: this.sliceContext(slice, base),\n commerce: { ...sliceCommerce(slice), ...buyer },\n props: { slice: slice.slice, slices: slice.slices },\n })\n }\n return\n }\n const snap = this.cartCommerce(d.sponsorId)\n this.track('begin_checkout', {\n context: this.singleSliceContext(slices[0], explicit, base),\n ...(snap || buyerId !== undefined ? { commerce: { ...(snap ?? {}), ...buyer } } : {}),\n })\n })\n\n on('vio:payment-success', (ev) => {\n const d = (ev as CustomEvent<PaymentSuccessDetail>).detail ?? {}\n const ids = purchaseIdsOf(d)\n // One purchase per checkout: another event for a checkout (or an order)\n // this page already reported — or is waiting to — adds nothing.\n if (!this.claimPurchase(ids)) return\n const sponsorId = d.sponsorId !== undefined ? Number(d.sponsorId) : undefined\n const base: AnalyticsContext = { sponsorId, campaignId: campaignOf(d), slot: slotOf(d), ...contentOf(d) }\n // Read NOW, whenever the event leaves: the cart is cleared right after\n // this event (the pre-clear snapshot covers the paths that clear first).\n const { slices, explicit } = this.cartSlices(sponsorId)\n const parts: TrackOptions[] =\n slices.length > 1\n ? // Several campaigns paid in one go: one purchase per campaign — its\n // items and value, the SAME order_id — so each campaign's revenue is\n // its own and the order still adds up. `props.slice/slices` lets the\n // collector count the order once.\n slices.map((slice) => ({\n context: this.sliceContext(slice, base),\n commerce: { ...sliceCommerce(slice), paymentMethod: d.method },\n props: { slice: slice.slice, slices: slice.slices },\n }))\n : [\n {\n context: this.singleSliceContext(slices[0], explicit, base),\n // value / currency / items: the cart snapshot, on every path.\n commerce: { ...(this.cartCommerce(sponsorId) ?? {}), paymentMethod: d.method },\n },\n ]\n this.reportPurchase(parts, ids, buyerRefOf(d), sponsorId)\n })\n }\n\n /**\n * Claims the purchase of a payment for this page load: false when its\n * checkout (or its order) already has one, reported or waiting.\n */\n private claimPurchase(ids: PurchaseIds): boolean {\n const keys: string[] = []\n if (ids.checkoutId) keys.push(`c:${ids.checkoutId}`)\n if (ids.orderIdKind === 'order' && ids.orderId) keys.push(`o:${ids.orderId}`)\n if (keys.some((key) => this.purchased.has(key))) return false\n for (const key of keys) this.purchased.add(key)\n return true\n }\n\n /**\n * Sends the `purchase` event(s) of one payment — ONCE, with Vio's order\n * number as `order_id` (`props.order_id_kind: 'order'`) and the checkout id\n * as `checkout_id`. When the payment event did not bring the number (a\n * redirect return, an order a webhook creates) the checkout is asked for it\n * — the receipt's own path, `Vio.checkout.getOrderReference` — at once and\n * after 0.5 / 1 / 2 / 3 / 3 s, for at most 10 s; nothing else waits for it.\n * Unanswered, or when the page hides or `stop()` comes first, the events go\n * out with what they have: the checkout id as `order_id`\n * (`order_id_kind: 'checkout'`), as before — and the late number adds no\n * second event. The events are BUILT at the payment — its moment (`ts`),\n * `event_id`, session, page and content — and only the order number (and a\n * buyer reference the payment did not bring) is filled in when it comes.\n */\n private reportPurchase(\n parts: TrackOptions[],\n ids: PurchaseIds,\n buyerId: string | undefined,\n sponsorId: number | undefined,\n ): void {\n const events = parts.map((part) =>\n this.buildEvent('purchase', {\n ...part,\n commerce: {\n ...part.commerce,\n ...(ids.orderId !== undefined ? { orderId: ids.orderId } : {}),\n ...(ids.checkoutId !== undefined ? { checkoutId: ids.checkoutId } : {}),\n ...(buyerId !== undefined ? { buyerId } : {}),\n },\n ...(ids.orderIdKind ? { props: { ...part.props, order_id_kind: ids.orderIdKind } } : {}),\n }),\n )\n const send = (found: OrderReferenceFound = {}) => {\n if (found.orderNumber) this.purchased.add(`o:${found.orderNumber}`)\n // Through the same filter as `buildEvent`: a reference, and only with consent to persist.\n const lateBuyer = this.canPersist ? normalizeBuyerRef(found.buyerRef) : undefined\n for (const event of events) {\n if (!event) continue\n if (found.orderNumber) {\n event.commerce = { ...event.commerce, order_id: found.orderNumber }\n event.props = { ...event.props, order_id_kind: 'order' }\n }\n if (lateBuyer && event.commerce && event.commerce.buyer_id === undefined) {\n event.commerce = { ...event.commerce, buyer_id: lateBuyer }\n }\n this.record(event)\n }\n }\n const ask = ids.orderIdKind === 'checkout' ? this.orderReferenceAsker(ids.checkoutId, sponsorId) : null\n if (!ask) {\n send()\n return\n }\n if (this.isPageHidden()) {\n // The page is going away (an emitter settling early on `pagehide`):\n // nothing can wait — out now, by beacon.\n send()\n this.flushWithBeacon()\n return\n }\n let done = false\n const settle = (found?: OrderReferenceFound) => {\n if (done) return\n done = true\n this.pendingPurchases.delete(settleNow)\n send(found)\n }\n const settleNow = () => settle()\n this.pendingPurchases.add(settleNow)\n void waitForOrderNumber(ask, () => done).then(settle, () => settle())\n }\n\n /** Sends every purchase still waiting for its order number, at once, with what it has. */\n private settlePendingPurchases(): void {\n for (const settle of [...this.pendingPurchases]) settle()\n }\n\n /** Whether the page is hidden or going away (`pagehide` until `pageshow`). */\n private isPageHidden(): boolean {\n if (this.pageHiding) return true\n try {\n return typeof document !== 'undefined' && document.visibilityState === 'hidden'\n } catch {\n return false\n }\n }\n\n /**\n * How a purchase asks a checkout for Vio's order number: through the SDK's\n * checkout manager (`getOrderReference`, which never throws and shares its\n * in-flight ask with the receipt's). `null` when there is nothing to ask —\n * no checkout id, or no checkout manager on this page.\n */\n private orderReferenceAsker(\n checkoutId: string | undefined,\n sponsorId: number | undefined,\n ): (() => Promise<CheckoutReference>) | null {\n if (!checkoutId) return null\n try {\n const checkout = vioFacade()?.checkout\n if (!checkout || typeof checkout.getOrderReference !== 'function') return null\n return () => checkout.getOrderReference!(checkoutId, sponsorId || undefined)\n } catch {\n return null\n }\n }\n\n /** The lines of the cart (current, else the pre-clear snapshot), optionally one sponsor's. */\n private cartLines(sponsorId?: number): CartLineItem[] {\n let items: CartLineItem[] = []\n const cart = vioCart()\n if (cart) {\n cart.getAllCarts().forEach((state, id) => {\n if (sponsorId === undefined || id === sponsorId) items.push(...state.items)\n })\n }\n if (items.length === 0 && this.lastCartSnapshot) {\n items = this.lastCartSnapshot.items.filter(\n (i) => sponsorId === undefined || i.sponsorId === sponsorId,\n )\n }\n return items\n }\n\n /**\n * The cart split per campaign — the shared rule of cart/slices.ts over the\n * current cart (else the pre-clear snapshot), plus whether any unit named\n * its campaign itself (a cart without origins is reported as before).\n */\n private cartSlices(sponsorId?: number): { slices: CartSlice[]; explicit: boolean } {\n const lines = this.cartLines(sponsorId)\n if (lines.length === 0) return { slices: [], explicit: false }\n const boot = vioBootstrapCache()\n const slices = cartSlicesFrom(\n lines,\n (slot, lineSponsorId) => resolveCampaignId({ slot, sponsorId: lineSponsorId }, boot),\n this.lastCartSnapshot?.currency,\n )\n return { slices, explicit: hasExplicitCampaign(lines) }\n }\n\n /**\n * The context of one of several per-campaign events: the slice's campaign,\n * slot and content — only its own; when the slice spans several slots or\n * articles the event names none rather than the one the click came from.\n */\n private sliceContext(slice: CartSlice, base: AnalyticsContext): AnalyticsContext {\n return compact({\n ...base,\n sponsorId: slice.sponsorId ?? base.sponsorId,\n campaignId: slice.campaignId,\n slot: slice.slot,\n contentId: slice.contentId,\n // The click's title only describes the click's content: when the slice\n // is another article (or several), the page's own title applies instead.\n contentTitle:\n slice.contentId !== undefined && slice.contentId === base.contentId ? base.contentTitle : undefined,\n }) as AnalyticsContext\n }\n\n /**\n * The context of a single-campaign checkout/purchase: when the cart's origins\n * say which campaign they came from, the event says it too (plus the slot /\n * content when unique) — a cart without origins is exactly as before.\n */\n private singleSliceContext(\n slice: CartSlice | undefined,\n explicit: boolean,\n base: AnalyticsContext,\n ): AnalyticsContext {\n if (!slice || !explicit) return base\n return compact({\n ...base,\n campaignId: base.campaignId ?? slice.campaignId,\n slot: base.slot ?? slice.slot,\n contentId: base.contentId ?? slice.contentId,\n }) as AnalyticsContext\n }\n\n /** Current cart → commerce payload; falls back to the pre-clear snapshot. */\n private cartCommerce(sponsorId?: number): AnalyticsCommerce | null {\n let items: CartLineItem[] = []\n const cart = vioCart()\n if (cart) {\n cart.getAllCarts().forEach((state, id) => {\n if (sponsorId === undefined || id === sponsorId) items.push(...state.items)\n })\n }\n if (items.length === 0 && this.lastCartSnapshot) {\n items = this.lastCartSnapshot.items.filter(\n (i) => sponsorId === undefined || i.sponsorId === sponsorId,\n )\n }\n if (items.length === 0) return null\n return {\n items: items.map((i) => ({\n productId: i.productId,\n name: i.name,\n brand: i.brand,\n variantId: i.variantId,\n price: i.unitPrice,\n quantity: i.quantity,\n })),\n value: items.reduce((sum, i) => sum + i.unitPrice * (i.quantity ?? 1), 0),\n currency: items[0]?.currency ?? this.lastCartSnapshot?.currency,\n }\n }\n\n private findLine(\n productId?: number | string,\n variantId?: number | string,\n ): CartLineItem | undefined {\n const pool: CartLineItem[] = []\n vioCart()\n ?.getAllCarts()\n .forEach((state) => pool.push(...state.items))\n if (pool.length === 0 && this.lastCartSnapshot) pool.push(...this.lastCartSnapshot.items)\n return pool.find(\n (i) =>\n String(i.productId) === String(productId) &&\n (variantId === undefined || String(i.variantId) === String(variantId)),\n )\n }\n}\n\n// ── Module-level helpers (pure; no side effects) ────────────────────────────\n\nfunction hasDom(): boolean {\n return typeof window !== 'undefined'\n}\n\nfunction uuid(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID()\n }\n // Ancient-browser fallback (non-cryptographic is fine for event ids).\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0\n return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16)\n })\n}\n\nfunction safeStorageGet(key: string): string | null {\n try {\n return window.localStorage.getItem(key)\n } catch {\n return null\n }\n}\n\nfunction safeStorageRemove(key: string): void {\n try {\n window.localStorage.removeItem(key)\n } catch {\n /* private mode / blocked */\n }\n}\n\nfunction safeStorageSet(key: string, value: string): void {\n try {\n window.localStorage.setItem(key, value)\n } catch {\n /* private mode / blocked — ephemeral ids are acceptable */\n }\n}\n\nfunction compact<T extends Record<string, unknown>>(obj: T): Record<string, unknown> {\n const out: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(obj)) {\n if (v !== undefined && v !== null && v !== '') out[k] = v\n }\n return out\n}\n\n/** Collector base URL for the active environment (override: `eventsBase`). */\nfunction eventsBase(): string {\n return Configuration.get().eventsBase\n}\n\n// Late imports via the global facade to avoid a circular module edge\n// (client.ts imports this file for the getter type).\ninterface FacadeLike {\n bootstrapCache: BootstrapResponse | null\n cart: CartManager\n content?: () => ContentRef\n /** The checkout manager: a purchase asks it for Vio's order number, as the receipt does. */\n checkout?: {\n getOrderReference?: (checkoutId: string, sponsorId?: number) => Promise<CheckoutReference>\n }\n}\nfunction vioFacade(): FacadeLike | null {\n const g = globalThis as unknown as { __VIO_FACADE__?: FacadeLike }\n return g.__VIO_FACADE__ ?? null\n}\nfunction vioBootstrapCache(): BootstrapResponse | null {\n return vioFacade()?.bootstrapCache ?? null\n}\n/** The page's content (article) — through the facade (live, init options included), else resolved here. */\nfunction vioContent(): ContentRef {\n try {\n const facade = vioFacade()\n return typeof facade?.content === 'function' ? facade.content() : resolveContent()\n } catch {\n return {}\n }\n}\nfunction vioCart(): CartManager | null {\n try {\n return vioFacade()?.cart ?? null\n } catch {\n return null\n }\n}\n\n// ── Attribution helpers (pure; exported for tests and hosts) ────────────────\n\n/**\n * The `campaign_id` of an event. In order: the context's explicit id; the\n * campaign assigned to the context's `slot` right now (ADR-0027 — only an\n * open assignment for the init platform counts, see `findSlotAssignment`);\n * the PAGE's campaign (`opts.pageCampaignId`, else `Vio.init({ campaignId })`)\n * when `campaigns[]` lists it as active (ADR-0034, amendment 3);\n * the active campaign of `campaigns[]` the event's sponsor takes part in, as\n * its primary or one of its secondaries — when it is in several, the\n * surface's default campaign if it is one of them, else the first one the\n * backend lists; the default campaign (`campaign.id`). `/v2/mobile/config`\n * has no top-level `campaignId` — reading one is why every event used to\n * leave with `campaign_id: 0` and the campaigns screen stayed empty.\n *\n * A malformed `campaigns[]` (not an array, a null entry) never breaks\n * `track()`: it falls back to `campaign.id`.\n */\nexport function resolveCampaignId(\n ctx: Pick<AnalyticsContext, 'campaignId' | 'sponsorId' | 'slot'>,\n boot: Pick<BootstrapResponse, 'campaign' | 'campaigns'> | null | undefined,\n opts: { pageCampaignId?: CampaignHint } = {},\n): number | undefined {\n if (ctx.campaignId !== undefined) return ctx.campaignId\n const defaultId = boot?.campaign?.id\n const config = Configuration.isInitialized ? Configuration.get() : undefined\n const sponsorId = toNumber(ctx.sponsorId)\n // The page's campaign (ADR-0034, amendment 3): the element's candidates\n // first, then Vio.init's; an unusable level falls through to the next. With\n // a known sponsor it applies only when that sponsor takes part in it —\n // otherwise the sponsor rule below says where the sponsor's campaign is.\n const candidates = [\n ...(Array.isArray(opts.pageCampaignId) ? opts.pageCampaignId : [opts.pageCampaignId]),\n config?.campaignId,\n ]\n const page = activeCampaignEntry(boot, candidates, sponsorId)\n if (ctx.slot) {\n const assignment = findSlotAssignmentDetail(boot, ctx.slot, Date.now(), config?.platform)\n // A dashboard assignment always wins; one this page made itself counts\n // like the page campaign: not when the page now declares another active\n // campaign, nor for a sponsor that takes no part in it (see slots.ts).\n if (assignment && assignmentApplies(assignment, activeCampaignEntry(boot, candidates), sponsorId)) {\n const assigned = toNumber(assignment.campaign.id)\n if (assigned !== undefined) return assigned\n }\n }\n const pageId = toNumber(page?.id)\n if (pageId !== undefined) return pageId\n if (sponsorId === undefined) return defaultId\n // The sponsor rule (shared with resolveSlotCampaign); a malformed\n // campaigns[] never breaks track(): it answers null and campaign.id applies.\n return toNumber(sponsorCampaignEntry(boot, sponsorId)?.id) ?? defaultId\n}\n\n/** The explicit `campaignId` a `vio:*` event detail carries (the element's attribution). */\nfunction campaignOf(detail: { campaignId?: unknown }): number | undefined {\n return toNumber(detail.campaignId)\n}\n\n/** An id the collector accepts (≤ 128 chars, as given — it coerces numbers); `undefined` otherwise. */\nfunction fitsId<T extends string | number>(value: T | null | undefined): T | undefined {\n if (value === undefined || value === null) return undefined\n const s = String(value)\n return s && s.length <= CONTENT_ID_MAX_LENGTH ? value : undefined\n}\n\n/** A title cut to what the collector accepts (≤ 255 chars). */\nfunction capTitle(value: string | undefined): string | undefined {\n if (!value) return undefined\n return value.length > CONTENT_TITLE_MAX_LENGTH ? value.slice(0, CONTENT_TITLE_MAX_LENGTH) : value\n}\n\n/** A slice as the commerce block of its event. */\nfunction sliceCommerce(slice: CartSlice): AnalyticsCommerce {\n return { items: slice.items, value: slice.value, currency: slice.currency }\n}\n\n/** The `slot` a `vio:*` event detail carries, when it is a non-empty string. */\nfunction slotOf(detail: { slot?: unknown }): string | undefined {\n return typeof detail.slot === 'string' && detail.slot.trim() ? detail.slot.trim() : undefined\n}\n\n/** The `componentTemplateId` a `vio:*` event detail carries — the kind of SDK element that emitted it (`product-card`, `product-carousel`, `product-detail`); omitted over the collector's 128. */\nfunction templateOf(detail: { componentTemplateId?: unknown }): string | undefined {\n const value = typeof detail.componentTemplateId === 'string' ? detail.componentTemplateId.trim() : ''\n return fitsId(value || undefined)\n}\n\n/** The per-element content override a `vio:*` event detail carries (`vio-content-id` / `vio-content-title`). */\nfunction contentOf(detail: { contentId?: unknown; contentTitle?: unknown }): Pick<AnalyticsContext, 'contentId' | 'contentTitle'> {\n const out: Pick<AnalyticsContext, 'contentId' | 'contentTitle'> = {}\n if (typeof detail.contentId === 'number' && Number.isFinite(detail.contentId)) out.contentId = detail.contentId\n else if (typeof detail.contentId === 'string' && detail.contentId.trim()) out.contentId = detail.contentId.trim()\n if (typeof detail.contentTitle === 'string' && detail.contentTitle.trim()) out.contentTitle = detail.contentTitle.trim()\n return out\n}\n\n\n/**\n * `detail` of `vio:payment-success` as the checkout emits it. Four paths,\n * three shapes: a redirect return (`orderId` = Vio's checkout id), the\n * confirmation drawer and a provider's own receipt (`result` from the\n * provider or the backend, plus Vio's `checkoutId`), and Apple Pay express\n * from the cart (`result` with the backend's `confirmation`, no sponsor).\n */\nexport interface PaymentSuccessDetail {\n method?: string\n sponsorId?: number | string\n /** The slot the purchase started from, when the emitter knows it. */\n slot?: string\n /** The campaign the emitter attributed the purchase to (its `Vio.attribution`). */\n campaignId?: number\n /** Per-element content override (`vio-content-id` / `vio-content-title`), when the emitter carries one. */\n contentId?: string | number\n contentTitle?: string\n /**\n * Redirect return: Vio's checkout id (the name predates `checkoutId`). A\n * value that is a whole number is read as Vio's order number instead — a\n * checkout id is a uuid, never one.\n */\n orderId?: string | number\n /** Vio's checkout id — from the checkout state or the return URL. */\n checkoutId?: string | number\n /**\n * Vio's order number (`4415`), when the emitter knows it: the SDK's checkout\n * adds it when its ask for the buyer reference already found the order.\n * Becomes the purchase's `order_id`.\n */\n orderNumber?: string | number | null\n /**\n * The buyer reference the emitter learned with the payment — shopcart's\n * `buyer_ref`, a keyed hash of the email (`buyerRef` from the SDK's own\n * checkout; `buyer_ref` when a host passes the backend's answer through).\n * Becomes `commerce.buyer_id`; never an email.\n */\n buyerRef?: string | null\n buyer_ref?: string | null\n result?: PaymentSuccessResult | null\n /**\n * The sponsor the order is with — the CHECKOUT's (its cart's sponsor),\n * never the page's: `{ id, name, logoUrl }` by the `Vio.sponsorIdentity`\n * rule, when it can be named. For the host's own receipt; analytics does\n * not read it.\n */\n sponsor?: CheckoutSponsor\n}\n\n/**\n * What the checkout attaches as `result`. Only `confirmation` carries Vio\n * ids: the order `ConfirmPaymentApplePay` created (its number) and the\n * checkout it paid. `order.orderId` / `orderId`\n * are the PROVIDER's references (Qliro's, Walley's — the checkout itself\n * shows them as `providerRef`), and `chargedTotal` includes shipping on some\n * methods only. Analytics reads none of those.\n */\nexport interface PaymentSuccessResult {\n confirmation?: {\n orderId?: string | number | null\n /** The checkout the confirmation paid (Apple Pay from the cart names no other). */\n checkoutId?: string | null\n status?: string\n buyerRef?: string | null\n buyer_ref?: string | null\n } | null\n /** The checkout as a host's backend answered it, when the host passes it through. */\n checkout?: { buyerRef?: string | null; buyer_ref?: string | null } | null\n buyerRef?: string | null\n buyer_ref?: string | null\n [key: string]: unknown\n}\n\n/**\n * The buyer reference of a `vio:payment-success` / `vio:checkout-open`\n * detail, wherever its emitter put it: top-level (`buyerRef`, or `buyer_ref`\n * as the backend spells it), on the result, on the result's `confirmation`\n * (Apple Pay) or `checkout`. Only a reference survives — never an email\n * (`normalizeBuyerRef`).\n */\nexport function buyerRefOf(\n d: { buyerRef?: unknown; buyer_ref?: unknown; result?: PaymentSuccessResult | null } | null | undefined,\n): string | undefined {\n if (!d) return undefined\n const r = d.result ?? {}\n const candidates = [\n d.buyerRef,\n d.buyer_ref,\n r.buyerRef,\n r.buyer_ref,\n r.confirmation?.buyerRef,\n r.confirmation?.buyer_ref,\n r.checkout?.buyerRef,\n r.checkout?.buyer_ref,\n ]\n for (const candidate of candidates) {\n const ref = normalizeBuyerRef(candidate)\n if (ref) return ref\n }\n return undefined\n}\n\n/** The ids of a `purchase`, as a `vio:payment-success` detail gives them (`purchaseIdsOf`). */\nexport interface PurchaseIds {\n /**\n * `commerce.order_id`: Vio's order number when the detail has it, else the\n * checkout id standing in for it.\n */\n orderId?: string\n /** `commerce.checkout_id`: Vio's checkout id (uuid), when the detail has it. */\n checkoutId?: string\n /** `props.order_id_kind`: what `orderId` is — `'order'` (the number) or `'checkout'` (the stand-in). */\n orderIdKind?: 'order' | 'checkout'\n}\n\n/**\n * The ids of a `purchase` — ALWAYS Vio's, never a provider's reference. The\n * order number: `orderNumber` (an emitter that knows it) →\n * `result.confirmation.orderId` (Apple Pay: the order `ConfirmPaymentApplePay`\n * created) → an `orderId` that is a whole number. The checkout id: `orderId`\n * (the redirect return's, a uuid) → `checkoutId` → `result.confirmation.checkoutId`\n * (Apple Pay from the cart). `orderId` is the number\n * when there is one, else the checkout id — the SDK's own `purchase` then\n * waits for the number (see `AnalyticsManager`); a host with its own sink can\n * ask `Vio.checkout.getOrderReference(checkoutId)` the same way.\n */\nexport function purchaseIdsOf(d: PaymentSuccessDetail | null | undefined): PurchaseIds {\n if (!d) return {}\n const r = d.result ?? {}\n const legacy = firstId(d.orderId)\n const legacyIsNumber = legacy !== undefined && isOrderNumber(legacy)\n const orderNumber = firstId(d.orderNumber, r.confirmation?.orderId, legacyIsNumber ? legacy : undefined)\n const checkoutId = firstId(legacyIsNumber ? undefined : legacy, d.checkoutId, r.confirmation?.checkoutId)\n if (orderNumber !== undefined) {\n return { orderId: orderNumber, ...(checkoutId !== undefined ? { checkoutId } : {}), orderIdKind: 'order' }\n }\n if (checkoutId !== undefined) return { orderId: checkoutId, checkoutId, orderIdKind: 'checkout' }\n return {}\n}\n\n/**\n * The `order_id`, `checkout_id` and `buyer_id` of a `purchase`, as far as the\n * detail says them NOW (`purchaseIdsOf`; the SDK's own `purchase` may still\n * wait for the order number). `value` and `currency` are deliberately NOT\n * read from the result: on every path they come from the cart snapshot (sum\n * of the items, no shipping), so revenue stays comparable across payment\n * methods — the charged total will arrive through the server-side\n * `order_paid` event. With nothing to say it returns `{}`, so the cart\n * snapshot keeps its keys.\n */\nexport function purchaseFromPaymentSuccess(\n d: PaymentSuccessDetail,\n): Pick<AnalyticsCommerce, 'orderId' | 'checkoutId' | 'buyerId'> {\n const { orderId, checkoutId } = purchaseIdsOf(d)\n const buyerId = buyerRefOf(d)\n return {\n ...(orderId !== undefined ? { orderId } : {}),\n ...(checkoutId !== undefined ? { checkoutId } : {}),\n ...(buyerId !== undefined ? { buyerId } : {}),\n }\n}\n\n/** Vio's order numbers are whole numbers (`4415`); its checkout ids are uuids. */\nfunction isOrderNumber(value: string): boolean {\n return /^[1-9][0-9]*$/.test(value)\n}\n\n/** What asking the checkout found: the order number once the order exists, and the buyer reference. */\ninterface OrderReferenceFound {\n orderNumber?: string\n buyerRef?: string\n}\n\n/**\n * Asks (`ask`) for Vio's order number until the checkout has one: at once,\n * then after each wait of `ORDER_NUMBER_BACKOFF_MS`, all within\n * `ORDER_NUMBER_MAX_WAIT_MS` — a slow answer counts against it too. A failed\n * ask is asked again. Resolves `{}` (or just the buyer reference) when the\n * time is up or `stopped()`; never rejects.\n */\nasync function waitForOrderNumber(\n ask: () => Promise<CheckoutReference>,\n stopped: () => boolean,\n): Promise<OrderReferenceFound> {\n let deadline: ReturnType<typeof setTimeout> | undefined\n const timeUp = new Promise<null>((resolve) => {\n deadline = setTimeout(() => resolve(null), ORDER_NUMBER_MAX_WAIT_MS)\n })\n let buyerRef: string | undefined\n const found = (orderNumber?: string): OrderReferenceFound => ({\n ...(orderNumber ? { orderNumber } : {}),\n ...(buyerRef ? { buyerRef } : {}),\n })\n try {\n for (let attempt = 0; attempt <= ORDER_NUMBER_BACKOFF_MS.length; attempt++) {\n if (attempt > 0) {\n const wait = ORDER_NUMBER_BACKOFF_MS[attempt - 1]!\n const slept = await Promise.race([new Promise<true>((resolve) => setTimeout(() => resolve(true), wait)), timeUp])\n if (slept === null) break\n }\n if (stopped()) break\n try {\n const reference = await Promise.race([ask(), timeUp])\n if (reference === null) break // time is up\n buyerRef ??= normalizeBuyerRef(reference?.buyerRef)\n const orderNumber = firstId(reference?.orderNumber)\n if (orderNumber !== undefined && isOrderNumber(orderNumber)) return found(orderNumber)\n } catch {\n /* ask again, or give up */\n }\n }\n return found()\n } finally {\n clearTimeout(deadline)\n }\n}\n\nfunction firstId(...candidates: unknown[]): string | undefined {\n for (const c of candidates) {\n if (c === undefined || c === null) continue\n const s = String(c)\n if (s !== '') return s\n }\n return undefined\n}\n\n// ── GA4 dataLayer sink (publisher feature; NOT the Vio pipeline) ────────────\n\nfunction pushGa4(event: WireEvent): void {\n const commerceNames = new Set([\n 'view_item_list',\n 'select_item',\n 'view_item',\n 'add_to_cart',\n 'view_cart',\n 'begin_checkout',\n 'purchase',\n ])\n if (!commerceNames.has(event.name)) return\n const w = window as unknown as { dataLayer?: unknown[] }\n w.dataLayer = w.dataLayer || []\n const commerce = (event.commerce ?? {}) as {\n items?: Array<Record<string, unknown>>\n value?: number\n currency?: string\n order_id?: string\n }\n // GA4 best practice: clear the previous ecommerce object before each push.\n w.dataLayer.push({ ecommerce: null })\n w.dataLayer.push({\n event: event.name,\n ecommerce: compact({\n currency: commerce.currency,\n value: commerce.value,\n transaction_id: commerce.order_id,\n items: commerce.items?.map((i) =>\n compact({\n item_id: i.product_id,\n item_name: i.name,\n item_brand: i.brand,\n item_variant: i.variant_id,\n price: i.price,\n quantity: i.quantity,\n }),\n ),\n }),\n })\n}\n","/**\n * The attribution of a checkout (ADR-0035 phase B): what the order is born\n * knowing about the surface it was sold from, the campaign of the page, the\n * page itself and where the shopper came in from. Sent as `attribution` on\n * `CreateCheckout` and on the `UpdateCheckout` right before paying; shopcart\n * keeps it on the checkout (`checkout.attribution`, merged key by key) and\n * writes `order.surface_id` / `campaign_id` / `content_url` / `content_title`\n * / `entry_source` from it when the order is created. The surface itself is\n * checked there against the cart's channel: a page cannot credit a sale to\n * somebody else's surface.\n *\n * Pure: `checkoutAttributionOf()` takes what the facade gathered. snake_case\n * on the wire, the caps of shopcart's `CheckoutAttributionDto` enforced here.\n */\n\nimport { CONTENT_TITLE_MAX_LENGTH, originAndPath } from '../content.js'\nimport { GRAPHQL_INT_MAX } from '../cart/origin-wire.js'\nimport {\n CLIENT_LANDING_URL_MAX_LENGTH,\n CLIENT_REFERRER_MAX_LENGTH,\n CLIENT_UTM_MAX_LENGTH,\n type Landing,\n} from '../analytics/client-context.js'\nimport type { CartSlice, VioItem } from '../cart/slices.js'\nimport type { SurfacePrivacyMode } from '../types.js'\n\n/** `EntryContextDto`: what the page knew when the shopper came in (the SDK's landing memory). */\nexport interface EntryContextWire {\n referrer?: string\n utm_source?: string\n utm_medium?: string\n utm_campaign?: string\n landing_url?: string\n}\n\n/** `CheckoutAttributionDto` (shopcart `checkout/dtos/checkout-attribution.dto.ts`). */\nexport interface CheckoutAttributionWire {\n surface_key?: string\n campaign_id?: number\n content_url?: string\n content_title?: string\n entry?: EntryContextWire\n}\n\n/** The caps of `CheckoutAttributionDto` / `EntryContextDto`. */\nexport const CHECKOUT_ATTRIBUTION_CAPS = Object.freeze({\n surfaceKey: 255,\n contentUrl: 2_048,\n contentTitle: CONTENT_TITLE_MAX_LENGTH,\n referrer: CLIENT_REFERRER_MAX_LENGTH,\n utm: CLIENT_UTM_MAX_LENGTH,\n landingUrl: CLIENT_LANDING_URL_MAX_LENGTH,\n})\n\nexport interface CheckoutAttributionInput {\n /** The surface's SDK key (`Vio.init({ apiKey })`) — shopcart resolves the surface from it. */\n surfaceKey?: string\n /** The campaign the PAGE belongs to, when the bootstrap lists it as active (`Vio.pageCampaign()`). */\n pageCampaignId?: number\n /** The cart split per campaign (`Vio.cartSlices(sponsorId)`), for the campaign that explains most units when the page has none. */\n slices?: ReadonlyArray<CartSlice>\n /** The page at pay time: `Vio.content()`'s url and title. */\n content?: { url?: string; title?: string }\n /** Where the session came in (`resolveLanding()`): referrer, utm, landing page. */\n landing?: Landing | null\n /**\n * The surface's privacy mode. Only on a `standard` surface do the page\n * (`content_url`, `content_title`) and the entry context travel: which\n * screen the sale was made on and why the shopper was there is what\n * `minimal` keeps private — the same promise the collector keeps for the\n * events. `unknown` (it could not be learnt) counts as `minimal`: what can\n * reveal it is only sent when the surface is known to allow it. The surface\n * and the campaign always travel.\n */\n privacyMode?: SurfacePrivacyMode | 'unknown'\n}\n\n/**\n * The attribution for the wire, or `undefined` when there is nothing to say.\n * The campaign is the page's; without one, the campaign that explains most\n * units of the cart under the same rule `purchase` is split by (ties: the\n * higher value, then the first). The page (origin + path) and the entry go\n * only on a `standard` surface.\n */\nexport function checkoutAttributionOf(input: CheckoutAttributionInput): CheckoutAttributionWire | undefined {\n const out: CheckoutAttributionWire = {}\n const surfaceKey = cut(input.surfaceKey, CHECKOUT_ATTRIBUTION_CAPS.surfaceKey)\n if (surfaceKey) out.surface_key = surfaceKey\n const campaignId = positiveInt(input.pageCampaignId) ?? dominantCampaignOf(input.slices)\n if (campaignId !== undefined) out.campaign_id = campaignId\n if (input.privacyMode === 'standard') {\n const url = originAndPath(input.content?.url, CHECKOUT_ATTRIBUTION_CAPS.contentUrl)\n if (url) out.content_url = url\n const title = cut(input.content?.title, CHECKOUT_ATTRIBUTION_CAPS.contentTitle)\n if (title) out.content_title = title\n const entry = entryContextOf(input.landing)\n if (entry) out.entry = entry\n }\n return Object.keys(out).length ? out : undefined\n}\n\n/** The landing as `entry`, capped; `undefined` when it says nothing. */\nexport function entryContextOf(landing: Landing | null | undefined): EntryContextWire | undefined {\n if (!landing || typeof landing !== 'object') return undefined\n const out: EntryContextWire = {}\n const referrer = cut(landing.referrer, CHECKOUT_ATTRIBUTION_CAPS.referrer)\n if (referrer) out.referrer = referrer\n const source = cut(landing.utm?.utm_source, CHECKOUT_ATTRIBUTION_CAPS.utm)\n if (source) out.utm_source = source\n const medium = cut(landing.utm?.utm_medium, CHECKOUT_ATTRIBUTION_CAPS.utm)\n if (medium) out.utm_medium = medium\n const campaign = cut(landing.utm?.utm_campaign, CHECKOUT_ATTRIBUTION_CAPS.utm)\n if (campaign) out.utm_campaign = campaign\n const landingUrl = cut(landing.url, CHECKOUT_ATTRIBUTION_CAPS.landingUrl)\n if (landingUrl) out.landing_url = landingUrl\n return Object.keys(out).length ? out : undefined\n}\n\n/**\n * The campaign that explains most units of the cart — over the slices\n * `purchase` is split by, so the order names the campaign the biggest\n * purchase event names. Ties go to the higher value, then to the first\n * slice. Units nobody attributes (a slice without campaign) never win.\n */\nexport function dominantCampaignOf(slices: ReadonlyArray<CartSlice> | null | undefined): number | undefined {\n if (!Array.isArray(slices)) return undefined\n let best: { campaignId: number; units: number; value: number } | undefined\n for (const slice of slices) {\n const campaignId = positiveInt(slice?.campaignId)\n if (campaignId === undefined) continue\n const items: ReadonlyArray<VioItem> = Array.isArray(slice.items) ? slice.items : []\n const units = items.reduce((sum: number, item) => sum + (Number(item?.quantity) > 0 ? Number(item.quantity) : 0), 0)\n const value = Number(slice.value) || 0\n if (!best || units > best.units || (units === best.units && value > best.value)) {\n best = { campaignId, units, value }\n }\n }\n return best?.campaignId\n}\n\n/** A positive `Int` as GraphQL coerces it (≤ 2³¹ − 1: a bigger value fails the whole mutation). */\nfunction positiveInt(value: unknown): number | undefined {\n if (value === undefined || value === null || value === '') return undefined\n const n = Number(value)\n return Number.isInteger(n) && n > 0 && n <= GRAPHQL_INT_MAX ? n : undefined\n}\n\nfunction cut(value: unknown, max: number): string | undefined {\n if (typeof value !== 'string' && typeof value !== 'number') return undefined\n const text = String(value).trim()\n if (!text) return undefined\n return text.length > max ? text.slice(0, max).trim() || undefined : text\n}\n","/**\n * Vio — public SDK entry point + facade.\n *\n * Usage:\n * import { Vio } from 'vio'\n * Vio.init({ apiKey: 'xxx' }) // backend-bound calls require this\n * await Vio.bootstrap() // GET /v2/mobile/config\n *\n * // Client-side primitives — no init needed:\n * Vio.cart.addProduct({ product, sponsorId: 3 })\n * Vio.checkout.open(3)\n *\n * // Backend-bound:\n * const products = await Vio.commerceFor(3).channel.product.getByIds({\n * product_ids: [408895],\n * })\n */\n\nimport { Configuration, type VioConfig } from './configuration.js'\nimport { VioApiError, createVioApi, type VioApi } from './api/vio.js'\nimport { createCommerceClient, type CommerceClient } from './api/commerce.js'\nimport { CartManager } from './cart/cart-manager.js'\nimport { CheckoutManager } from './checkout/checkout-manager.js'\nimport { AnalyticsManager, resolveCampaignId } from './analytics/analytics-manager.js'\nimport { resolveContent, type ContentRef } from './content.js'\nimport { storedLanding, type Landing } from './analytics/client-context.js'\nimport { checkoutAttributionOf, type CheckoutAttributionWire } from './checkout/attribution.js'\nimport {\n MAX_DECLARATIONS_PER_LOAD,\n MAX_LOCATIONS_PER_DECLARATION,\n SLOT_DECLARATION_FAILURE_TTL_MS,\n SLOT_DECLARATION_TTL_MS,\n activeCampaignEntry,\n campaignCandidates,\n normalizeSlotId,\n normalizeSlotKind,\n normalizeSlotLocations,\n pendingSlotKeys,\n readSlotDeclaration,\n rememberSlotKeys,\n resolveSlotCampaign,\n slotDeclarationKey,\n slotDeclarationStorageKey,\n toCampaignId,\n toNumber,\n writeSlotDeclaration,\n type CampaignHint,\n type RegisterSlotOptions,\n type SlotInput,\n} from './slots.js'\nimport { cartSlicesFrom, type CartSlice } from './cart/slices.js'\nimport {\n findSponsorIn,\n rememberedCheckoutSponsor,\n rememberedSponsor,\n sponsorIdentityFrom,\n toSponsorId,\n type RememberedCheckoutSponsor,\n type SponsorIdentity,\n} from './sponsor-identity.js'\nimport type { CartLineItem } from './cart/types.js'\nimport type {\n Attribution,\n BootstrapCampaignEntry,\n BootstrapResponse,\n ManifestLocation,\n ManifestResult,\n Sponsor,\n SurfacePrivacyMode,\n} from './types.js'\n\n/** Mount storms (a carousel of cards, Vev blocks) collapse into ONE manifest. */\nconst SLOT_DECLARATION_DEBOUNCE_MS = 1_000\n\n/** How long the surface is given to answer its privacy mode (preloaded at init; never awaited by the payment path). */\nconst PRIVACY_MODE_TIMEOUT_MS = 1_500\n/** How long \"could not tell\" (a timeout, a failure) is believed before the surface is asked again. */\nconst PRIVACY_UNKNOWN_TTL_MS = 60_000\n\ntype PrivacyAnswer = SurfacePrivacyMode | 'unknown'\n\n/** `standard` | `minimal` as the backend says it; anything else is \"not said\". */\nfunction privacyModeOf(value: unknown): SurfacePrivacyMode | undefined {\n return value === 'minimal' || value === 'standard' ? value : undefined\n}\n\n/**\n * What `GET /v2/mobile/surface` says of the mode: the field absent or null is\n * the default (`standard`); a word the SDK does not know is NOT — it may be\n * a stricter mode of a newer service — so it reads as `unknown`, as does an\n * answer without a surface at all.\n */\nfunction privacyModeOfSurface(res: unknown): PrivacyAnswer {\n const surface = (res as { surface?: unknown } | null | undefined)?.surface\n if (!surface || typeof surface !== 'object') return 'unknown'\n const raw = (surface as { privacyMode?: unknown }).privacyMode\n if (raw === undefined || raw === null) return 'standard'\n return privacyModeOf(raw) ?? 'unknown'\n}\n\nclass VioFacade {\n private apiInstance: VioApi | null = null\n private commerceClients = new Map<number, CommerceClient>()\n private bootstrapPromise: Promise<BootstrapResponse> | null = null\n private cachedBootstrap: BootstrapResponse | null = null\n /** Last bootstrap failure — short backoff so cart mutations don't hammer a\n * dead endpoint on every call. */\n private bootstrapFailedAt = 0\n /** Bumped by every init(). A bootstrap started under an older configuration\n * (another key or environment) is still in flight after a re-init; its answer\n * belongs to that configuration and must not land in this one. */\n private generation = 0\n\n /** Slot ids present on the page (`Vio.registerSlot`): how many elements hold each, its display name, its own campaign and its kind. */\n private slotRegistry = new Map<string, { count: number; displayName?: string; campaignId?: number; kind?: string }>()\n /** Slots already warned about (`dashboard`: the dashboard's assignment stands; `replaced`: this page moved it). */\n private warnedDashboardSlots = new Set<string>()\n private warnedReplacedSlots = new Set<string>()\n /** Pending debounced declaration of the registry. */\n private slotDeclareTimer: ReturnType<typeof setTimeout> | null = null\n /** A name appeared (or the key changed) since the registry was last declared. */\n private slotsDirty = false\n /** Manifests POSTed by this page load (abuse / rollout guard, see declareSlots). */\n private declarationsThisLoad = 0\n /** Each cap warns once per page load. */\n private warnedLocationCap = false\n private warnedDeclarationCap = false\n\n // Client-side managers — created lazily on first access. They don't\n // need Vio.init() to work (state is purely local).\n private cartManager: CartManager | null = null\n private checkoutManager: CheckoutManager | null = null\n private analyticsManager: AnalyticsManager | null = null\n /** What the surface answered of its privacy mode (`GET /v2/mobile/surface`) and when; `unknown` expires after a minute. */\n private surfaceMode: { mode: PrivacyAnswer; at: number } | null = null\n /** The request in flight for it, if any. */\n private surfaceRequest: Promise<PrivacyAnswer> | null = null\n\n init(config: VioConfig): void {\n Configuration.init(config)\n // Reset cached backend instances so a re-init picks up the new config.\n this.apiInstance = null\n this.commerceClients.clear()\n this.bootstrapPromise = null\n this.cachedBootstrap = null\n this.bootstrapFailedAt = 0\n this.generation++\n // The surface (its privacy mode) is the key's: forgotten, and asked again\n // for the new one right away — so it is known by the time anything is\n // added to the cart or paid for, and nothing on that path waits for it.\n this.surfaceMode = null\n this.surfaceRequest = null\n this.preloadPrivacyMode()\n // A new key/environment invalidates the per-sponsor payment methods too.\n this.checkoutManager?.clearPaymentMethodsCache()\n // The page's slots stay; they are declared again once the NEW key has\n // bootstrapped (a declaration pending for the old key is dropped).\n if (this.slotDeclareTimer) {\n clearTimeout(this.slotDeclareTimer)\n this.slotDeclareTimer = null\n }\n this.slotsDirty = this.slotRegistry.size > 0\n // The declaration caps are per configuration: a new key starts afresh.\n this.declarationsThisLoad = 0\n this.warnedLocationCap = false\n this.warnedDeclarationCap = false\n this.warnedDashboardSlots.clear()\n this.warnedReplacedSlots.clear()\n // NOTE: cart / checkout managers are NOT reset — user cart state is\n // independent of SDK re-config.\n }\n\n /**\n * The content (article, page) this SDK instance is rendered in — what every\n * analytics event carries as `content_id` / `content_title` when the event\n * has no explicit one: init option → URL query → `vio:content-*` metas →\n * canonical/og:url → pathname (see `resolveContent`). Resolved LIVE on each\n * call — a few querySelectors — so an SPA route change, a new canonical or\n * a new title are seen without any re-init. Never throws; `{}` without a\n * document.\n */\n content(): ContentRef {\n let init: { contentId?: string | number; contentTitle?: string } | undefined\n if (Configuration.isInitialized) {\n const cfg = Configuration.get()\n init = { contentId: cfg.contentId, contentTitle: cfg.contentTitle }\n }\n return resolveContent(init)\n }\n\n get isInitialized(): boolean { return Configuration.isInitialized }\n get config() { return Configuration.get() }\n\n // MARK: - Client-side managers (no init required)\n\n /** Multi-sponsor cart manager. Reactive — listen via addEventListener('change', ...). */\n get cart(): CartManager {\n if (!this.cartManager) this.cartManager = new CartManager()\n return this.cartManager\n }\n\n /** Checkout flow manager. Subscribes to cart state via the CartManager; asks here for the order's attribution. */\n get checkout(): CheckoutManager {\n if (!this.checkoutManager) {\n this.checkoutManager = new CheckoutManager(this.cart, {\n orderAttribution: (sponsorId) => this.orderAttribution(sponsorId),\n sponsorIdentity: (sponsorId, opts) => this.sponsorIdentity(sponsorId, opts),\n })\n }\n return this.checkoutManager\n }\n\n /**\n * Analytics — track() queues even pre-init; nothing is sent (and no\n * listeners are installed) until an explicit `Vio.analytics.start()`.\n */\n get analytics(): AnalyticsManager {\n if (!this.analyticsManager) this.analyticsManager = new AnalyticsManager()\n return this.analyticsManager\n }\n\n // MARK: - Backend-bound\n\n /** Lazy VioApi for REST endpoints on `api-staging.vio.live`. */\n get api(): VioApi {\n if (!this.apiInstance) {\n const cfg = Configuration.get()\n this.apiInstance = createVioApi({ apiBase: cfg.apiBase, apiKey: cfg.apiKey })\n }\n return this.apiInstance\n }\n\n /**\n * Bootstrap — fetches client config and caches it. Dedupes in-flight\n * concurrent requests.\n *\n * A request that was started before the last init() (Vev starts with the key\n * the browser remembers, then the page's own key arrives) answers for a key\n * that is gone: it neither fills the cache nor arms the failure backoff, and\n * whoever awaited it gets the current configuration's bootstrap instead.\n */\n async bootstrap(): Promise<BootstrapResponse> {\n if (this.cachedBootstrap) return this.cachedBootstrap\n if (this.bootstrapPromise) return this.bootstrapPromise\n // Failure backoff: don't re-fire a request for 5s after a failure —\n // every cart mutation awaits bootstrap, so a dead endpoint would\n // otherwise add a failed round-trip per click.\n if (this.bootstrapFailedAt && Date.now() - this.bootstrapFailedAt < 5_000) {\n throw new Error('[Vio] bootstrap recently failed — backing off')\n }\n const generation = this.generation\n const promise: Promise<BootstrapResponse> = this.api\n .bootstrap(Configuration.get().platform)\n .then(\n (res) => {\n if (generation !== this.generation) return this.bootstrap()\n this.cachedBootstrap = res\n this.bootstrapFailedAt = 0\n // The slots that mounted before this answer can be declared now.\n if (this.slotsDirty) this.scheduleSlotDeclaration()\n // The surface's privacy mode, in case init's ask failed or expired.\n this.preloadPrivacyMode()\n return res\n },\n (err) => {\n if (generation !== this.generation) return this.bootstrap()\n this.bootstrapFailedAt = Date.now()\n throw err\n },\n )\n .finally(() => {\n // Only clear our own slot: after a re-init it may hold the new request.\n if (this.bootstrapPromise === promise) this.bootstrapPromise = null\n })\n this.bootstrapPromise = promise\n return promise\n }\n\n get bootstrapCache(): BootstrapResponse | null {\n return this.cachedBootstrap\n }\n\n /**\n * Who a sponsor is to a shopper — `{ id, name, logoUrl, avatarUrl }` — by\n * the ONE rule every element uses (`sponsorIdentityFrom`): the live\n * bootstrap's sponsor blocks (the config's primary and secondaries, then\n * every `campaigns[]` primary and secondaries, first match); when the\n * bootstrap does not know the id (not loaded yet, a redirect return), what\n * this tab remembered of the checkout (`opts.checkoutId`, else the latest\n * checkout of that sponsor), then the cart's `sponsorName`. With only\n * `opts.checkoutId`, the sponsor is the one remembered for that checkout.\n * In a checkout pass the CHECKOUT's sponsor — never the page's\n * attribution. URLs as given; an empty logo is `null`. `null` when nothing\n * names it. Pure over local state, never throws.\n */\n sponsorIdentity(\n sponsorId?: number | string | null,\n opts: { checkoutId?: string | null } = {},\n ): SponsorIdentity | null {\n try {\n // The memory is read only when needed: the bootstrap usually answers.\n let memo: RememberedCheckoutSponsor | null | undefined\n const memoOfCheckout = () => (memo === undefined ? (memo = rememberedCheckoutSponsor(opts?.checkoutId ?? undefined)) : memo)\n const id = toSponsorId(sponsorId) ?? memoOfCheckout()?.sponsorId\n if (id === undefined) return null\n const fromBootstrap = sponsorIdentityFrom(this.cachedBootstrap, id)\n if (fromBootstrap) return fromBootstrap\n const ofCheckout = memoOfCheckout()\n const remembered =\n (ofCheckout && ofCheckout.sponsorId === id && (ofCheckout.name || ofCheckout.logoUrl) ? ofCheckout : null) ??\n rememberedSponsor(id)\n if (remembered) {\n return { id, name: remembered.name, logoUrl: remembered.logoUrl, avatarUrl: null }\n }\n const cartName = this.cart.getCart(id)?.sponsorName\n const name = typeof cartName === 'string' ? cartName.trim() : ''\n return name ? { id, name, logoUrl: null, avatarUrl: null } : null\n } catch {\n return null\n }\n }\n\n /**\n * Get a CommerceClient scoped to a specific sponsor (via bootstrap).\n * Throws if bootstrap hasn't been called or the sponsor is unknown.\n */\n commerceFor(sponsorId: number): CommerceClient {\n // Coacción a número: los web-components pasan sponsorId como string\n // (atributo), y findSponsor compara con `===` contra el id numérico.\n sponsorId = Number(sponsorId) as number\n const existing = this.commerceClients.get(sponsorId)\n if (existing) return existing\n const sponsor = this.findSponsor(sponsorId)\n if (!sponsor) {\n throw new Error(\n `[Vio] Sponsor ${sponsorId} not found in bootstrap. Call Vio.bootstrap() first or pass commerce-key directly.`,\n )\n }\n const cfg = Configuration.get()\n const client = createCommerceClient({ endpoint: cfg.graphQLBase, apiKey: sponsor.commerce.apiKey })\n this.commerceClients.set(sponsorId, client)\n return client\n }\n\n /** Get a CommerceClient using an explicit commerce apiKey (skip bootstrap). */\n commerceWithKey(commerceApiKey: string): CommerceClient {\n const cfg = Configuration.get()\n return createCommerceClient({ endpoint: cfg.graphQLBase, apiKey: commerceApiKey })\n }\n\n // MARK: - Slots (ADR-0027 / ADR-0034)\n\n /**\n * Declare this page's slots to the campaigns service\n * (`POST /v2/mobile/components/manifest`, `mode: 'merge'`, the init\n * platform). Best-effort: it NEVER throws — a failure is logged and resolves\n * `null`. The same set is not re-posted from this browser for 24 h unless\n * `force` (then `null` also means \"skipped, already declared\"). Ids are\n * trimmed, cut at 100 chars, deduped; empties are dropped.\n */\n async declareSlots(\n slots: ReadonlyArray<SlotInput>,\n opts: { force?: boolean } = {},\n ): Promise<ManifestResult | null> {\n let storageKey: string | undefined\n let keys: string[] = []\n let now = Date.now()\n try {\n const all = normalizeSlotLocations(slots)\n if (all.length === 0) return null\n if (!Configuration.isInitialized) {\n warn('declareSlots() before Vio.init() — nothing declared')\n return null\n }\n const cfg = Configuration.get()\n storageKey = slotDeclarationStorageKey(cfg.platform, cfg.apiKey)\n now = Date.now()\n // The page's campaign goes top-level; a location names its own only when\n // it differs from the page's (ADR-0034, amendment 3).\n const pageCampaignId = cfg.campaignId\n for (const l of all) {\n if (l.campaignId !== undefined && l.campaignId === pageCampaignId) delete l.campaignId\n }\n // Per id, not per set: only what this browser has not declared (under\n // this name and campaign) in the last 24 h goes out — a multi-page site\n // declares each page's new ids once, a renamed block or a page that\n // changed campaign again, a failed attempt after 1 h.\n const memory = readSlotDeclaration(storageKey)\n const keyOf = (l: ManifestLocation) => slotDeclarationKey(l, pageCampaignId)\n const pending = new Set(pendingSlotKeys(memory, all.map(keyOf), now))\n let locations = opts.force ? all : all.filter((l) => pending.has(keyOf(l)))\n if (locations.length === 0) return null\n if (locations.length > MAX_LOCATIONS_PER_DECLARATION) {\n if (!this.warnedLocationCap) {\n this.warnedLocationCap = true\n warn(\n `declareSlots(): ${locations.length} slots on one page — only the first ${MAX_LOCATIONS_PER_DECLARATION} are declared`,\n )\n }\n locations = locations.slice(0, MAX_LOCATIONS_PER_DECLARATION)\n }\n keys = locations.map(keyOf)\n if (!opts.force && this.declarationsThisLoad >= MAX_DECLARATIONS_PER_LOAD) {\n if (!this.warnedDeclarationCap) {\n this.warnedDeclarationCap = true\n warn(\n `declareSlots(): already ${MAX_DECLARATIONS_PER_LOAD} manifests this page load — further ones are skipped (force: true to override)`,\n )\n }\n return null\n }\n this.declarationsThisLoad++\n const result = await this.api.declareManifest({\n platform: cfg.platform,\n mode: 'merge',\n locations,\n ...(pageCampaignId !== undefined ? { campaignId: pageCampaignId } : {}),\n })\n this.reportAssignments(result, locations, pageCampaignId, cfg.debug)\n // A server that predates `mode` drops the field, answers 200 without it\n // and REPLACES (it deprecates the other pages' slots). Only a declaration\n // the server confirms as merged is remembered for 24 h — a replace is\n // remembered for 1 h, so the next load (not every view) tries again,\n // and succeeds once the server is updated. A location whose campaign the\n // micro did not take up (no `assignment` at all — an older micro — or\n // `none` for a campaign the bootstrap lists as active) is remembered for\n // 1 h too, so the page's campaign lands once the micro is updated.\n if (result?.mode === 'merge') {\n const unhandled = this.campaignNotTakenUp(result, locations, pageCampaignId)\n const settled = keys.filter((k) => !unhandled.has(k))\n let next = rememberSlotKeys(memory, settled, now)\n if (unhandled.size > 0) next = rememberSlotKeys(next, [...unhandled], failedAt(now))\n writeSlotDeclaration(storageKey, next)\n } else {\n writeSlotDeclaration(storageKey, rememberSlotKeys(memory, keys, failedAt(now)))\n warn(\n 'slots declared but the server ignored mode=merge (old server); not caching, will retry next load',\n )\n }\n return result\n } catch (err) {\n // Not retried for an hour: a failing micro must not get a POST per view.\n if (storageKey && keys.length > 0) {\n writeSlotDeclaration(storageKey, rememberSlotKeys(readSlotDeclaration(storageKey), keys, failedAt(now)))\n }\n warn('declareSlots() failed —', err)\n return null\n }\n }\n\n /**\n * Register a slot present on the page (the `<vio-*>` elements call it with\n * their effective id — the host's `vio-slot` or the auto-generated one —\n * the optional display name, and the element's own campaign when it has\n * one: `vio-campaign` or an ancestor's `data-vio-campaign`). The registry is\n * declared ONCE, debounced, after the first successful bootstrap — and again\n * whenever a new id, display name, campaign or kind appears. A `displayName` /\n * `campaignId` given later for an id already registered replaces the one\n * kept; `undefined` leaves it alone. The third argument is the campaign id\n * (as before) or `{ campaignId?, kind? }`, and a fourth `{ kind? }` may\n * follow a positional campaign — the elements call\n * `registerSlot(id, name, campaignId, { kind })` so a facade from an older\n * bundle, which reads only three arguments, still gets the campaign. `kind`\n * is what kind of element holds the slot (`card` | `carousel` | `detail`);\n * the FIRST kind an id gets stays (the cards a carousel renders share its\n * id: the slot is the carousel's). The returned function unregisters;\n * removal never re-declares.\n */\n registerSlot(\n name: string,\n displayName?: string,\n campaignIdOrOptions?: number | string | null | RegisterSlotOptions,\n options?: RegisterSlotOptions,\n ): () => void {\n const id = normalizeSlotId(name)\n if (!id) return () => {}\n const label = typeof displayName === 'string' && displayName.trim() ? displayName.trim() : undefined\n const positional: RegisterSlotOptions =\n campaignIdOrOptions !== null && typeof campaignIdOrOptions === 'object'\n ? campaignIdOrOptions\n : { campaignId: campaignIdOrOptions }\n const merged: RegisterSlotOptions = { ...positional, ...(options ?? {}) }\n const campaign = toCampaignId(merged.campaignId) // invalid (0, -5, 'x') = absent: leaves the kept one alone\n const kind = normalizeSlotKind(merged.kind)\n const entry = this.slotRegistry.get(id)\n let changed = false\n if (!entry) {\n this.slotRegistry.set(id, { count: 1, displayName: label, campaignId: campaign, kind })\n changed = true\n } else {\n entry.count++\n if (label !== undefined && label !== entry.displayName) {\n entry.displayName = label\n changed = true\n }\n if (campaign !== undefined && campaign !== entry.campaignId) {\n entry.campaignId = campaign\n changed = true\n }\n if (kind !== undefined && entry.kind === undefined) {\n entry.kind = kind\n changed = true\n }\n }\n if (changed) {\n this.slotsDirty = true\n if (this.cachedBootstrap) this.scheduleSlotDeclaration()\n }\n let released = false\n return () => {\n if (released) return\n released = true\n const current = this.slotRegistry.get(id)\n if (!current) return\n if (current.count <= 1) this.slotRegistry.delete(id)\n else current.count--\n }\n }\n\n /**\n * The campaign a slot shows now, from the last bootstrap: its assigned and\n * open campaign for the init platform, else the surface's default. With no\n * slot, the default. `null` before the bootstrap. See `resolveSlotCampaign`.\n */\n campaignForSlot(\n slot?: string | null,\n hint?: { campaignId?: CampaignHint; sponsorId?: number | string | null },\n ): BootstrapCampaignEntry | null {\n const config = Configuration.isInitialized ? Configuration.get() : undefined\n return resolveSlotCampaign(\n this.cachedBootstrap,\n slot ?? null,\n Date.now(),\n config?.platform,\n this.pageCampaignCandidates(hint?.campaignId),\n toNumber(hint?.sponsorId),\n )\n }\n\n /** The page-campaign candidates in precedence order: the element's (own, ancestor), then `Vio.init`'s. */\n private pageCampaignCandidates(hint: CampaignHint): number[] {\n const config = Configuration.isInitialized ? Configuration.get() : undefined\n return campaignCandidates([...(Array.isArray(hint) ? hint : [hint]), config?.campaignId])\n }\n\n /**\n * The campaign the PAGE belongs to (`Vio.init({ campaignId })`, ADR-0034\n * amendment 3), as the last bootstrap lists it — only when it is there and\n * active; `null` otherwise (no page campaign, paused, unknown, no bootstrap).\n */\n pageCampaign(): BootstrapCampaignEntry | null {\n const config = Configuration.isInitialized ? Configuration.get() : undefined\n return activeCampaignEntry(this.cachedBootstrap, config?.campaignId)\n }\n\n /**\n * THE attribution helper — the SDK elements, Vev and Replit all use this\n * one. For a place (`slot`): the campaign it shows right now\n * (`campaignForSlot`: its assignment, else the surface's default) as\n * `campaignId` + that campaign's primary sponsor as `sponsorId`, plus the\n * page's content (`content()`). Pure, never throws; `{}` before the\n * bootstrap, except the content.\n *\n * `hint.sponsorId` — when the caller already knows the sponsor (a card with\n * `sponsor-id`) it is kept as `sponsorId`, and the campaign follows the same\n * cascade analytics uses (slot assignment → page campaign → the sponsor's\n * active campaign → default), so what the cart remembers matches what the\n * events say — the page campaign applies there only when that sponsor takes\n * part in it. `hint.campaignId` — the element's own page campaign\n * candidates (`vio-campaign`, an ancestor's `data-vio-campaign`), ahead of\n * `Vio.init`'s; an unusable one falls through to the next; `0` = unset.\n */\n attribution(\n slot?: string | null,\n hint?: { sponsorId?: number | string; campaignId?: CampaignHint },\n ): Attribution {\n const out: Attribution = {}\n try {\n const name = normalizeSlotId(slot)\n if (name) out.slot = name\n const boot = this.cachedBootstrap\n const hinted = toNumber(hint?.sponsorId)\n const pageCampaignId = this.pageCampaignCandidates(hint?.campaignId)\n if (boot) {\n if (hinted !== undefined) {\n const campaignId = resolveCampaignId({ slot: name || undefined, sponsorId: hinted }, boot, {\n pageCampaignId,\n })\n if (campaignId !== undefined) out.campaignId = campaignId\n out.sponsorId = hinted\n } else {\n const campaign = this.campaignForSlot(name || null, { campaignId: pageCampaignId })\n const campaignId = toNumber(campaign?.id)\n if (campaignId !== undefined) out.campaignId = campaignId\n // No active campaign on the surface (`campaign: null`): the page\n // still sells, with the sponsor of the surface's channel and no\n // campaign (campaigns micro, 21/10).\n const sponsorId = campaign ? toNumber(campaign.primarySponsor?.id) : toNumber(boot.primarySponsor?.id)\n if (sponsorId !== undefined) out.sponsorId = sponsorId\n }\n } else if (hinted !== undefined) {\n out.sponsorId = hinted\n }\n const content = this.content()\n if (content.id) out.contentId = content.id\n if (content.title) out.contentTitle = content.title\n if (content.url) out.contentUrl = content.url\n } catch {\n /* attribution never breaks a render or a click */\n }\n return out\n }\n\n /**\n * What the surface answered and is still believed: `standard` / `minimal`\n * for the configuration; `unknown` for a minute after a timeout or a\n * failure (then it is asked again). `null` = nothing believed.\n */\n private believedSurfaceMode(): PrivacyAnswer | null {\n const answer = this.surfaceMode\n if (!answer) return null\n if (answer.mode !== 'unknown') return answer.mode\n return Date.now() - answer.at < PRIVACY_UNKNOWN_TTL_MS ? 'unknown' : null\n }\n\n /**\n * Ask the surface its privacy mode (`GET /v2/mobile/surface`), once —\n * started at `init()` and again by `bootstrap()`, never by the payment\n * path, which only reads what is known (`privacyModeNow`). Resolves what\n * was learnt within 1.5 s: the mode; `standard` for a service that predates\n * the endpoint (404) or a surface that names none; `unknown` for a word the\n * SDK does not know, a timeout or any other failure — believed for a\n * minute, then asked again. An answer that arrives after the cap still\n * lands for the next step. Never throws.\n */\n preloadPrivacyMode(): Promise<PrivacyAnswer> {\n try {\n if (this.surfaceRequest) return this.surfaceRequest\n const believed = this.believedSurfaceMode()\n if (believed) return Promise.resolve(believed)\n if (!Configuration.isInitialized) return Promise.resolve('unknown')\n const now = Date.now()\n if (Configuration.get().privacyMode === 'minimal') {\n this.surfaceMode = { mode: 'minimal', at: now }\n return Promise.resolve('minimal')\n }\n const generation = this.generation\n const learnt = (mode: PrivacyAnswer) => {\n // An older key's answer is not this surface's.\n if (generation !== this.generation) return\n // A real answer after a timeout replaces the \"unknown\"; never the other way round.\n if (mode === 'unknown' && this.surfaceMode && this.surfaceMode.mode !== 'unknown') return\n this.surfaceMode = { mode, at: Date.now() }\n }\n const asked: Promise<PrivacyAnswer> = this.api.surface().then(\n (res) => privacyModeOfSurface(res),\n (err: unknown) => (err instanceof VioApiError && err.status === 404 ? 'standard' : 'unknown'),\n )\n let timer: ReturnType<typeof setTimeout> | undefined\n const capped = new Promise<PrivacyAnswer>((resolve) => {\n timer = setTimeout(() => resolve('unknown'), PRIVACY_MODE_TIMEOUT_MS)\n })\n const request: Promise<PrivacyAnswer> = Promise.race([asked, capped]).then((mode) => {\n clearTimeout(timer)\n learnt(mode)\n if (this.surfaceRequest === request) this.surfaceRequest = null\n return mode\n })\n // The late answer, if the cap won.\n void asked.then((mode) => {\n clearTimeout(timer)\n learnt(mode)\n })\n this.surfaceRequest = request\n return request\n } catch {\n return Promise.resolve('unknown')\n }\n }\n\n /**\n * How much of the visit the order attribution may carry (ADR-0035): the\n * surface's privacy mode, as known RIGHT NOW, without waiting —\n * `Vio.init({ privacyMode: 'minimal' })` when the host says so, else what\n * the bootstrap says of the surface, else what the surface answered to the\n * ask `init()` started (`preloadPrivacyMode`), else the host's `standard`\n * once the surface could not tell. `unknown` while nothing is known: then\n * the page, the slot and the entry stay off what goes to Commerce, because\n * what can reveal which screen someone was on, and why, is only sent when\n * the surface is known to allow it. The payment path reads this one.\n */\n privacyModeNow(): PrivacyAnswer {\n try {\n const config = Configuration.isInitialized ? Configuration.get() : undefined\n if (config?.privacyMode === 'minimal') return 'minimal'\n const fromBootstrap = privacyModeOf(this.cachedBootstrap?.surface?.privacyMode)\n if (fromBootstrap) return fromBootstrap\n if (!config) return 'unknown'\n const believed = this.believedSurfaceMode()\n if (believed === 'standard' || believed === 'minimal') return believed\n // Nothing believed, nothing asked: ask now for the next time.\n if (!believed) this.preloadPrivacyMode()\n // The host's word stands in only once the surface could not tell.\n return believed === 'unknown' ? (config.privacyMode ?? 'unknown') : 'unknown'\n } catch {\n return 'unknown'\n }\n }\n\n /**\n * `privacyModeNow`, but waiting for the ask in flight when there is one\n * (at most its 1.5 s cap) — for the cart's lines, which are not the\n * payment path. Never throws.\n */\n async privacyMode(): Promise<PrivacyAnswer> {\n try {\n const now = this.privacyModeNow()\n if (now !== 'unknown') return now\n if (!this.surfaceRequest) return 'unknown'\n const asked = await this.surfaceRequest\n if (asked !== 'unknown') return asked\n const config = Configuration.isInitialized ? Configuration.get() : undefined\n return config?.privacyMode ?? 'unknown'\n } catch {\n return 'unknown'\n }\n }\n\n /**\n * The attribution of the order a sponsor's cart is about to become\n * (ADR-0035 phase B) — what `CreateCheckout` / `UpdateCheckout` send as\n * `attribution` and shopcart writes on the order: the surface (its SDK\n * key), the page's campaign (`pageCampaign()`; without one, the campaign\n * that explains most units of the cart under the same rule `purchase` is\n * split by — `cartSlices`) and, on a surface KNOWN to be `standard`\n * (`privacyModeNow`), the page (`content()`'s url as origin + path, and\n * title) and where the session came in: the landing the session REMEMBERS\n * (`storedLanding`, else the one analytics resolved on this page) — never\n * the page the shopper pays on taken for a landing. Synchronous: nothing\n * on the way to a payment waits for it. snake_case, capped to Commerce's\n * limits. `undefined` when there is nothing to say; never throws.\n */\n orderAttribution(sponsorId?: number): CheckoutAttributionWire | undefined {\n try {\n const config = Configuration.isInitialized ? Configuration.get() : undefined\n const content = this.content()\n return checkoutAttributionOf({\n surfaceKey: config?.apiKey,\n pageCampaignId: toNumber(this.pageCampaign()?.id),\n slices: this.cartSlices(sponsorId),\n content: { url: content.url, title: content.title },\n landing: this.rememberedLanding(),\n privacyMode: this.privacyModeNow(),\n })\n } catch {\n return undefined\n }\n }\n\n /** The landing the session remembers: what the first page stored, else what analytics resolved on this page load (consent pending); null otherwise. */\n private rememberedLanding(): Landing | null {\n try {\n return storedLanding() ?? this.analyticsManager?.currentLanding ?? null\n } catch {\n return null\n }\n }\n\n /**\n * The cart split per campaign — the SAME rule `begin_checkout` / `purchase`\n * use, for hosts with their own analytics sink (Vev). Every unit of every\n * line goes to the campaign of its origin; units without one to the campaign\n * the current rule resolves for the line's sponsor (slot assignment → the\n * sponsor's active campaign → default); `slot` / `contentId` / `sponsorId`\n * only when they are the same for the whole slice; `value` with two\n * decimals; `slice` / `slices` number the parts. Pure over the current cart\n * (or over `opts.items`); `[]` when there is nothing.\n */\n cartSlices(sponsorId?: number, opts: { items?: CartLineItem[] } = {}): CartSlice[] {\n try {\n let lines: CartLineItem[] = []\n if (Array.isArray(opts.items)) {\n lines = opts.items.filter((i) => sponsorId === undefined || Number(i?.sponsorId) === Number(sponsorId))\n } else {\n this.cart.getAllCarts().forEach((state, id) => {\n if (sponsorId === undefined || id === Number(sponsorId)) lines.push(...state.items)\n })\n }\n const boot = this.cachedBootstrap\n return cartSlicesFrom(lines, (slot, lineSponsorId) =>\n resolveCampaignId({ slot, sponsorId: lineSponsorId }, boot),\n )\n } catch {\n return []\n }\n }\n\n /**\n * What the micro did with the page's campaign per slot (`assignment`):\n * `console.debug` when `Vio.init({ debug: true })`; a warning once per\n * slot when the dashboard's own assignment stands (only for a slot this\n * page actually sent a campaign for) and once per slot when this page moved\n * it from an earlier page assignment (`replaced`).\n */\n private reportAssignments(\n result: ManifestResult | null | undefined,\n sent: ReadonlyArray<ManifestLocation>,\n pageCampaignId: number | undefined,\n debug: boolean,\n ): void {\n const answered = Array.isArray(result?.locations) ? result.locations : []\n const campaignFor = (id: string) =>\n sent.find((l) => l.id === id)?.campaignId ?? pageCampaignId\n for (const l of answered) {\n if (!l || typeof l !== 'object' || !l.assignment) continue\n if (debug && typeof console !== 'undefined') console.debug('[Vio] slot', l.locationId, 'assignment:', l.assignment)\n const sentCampaign = campaignFor(l.locationId)\n if (sentCampaign === undefined) continue\n if (l.assignment === 'dashboard' && !this.warnedDashboardSlots.has(l.locationId)) {\n this.warnedDashboardSlots.add(l.locationId)\n warn(`slot ${l.locationId} is assigned from the dashboard; the page's campaign is ignored there`)\n }\n if (l.assignment === 'replaced' && !this.warnedReplacedSlots.has(l.locationId)) {\n this.warnedReplacedSlots.add(l.locationId)\n warn(`slot ${l.locationId} moved to campaign ${sentCampaign} by this page (it replaced an earlier page assignment)`)\n }\n }\n }\n\n /**\n * The memory keys of the sent locations whose campaign the micro did not\n * take up: every location when a campaign was sent and no answer carries\n * `assignment` (an older micro), or the ones answered `none` for a campaign\n * the bootstrap lists as active. They are remembered with the 1 h TTL.\n */\n private campaignNotTakenUp(\n result: ManifestResult | null | undefined,\n sent: ReadonlyArray<ManifestLocation>,\n pageCampaignId: number | undefined,\n ): Set<string> {\n const out = new Set<string>()\n const withCampaign = sent.filter((l) => (l.campaignId ?? pageCampaignId) !== undefined)\n if (withCampaign.length === 0) return out\n const answered = Array.isArray(result?.locations) ? result.locations : []\n const anyAssignment = answered.some((l) => l && typeof l === 'object' && !!l.assignment)\n for (const l of withCampaign) {\n const answer = answered.find((a) => a && a.locationId === l.id)\n const campaignId = l.campaignId ?? pageCampaignId\n const notTaken =\n !anyAssignment ||\n (answer?.assignment === 'none' && activeCampaignEntry(this.cachedBootstrap, campaignId) !== null)\n if (notTaken) out.add(slotDeclarationKey(l, pageCampaignId))\n }\n return out\n }\n\n private scheduleSlotDeclaration(): void {\n if (this.slotDeclareTimer) clearTimeout(this.slotDeclareTimer)\n this.slotDeclareTimer = setTimeout(() => {\n this.slotDeclareTimer = null\n this.slotsDirty = false\n void this.declareSlots(\n [...this.slotRegistry.entries()].map(([id, { displayName, campaignId, kind }]) => ({\n id,\n ...(displayName ? { displayName } : {}),\n ...(campaignId !== undefined ? { campaignId } : {}),\n ...(kind ? { kind } : {}),\n })),\n )\n }, SLOT_DECLARATION_DEBOUNCE_MS)\n }\n\n private findSponsor(sponsorId: number): Sponsor | undefined {\n // A sponsor may live only in a non-default campaign (the one a slot shows).\n return findSponsorIn(this.cachedBootstrap, sponsorId)\n }\n}\n\nfunction warn(...args: unknown[]): void {\n if (typeof console !== 'undefined') console.warn('[Vio]', ...args)\n}\n\n/** The timestamp a failed attempt is remembered at: it expires after the 1 h failure TTL. */\nfunction failedAt(now: number): number {\n return now - (SLOT_DECLARATION_TTL_MS - SLOT_DECLARATION_FAILURE_TTL_MS)\n}\n\n\n// Cross-bundle singleton. Some hosts (e.g. Vev) bundle each component into its\n// own chunk, so a plain module-level instance would give EACH chunk its own\n// `Vio` — separate cart + bootstrap cache. That breaks shared state (one chunk\n// bootstraps, another reads an empty cache → \"Sponsor not found\"). Anchoring the\n// facade on `globalThis` means every copy resolves to the SAME instance within a\n// page. SSR-safe: `globalThis` exists in Node too.\nconst _vioGlobal = globalThis as unknown as { __VIO_FACADE__?: VioFacade }\nexport const Vio: VioFacade =\n _vioGlobal.__VIO_FACADE__ ?? (_vioGlobal.__VIO_FACADE__ = new VioFacade())\n","/**\n * Vipps MobilePay's own button, the way the design guidelines ask for it.\n *\n * Vipps publishes a web component (`<vipps-mobilepay-button>`) that draws\n * the on-brand button and nothing else: it does not start the payment, we\n * do, on its click. Using it means no logo of ours to keep in step with the\n * brand rules (ePayment checklist, \"Follow the design guidelines\",\n * 2026-10-06). The script is loaded once, on demand, from Vipps' CDN; when\n * it does not arrive in time — blocked, offline — callers draw the plain\n * orange button they always had.\n */\nexport const VIPPS_BUTTON_SCRIPT = 'https://cdn.vippsmobilepay.com/js/button/button.js'\nexport const VIPPS_BUTTON_TAG = 'vipps-mobilepay-button'\n\nlet pending: Promise<boolean> | null = null\n\n/**\n * Resolves true once Vipps' button element is defined, false when its script\n * failed to load (or, with `timeoutMs`, did not answer in time). Callers draw\n * their own button meanwhile and swap it for Vipps' when this resolves — the\n * CDN takes a few seconds on a slow line, and nobody should wait for it.\n */\nexport function ensureVippsButton(timeoutMs = 0): Promise<boolean> {\n if (typeof document === 'undefined' || typeof customElements === 'undefined') {\n return Promise.resolve(false)\n }\n if (customElements.get(VIPPS_BUTTON_TAG)) return Promise.resolve(true)\n if (!pending) {\n pending = new Promise<boolean>((resolve) => {\n let settled = false\n const done = (ok: boolean) => {\n if (settled) return\n settled = true\n if (timer) clearTimeout(timer)\n resolve(ok)\n }\n const timer = timeoutMs > 0 ? setTimeout(() => done(false), timeoutMs) : undefined\n customElements.whenDefined(VIPPS_BUTTON_TAG).then(\n () => done(true),\n () => done(false),\n )\n if (!document.querySelector(`script[src=\"${VIPPS_BUTTON_SCRIPT}\"]`)) {\n const script = document.createElement('script')\n script.async = true\n script.src = VIPPS_BUTTON_SCRIPT\n script.onerror = () => done(false)\n document.head.appendChild(script)\n }\n })\n // A load that failed is not remembered: the next caller tries again.\n void pending.then((ok) => {\n if (!ok) pending = null\n })\n }\n return pending\n}\n\n/** The attributes of the official button as Vio uses it (React hosts spread these). */\nexport function vippsButtonAttributes(\n verb: 'buy' | 'pay' | 'express' | 'continue' = 'buy',\n opts: { stretched?: boolean; compact?: boolean; language?: string } = {},\n): Record<string, string> {\n return {\n brand: 'vipps',\n language: opts.language ?? 'no',\n verb,\n variant: 'primary',\n rounded: 'true',\n stretched: opts.stretched === false ? 'false' : 'true',\n ...(opts.compact ? { compact: 'true' } : {}),\n }\n}\n"]}
|