@asteby/storefront 0.24.0 → 0.26.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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors.ts","../src/geo.ts","../src/money.ts","../src/query.ts","../src/client.ts","../src/payment-errors.ts","../src/diagnose.ts","../src/availability.ts","../src/payments.ts","../src/promotions.ts","../src/market.ts","../src/order-progress.ts","../src/account-settings.ts","../src/invoice-docs.ts","../src/subjects.ts","../src/delivery.ts"],"names":["fmt","ES","EN","CATALOG","path","key"],"mappings":";;;AA8BO,IAAM,eAAA,GAAN,cAA8B,KAAA,CAAM;AAAA,EACvB,IAAA,GAAO,iBAAA;AAAA,EAChB,MAAA;AAAA,EACA,IAAA;AAAA,EACA,KAAA;AAAA,EACA,OAAA;AAAA,EACA,GAAA;AAAA;AAAA,EAEA,cAAA;AAAA;AAAA,EAEA,SAAA;AAAA;AAAA,EAEA,UAAA;AAAA;AAAA,EAEA,UAAA;AAAA;AAAA,EAEA,IAAA;AAAA;AAAA,EAEA,SAAA;AAAA,EAET,YAAY,IAAA,EAA2B;AACrC,IAAA,KAAA,CAAM,IAAA,CAAK,OAAA,EAAS,IAAA,CAAK,KAAA,KAAU,MAAA,GAAY,SAAY,EAAE,KAAA,EAAO,IAAA,CAAK,KAAA,EAAO,CAAA;AAChF,IAAA,IAAA,CAAK,SAAS,IAAA,CAAK,MAAA;AACnB,IAAA,IAAA,CAAK,OAAO,IAAA,CAAK,IAAA;AACjB,IAAA,IAAA,CAAK,QAAQ,IAAA,CAAK,KAAA;AAClB,IAAA,IAAA,CAAK,UAAU,IAAA,CAAK,OAAA;AACpB,IAAA,IAAA,CAAK,MAAM,IAAA,CAAK,GAAA;AAChB,IAAA,IAAA,CAAK,cAAA,GAAiB,IAAA,CAAK,cAAA,IAAkB,EAAC;AAC9C,IAAA,IAAA,CAAK,YAAY,IAAA,CAAK,SAAA;AACtB,IAAA,IAAA,CAAK,aAA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1E,EAAA,IAAI,MAAA,CAAO,aAAa,OAAO,IAAA;AAC/B,EAAA,IAAI,MAAA,CAAO,SAAS,QAAA,EAAU,OAAO,EAAE,MAAA,EAAQ,QAAA,EAAU,SAAA,EAAW,MAAA,CAAO,EAAA,EAAG;AAC9E,EAAA,OAAO,EAAE,MAAA,EAAQ,UAAA,EAAY,OAAA,EAAS,MAAA,CAAO,MAAM,MAAA,EAAU;AAC/D;AAGO,IAAM,cAAA,GAAiB;AAYvB,SAAS,gBAAgB,QAAA,EAAgG;AAC9H,EAAA,MAAM,GAAA,GAAM,QAAA,EAAU,WAAA,IAAe,EAAC;AACtC,EAAA,MAAM,gBAAgB,GAAA,CAAI,MAAA,CAAO,CAAC,CAAA,KAAM,CAAA,CAAE,SAAS,cAAc,CAAA;AACjE,EAAA,MAAM,cAAc,GAAA,CAAI,MAAA,CAAO,CAAC,CAAA,KAAM,CAAA,CAAE,SAAS,cAAc,CAAA;AAC/D,EAAA,OAAO;AAAA,IACL,aAAA;AAAA,IACA,WAAA;AAAA,IACA,UAAA,EAAY,cAAc,MAAA,GAAS,CAAA,IAAK,YAAY,MAAA,GAAS,CAAA,IAAK,UAAU,OAAA,KAAY;AAAA,GAC1F;AACF","file":"index.cjs","sourcesContent":["import type { InsufficientStockLine, StorefrontErrorCode } from './types.js'\n\nexport type StorefrontErrorInit = {\n status: number\n code: StorefrontErrorCode\n message: string\n field?: string\n /** Raw `error.details` from the body (untrusted shape). */\n details?: unknown\n /** Request URL that failed (without credentials). */\n url?: string\n cause?: unknown\n /** Scopes named by the gateway on a `403 insufficient_scope`. */\n requiredScopes?: string[]\n /** `error.retryable` as OPS declared it (payment failures). `undefined` = OPS did not say. */\n retryable?: boolean\n /** `error.retry_after` in seconds. */\n retryAfter?: number\n /** `error.checkout_id`: the checkout a refused cart write can resume. */\n checkoutId?: string\n /** `error.cost` of a `price_mismatch` (the cart's current cost; untrusted shape). */\n cost?: unknown\n /** `error.message_en`. */\n messageEn?: string\n}\n\n/**\n * Error thrown by the client for any non-2xx response, network failure,\n * timeout or abort. `status` is `0` when no HTTP response was received.\n */\nexport class StorefrontError extends Error {\n override readonly name = 'StorefrontError'\n readonly status: number\n readonly code: StorefrontErrorCode\n readonly field: string | undefined\n readonly details: unknown\n readonly url: string | undefined\n /** Scopes a `403 insufficient_scope` says the route needs (empty for any other error). */\n readonly requiredScopes: string[]\n /** `true`: repeating the request (same idempotency key) can succeed. `false`: not until someone fixes something. `undefined`: OPS did not say. */\n readonly retryable: boolean | undefined\n /** Seconds OPS asks to wait before retrying. */\n readonly retryAfter: number | undefined\n /** Checkout that a refused cart write can resume. */\n readonly checkoutId: string | undefined\n /** Current cart cost sent with a `price_mismatch` (untrusted shape). */\n readonly cost: unknown\n /** English version of `message`, when OPS sent one. */\n readonly messageEn: string | undefined\n\n constructor(init: StorefrontErrorInit) {\n super(init.message, init.cause === undefined ? undefined : { cause: init.cause })\n this.status = init.status\n this.code = init.code\n this.field = init.field\n this.details = init.details\n this.url = init.url\n this.requiredScopes = init.requiredScopes ?? []\n this.retryable = init.retryable\n this.retryAfter = init.retryAfter\n this.checkoutId = init.checkoutId\n this.cost = init.cost\n this.messageEn = init.messageEn\n }\n\n /**\n * Affected lines of a `409 insufficient_stock` (empty for any other error or a\n * server older than contract 1.1). The cart is untouched: show the lines and\n * let the buyer adjust or remove them.\n */\n get stockLines(): InsufficientStockLine[] {\n const lines = (this.details as { lines?: unknown } | null | undefined)?.lines\n if (this.code !== 'insufficient_stock' || !Array.isArray(lines)) return []\n return lines.filter((l): l is InsufficientStockLine => typeof l === 'object' && l !== null && typeof (l as { sku?: unknown }).sku === 'string')\n }\n\n toJSON() {\n return {\n name: this.name,\n status: this.status,\n code: this.code,\n message: this.message,\n field: this.field,\n ...(this.requiredScopes.length ? { requiredScopes: this.requiredScopes } : {}),\n ...(this.retryable !== undefined ? { retryable: this.retryable } : {}),\n ...(this.retryAfter !== undefined ? { retryAfter: this.retryAfter } : {}),\n ...(this.checkoutId ? { checkoutId: this.checkoutId } : {}),\n }\n }\n}\n\nexport function isStorefrontError(err: unknown): err is StorefrontError {\n return err instanceof StorefrontError || (typeof err === 'object' && err !== null && (err as { name?: unknown }).name === 'StorefrontError')\n}\n\nconst STATUS_CODES: Record<number, StorefrontErrorCode> = {\n 400: 'validation',\n 401: 'unauthorized',\n 403: 'forbidden',\n 404: 'not_found',\n 409: 'conflict',\n 422: 'invalid_state',\n 429: 'rate_limited',\n}\n\nexport function defaultCodeForStatus(status: number): StorefrontErrorCode {\n return STATUS_CODES[status] ?? (status >= 500 ? 'server_error' : 'invalid_response')\n}\n","/**\n * Geo helpers: pure TypeScript, no network and no DOM. Works in Node 20, edge\n * runtimes and browsers. Behaviour is pinned by `geo-vectors.json`, which the\n * Go side copies verbatim, so keep both implementations in sync.\n */\n\nexport type GeoPoint = { lat: number; lng: number }\n\n/** `(0, 0)` means \"unset\" on this platform, so it is never a valid point. */\ntype MaybePoint = { lat?: number | null; lng?: number | null } | null | undefined\n\nexport type OpeningHours = {\n /** `day`: 1 = Monday ... 7 = Sunday. Several entries per day are allowed. A `close` at or before `open` crosses midnight. */\n weekly: { day: number; open: string; close: string }[]\n /** Dated overrides of the weekly rule. `closed`, or both `open` and `close`. */\n exceptions?: { date: string; closed?: true; open?: string; close?: string; note?: string }[]\n}\n\nexport type OpenStatus = {\n open: boolean\n /** ISO instant (UTC) when the current interval ends; `null` when closed. */\n closesAt: string | null\n /** ISO instant (UTC) of the next opening; `null` when open or none within 8 days. */\n nextOpenAt: string | null\n}\n\nconst RAD = Math.PI / 180\n\n/** Great-circle distance in km (haversine, earth radius 6371.0088 km). */\nexport function distanceKm(a: GeoPoint, b: GeoPoint): number {\n const dLat = (b.lat - a.lat) * RAD\n const dLng = (b.lng - a.lng) * RAD\n const h = Math.sin(dLat / 2) ** 2 + Math.cos(a.lat * RAD) * Math.cos(b.lat * RAD) * Math.sin(dLng / 2) ** 2\n return 2 * 6371.0088 * Math.atan2(Math.sqrt(h), Math.sqrt(1 - h))\n}\n\n/** Finite, in range and not the `(0, 0)` \"unset\" pair. */\nexport function isValidPoint(p: MaybePoint): p is GeoPoint {\n const { lat, lng } = p ?? {}\n // Number.isFinite is false for null, undefined and non-numbers.\n return Number.isFinite(lat) && Number.isFinite(lng) && Math.abs(lat!) <= 90 && Math.abs(lng!) <= 180 && !(lat === 0 && lng === 0)\n}\n\n/** `'19.43,-99.13'` (spaces allowed) to a point; `null` when malformed or invalid. */\nexport function parseLatLng(s: string | null | undefined): GeoPoint | null {\n const [a, b, ...rest] = (s ?? '').split(',')\n const p = !rest.length && a?.trim() && b?.trim() ? { lat: Number(a), lng: Number(b) } : null\n return isValidPoint(p) ? p : null\n}\n\nexport type RankOptions<T> = {\n /** Keep items at most this far away (inclusive). */\n radiusKm?: number\n /** Keep the first N after sorting. */\n limit?: number\n /** Defaults to reading `lat` / `lng` from the item. */\n getPoint?: (item: T) => MaybePoint\n}\n\n/**\n * Sorts by distance from `origin` (stable: ties keep input order). Items without\n * a valid point are EXCLUDED, not placed last, because they have no distance.\n */\nexport function rankByDistance<T>(\n items: readonly T[],\n origin: GeoPoint,\n { radiusKm, limit, getPoint = (i) => i as MaybePoint }: RankOptions<T> = {},\n): { item: T; distanceKm: number }[] {\n const out: { item: T; distanceKm: number }[] = []\n for (const item of items) {\n const p = getPoint(item)\n if (!isValidPoint(p)) continue\n const d = distanceKm(origin, p)\n if (radiusKm === undefined || d <= radiusKm) out.push({ item, distanceKm: d })\n }\n // Array.prototype.sort is stable (ES2019), so ties keep input order.\n out.sort((x, y) => x.distanceKm - y.distanceKm)\n return limit === undefined ? out : out.slice(0, Math.max(0, limit))\n}\n\n/** Under 1 km: meters rounded to 50 m. Otherwise km with one decimal. */\nexport function formatDistance(km: number, locale = 'es-MX'): string {\n const m = Math.round((km * 1000) / 50) * 50\n const [value, unit, digits] = m < 1000 ? [m, 'meter', 0] : [km, 'kilometer', 1]\n return new Intl.NumberFormat(locale, {\n style: 'unit', unit, minimumFractionDigits: digits, maximumFractionDigits: digits,\n }).format(value)\n}\n\n/** Destination for directions: coordinates when valid, else the address text. */\nexport function directionsUrl(\n location: { lat?: number | null; lng?: number | null; address?: string | null; city?: string | null },\n { provider = 'google' }: { provider?: 'google' | 'apple' | 'geo' } = {},\n): string | null {\n const ll = isValidPoint(location) ? `${location.lat},${location.lng}` : null\n const text = [location.address, location.city].filter(Boolean).join(', ')\n const dest = ll ?? text\n if (!dest) return null\n const q = encodeURIComponent(dest)\n if (provider === 'apple') return `https://maps.apple.com/?daddr=${q}`\n if (provider === 'geo') return ll ? `geo:${ll}?q=${ll}` : `geo:0,0?q=${q}`\n return `https://www.google.com/maps/dir/?api=1&destination=${q}`\n}\n\n// --- opening hours -------------------------------------------------------\n\nconst toMin = (t: string | undefined): number => {\n const m = /^(\\d{1,2}):(\\d{2})$/.exec(t ?? '')\n return m ? Number(m[1]) * 60 + Number(m[2]) : NaN\n}\n\ntype Iv = [number, number]\n\n/** Intervals in minutes; an end at or before the start crosses midnight. */\nconst interval = (open: string | undefined, close: string | undefined): Iv[] => {\n const s = toMin(open)\n let e = toMin(close)\n if (Number.isNaN(s) || Number.isNaN(e)) return []\n if (e <= s) e += 1440\n return [[s, e]]\n}\n\nconst dayIntervals = (h: OpeningHours, day: number, date: string): Iv[] => {\n const x = h.exceptions?.find((e) => e.date === date)\n if (x?.closed) return []\n if (x && x.open && x.close) return interval(x.open, x.close)\n return h.weekly.filter((w) => w.day === day).flatMap((w) => interval(w.open, w.close))\n}\n\n/**\n * Whether the place is open at `now` in the IANA `timeZone` (throws RangeError\n * for an unknown zone). Looks 8 days ahead for the next opening. Handles\n * intervals crossing midnight, several per day, dated exceptions and DST.\n */\nexport function openStatus(hours: OpeningHours, timeZone: string, now: Date = new Date()): OpenStatus {\n const fmt = new Intl.DateTimeFormat('en-US', {\n timeZone, hourCycle: 'h23', year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric',\n })\n // Wall-clock minutes since the epoch as seen in `timeZone`.\n const wall = (ms: number): number => {\n const p: Record<string, number> = {}\n for (const { type, value } of fmt.formatToParts(ms)) p[type] = Number(value)\n return Date.UTC(p.year!, p.month! - 1, p.day!, (p.hour ?? 0) % 24, p.minute!) / 60000\n }\n const nowMs = now.getTime()\n const w = wall(nowMs)\n const day0 = Math.floor(w / 1440) * 1440\n // Offset from UTC, in minutes, at an instant.\n const offset = (ms: number): number => wall(ms) - Math.floor(ms / 60000)\n const toInstant = (t: number): string => {\n const guess = (t - offset(nowMs)) * 60000\n return new Date((t - offset(guess)) * 60000).toISOString()\n }\n\n const all: Iv[] = []\n for (let d = -1; d <= 8; d++) {\n const at = new Date((day0 + d * 1440) * 60000)\n const day = at.getUTCDay() || 7\n for (const [s, e] of dayIntervals(hours, day, at.toISOString().slice(0, 10))) all.push([day0 + d * 1440 + s, day0 + d * 1440 + e])\n }\n all.sort((a, b) => a[0] - b[0])\n const merged: Iv[] = []\n for (const iv of all) {\n const last = merged[merged.length - 1]\n if (last && iv[0] <= last[1]) last[1] = Math.max(last[1], iv[1])\n else merged.push([iv[0], iv[1]])\n }\n const current = merged.find(([s, e]) => s <= w && w < e)\n if (current) return { open: true, closesAt: toInstant(current[1]), nextOpenAt: null }\n const next = merged.find(([s]) => s > w)\n return { open: false, closesAt: null, nextOpenAt: next ? toInstant(next[0]) : null }\n}\n\ntype Run = { from: number; to: number; iv: Iv[] }\n\n/** Consecutive days (1..7) with identical intervals, in week order. */\nconst runs = (h: OpeningHours): Run[] => {\n const out: Run[] = []\n for (let day = 1; day <= 7; day++) {\n const iv = h.weekly.filter((x) => x.day === day).flatMap((x) => interval(x.open, x.close)).sort((a, b) => a[0] - b[0])\n if (!iv.length) continue\n const last = out[out.length - 1]\n if (last && last.to === day - 1 && JSON.stringify(last.iv) === JSON.stringify(iv)) last.to = day\n else out.push({ from: day, to: day, iv })\n }\n return out\n}\n\n/** Hour (24 for an end at midnight) and padded minutes of a minute-of-day value. */\nconst hm = (min: number): [number, string] => [min && min % 1440 === 0 ? 24 : Math.floor(min / 60) % 24, String(min % 60).padStart(2, '0')]\n\n/** Compact text, e.g. `Lun–Vie 9:00–19:00 · Sáb 9:00–14:00` (24 h) or `Mon–Fri 9:00 AM–7:00 PM` (en). */\nexport function formatOpeningHours(hours: OpeningHours, locale = 'es-MX'): string {\n const en = /^en/i.test(locale)\n const name = (d: number): string => {\n const s = new Intl.DateTimeFormat(locale, { weekday: 'short', timeZone: 'UTC' }).format(Date.UTC(2024, 0, d)).replace(/\\.$/, '')\n return s.charAt(0).toUpperCase() + s.slice(1)\n }\n const time = (min: number): string => {\n const [h, m] = hm(min)\n return en ? `${h % 12 || 12}:${m} ${h % 24 < 12 ? 'AM' : 'PM'}` : `${h}:${m}`\n }\n return runs(hours)\n .map((r) => `${name(r.from)}${r.from === r.to ? '' : '–' + name(r.to)} ${r.iv.map(([s, e]) => `${time(s)}–${time(e)}`).join(', ')}`)\n .join(' · ')\n}\n\n/** schema.org `openingHours` strings, one per interval, e.g. `Mo-Fr 09:00-19:00`. */\nexport function toSchemaOpeningHours(hours: OpeningHours): string[] {\n const code = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su']\n const t = (min: number): string => { const [h, m] = hm(min); return `${String(h).padStart(2, '0')}:${m}` }\n return runs(hours).flatMap((r) =>\n r.iv.map(([s, e]) => `${code[r.from - 1]}${r.from === r.to ? '' : '-' + code[r.to - 1]} ${t(s)}-${t(e)}`),\n )\n}\n","import type { Money } from './types.js'\n\nexport type FormatMoneyOptions = {\n /** Drop `.00` when the amount is a whole number. */\n withoutTrailingZeros?: boolean\n /** Format as a plain number, without the currency symbol. */\n withoutCurrency?: boolean\n /** `symbol` (default), `narrowSymbol`, `code` or `name`. */\n currencyDisplay?: 'symbol' | 'narrowSymbol' | 'code' | 'name'\n}\n\n/** Parses a contract `Money` amount into a JS number (`\"1899.00\"` → `1899`). */\nexport function parseMoney(money: Money | string | null | undefined): number {\n if (money == null) return 0\n const raw = typeof money === 'string' ? money : money.amount\n const n = Number.parseFloat(raw)\n return Number.isFinite(n) ? n : 0\n}\n\n/**\n * Formats `Money` with `Intl.NumberFormat`. Works in every runtime (no DOM).\n * Falls back to `\"<amount> <code>\"` when the runtime lacks the currency.\n */\nexport function formatMoney(money: Money, locale?: string, options: FormatMoneyOptions = {}): string {\n const value = parseMoney(money)\n const whole = Number.isInteger(value)\n const digits = options.withoutTrailingZeros && whole ? 0 : undefined\n try {\n const fmt = new Intl.NumberFormat(locale, {\n ...(options.withoutCurrency\n ? { style: 'decimal', minimumFractionDigits: digits ?? 2, maximumFractionDigits: digits ?? 2 }\n : {\n style: 'currency',\n currency: money.currency_code,\n currencyDisplay: options.currencyDisplay ?? 'symbol',\n ...(digits === 0 ? { minimumFractionDigits: 0, maximumFractionDigits: 0 } : {}),\n }),\n })\n return fmt.format(value)\n } catch {\n const amount = digits === 0 ? String(value) : value.toFixed(2)\n return options.withoutCurrency ? amount : `${amount} ${money.currency_code}`\n }\n}\n\n/** Builds a `Money` from a number, rounding to cents. */\nexport function toMoney(value: number, currencyCode: string): Money {\n return { amount: (Math.round(value * 100) / 100).toFixed(2), currency_code: currencyCode }\n}\n\n/**\n * True for public (`pk_`) tokens, the only ones that may reach a browser.\n * Private (`sk_`) tokens must stay on the server.\n */\nexport function isTokenPublishable(token: string | null | undefined): boolean {\n return typeof token === 'string' && token.startsWith('pk_')\n}\n","import type { ProductSort } from './types.js'\n\nexport type QueryValue = string | number | boolean | null | undefined\nexport type QueryParams = Record<string, QueryValue | QueryValue[]>\n\nexport type PaginationParams = {\n /** Page size (1–100; articles accept at most 50). */\n first?: number\n /** Cursor from `page_info.end_cursor`. */\n after?: string | null\n}\n\nexport type ProductListParams = PaginationParams & {\n /** Free-text search. */\n q?: string\n /** Collection handle. */\n collection?: string\n sort?: ProductSort\n /** Only products available for sale. */\n available?: boolean\n price_min?: number | string\n price_max?: number | string\n /**\n * Attribute filters, serialized as repeated `filter.<key>=<value>` params.\n * Values of one key are OR-ed; different keys are AND-ed.\n * e.g. `{ vendor: ['A', 'B'], rim: 16 }`.\n */\n filters?: Record<string, QueryValue | QueryValue[]>\n /** Restrict to these handles (max 100). Serialized comma-separated. */\n handles?: string[]\n /**\n * Only products carrying at least one of these tags (OR, at most 5 of 120 characters; contract 1.9). Serialized\n * comma-separated. A parts store passes `fitTagsAny(fitKey)` (`fit:<key>`, `fit:universal`); any tag works.\n */\n tags_any?: string[]\n}\n\nexport type CollectionListParams = PaginationParams\n\nexport type ArticleListParams = Omit<PaginationParams, 'first'> & {\n /** Page size (1–50). The API answers 400 `validation` above 50. */\n first?: number\n tag?: string\n q?: string\n}\n\n/** Appends params to a URLSearchParams, repeating keys for arrays and skipping nullish values. */\nexport function appendParams(search: URLSearchParams, params: QueryParams | undefined): URLSearchParams {\n if (!params) return search\n for (const [key, raw] of Object.entries(params)) {\n const values = Array.isArray(raw) ? raw : [raw]\n for (const v of values) {\n if (v === undefined || v === null || v === '') continue\n search.append(key, String(v))\n }\n }\n return search\n}\n\n/** Serializes product list params per the contract (`filter.<attr>` repeated, `handles` comma-separated). */\nexport function productListQuery(params: ProductListParams = {}): URLSearchParams {\n const { filters, handles, tags_any, ...rest } = params\n const search = appendParams(new URLSearchParams(), rest as QueryParams)\n if (handles && handles.length > 0) search.set('handles', handles.join(','))\n if (tags_any && tags_any.length > 0) {\n if (tags_any.length > 5) throw new RangeError('tags_any takes at most 5 tags')\n // The API splits on commas: a tag that holds one would become two.\n if (tags_any.some((t) => t.includes(',') || t.length > 120)) throw new TypeError('tags_any: a tag has at most 120 characters and no comma')\n search.set('tags_any', tags_any.join(','))\n }\n if (filters) {\n for (const [key, raw] of Object.entries(filters)) {\n const name = key.startsWith('filter.') ? key : `filter.${key}`\n appendParams(search, { [name]: raw })\n }\n }\n return search\n}\n\n/** Reads `filter.<key>` params back into a filters record (useful in route loaders). */\nexport function parseProductFilters(search: URLSearchParams): Record<string, string[]> {\n const out: Record<string, string[]> = {}\n for (const [key, value] of search) {\n if (!key.startsWith('filter.')) continue\n const name = key.slice('filter.'.length)\n ;(out[name] ??= []).push(value)\n }\n return out\n}\n","import type { AccountDeleteInput, CustomerSessionInfo, DataExportFile, ReauthInput, ReauthResult } from './account-settings.js'\nimport { StorefrontError, defaultCodeForStatus } from './errors.js'\nimport { isValidPoint, type GeoPoint } from './geo.js'\nimport { isTokenPublishable } from './money.js'\nimport {\n appendParams,\n productListQuery,\n type ArticleListParams,\n type CollectionListParams,\n type PaginationParams,\n type ProductListParams,\n type QueryParams,\n} from './query.js'\nimport type {\n Address,\n AddressInput,\n Article,\n Cart,\n CartBuyerInput,\n CartLineInput,\n CartLineUpdateInput,\n CartRecommendations,\n PaymentAttemptResult,\n PaymentConfig,\n PaymentSubmitInput,\n PromotionsList,\n RecommendationPlacement,\n CheckoutInput,\n CheckoutResult,\n Collection,\n Connection,\n Customer,\n CustomerIdentifier,\n CustomerCapabilities,\n CustomerUpdateInput,\n CustomerPasswordLoginInput,\n CustomerRegisterInput,\n CustomerRegisterResult,\n CustomerResetPasswordInput,\n CustomerSession,\n CustomerSessionInput,\n CustomerSetPasswordInput,\n CustomerEmailChangeConfirmInput,\n CustomerEmailChangeInput,\n CustomerEmailChangeRequested,\n CustomerEmailCodeInput,\n CustomerVerifyRegistrationInput,\n DeliveryInput,\n DeliveryOptions,\n PaymentMethods,\n FiscalProfile,\n FiscalProfileInput,\n InvoiceFile,\n InvoiceFileKind,\n InvoiceRequest,\n Location,\n LocationListParams,\n NearestLocation,\n InvoiceResult,\n Menu,\n Order,\n Page,\n PendingPayment,\n Product,\n ProductConnection,\n Region,\n RegionPostalCode,\n AddressSuggestions,\n ReturnRequest,\n ReturnRequestInput,\n Shop,\n RestockSubscriptionInput,\n RestockSubscriptionResult,\n StockLevel,\n StorefrontErrorBody,\n Subject,\n SubjectInput,\n SubjectKind,\n SubjectPatch,\n Theme,\n TokenIntrospection,\n} from './types.js'\n\nexport type FetchLike = (input: string | URL | Request, init?: RequestInit) => Promise<Response>\n\n/** Context passed to `onRequest` / `onResponse` hooks. */\nexport type StorefrontRequestContext = {\n method: string\n /** Absolute URL, including the query string. */\n url: string\n /** Route path relative to `baseUrl`, e.g. `/storefront/products/abc`. */\n path: string\n /** Final `RequestInit` (headers already merged). Hooks may mutate it. */\n init: RequestInit & { headers: Headers }\n /** Per-call options as given by the caller. */\n options: RequestOptions\n}\n\nexport type StorefrontResponseContext = StorefrontRequestContext & {\n response: Response\n /** Milliseconds spent waiting for the response. */\n durationMs: number\n}\n\nexport type StorefrontClientOptions = {\n /** Base URL of the gateway, e.g. `https://ops.example.com/api/gw`. Routes are appended as `/storefront/...`. */\n baseUrl: string\n /**\n * `pk_...` (browser) or `sk_...` (server only). Sent as `Authorization: Bearer <token>`. A function is called on\n * EVERY request, so a token read from a file (`createFileTokenSource` in `@asteby/storefront/node`) can rotate\n * without restarting the server.\n */\n token: string | (() => string)\n /** Buyer session (`X-Customer-Token`) for `/storefront/customer/*` routes. */\n customerToken?: string | null\n /** Custom fetch (defaults to `globalThis.fetch`). */\n fetch?: FetchLike\n /** Sent as `Accept-Language`. */\n locale?: string\n /**\n * Public host of the storefront (`godsnutrition.com`), sent as `X-Storefront-Domain`. Platform (`pt_`)\n * tokens need it to pick the organization; with an org-scoped token it only scopes the market.\n */\n domain?: string\n /**\n * Market the request is for (`mx`, `us`), sent as `<domain>#<market>` in `X-Storefront-Domain`. It lets ONE\n * public domain serve several markets (the storefront routes by path prefix, e.g. `/us`): OPS honors it\n * when the organization has that market active and otherwise falls back to the domain's own market.\n * Ignored without `domain`.\n */\n market?: string\n /** Extra headers on every request. */\n headers?: Record<string, string>\n /**\n * IP address of the shopper, for SERVER-side calls (SSR, route actions) made with an\n * `sk_`/`pt_` token. Sent as `X-Storefront-Client-IP`, which the gateway honors only for\n * tokens issued with the `trust_client_ip` option: the rate limit is then charged per\n * shopper instead of to the store's single token bucket, and the OTP flow limits the\n * shopper's IP instead of the server's. Pass the IP from your own connection or trusted\n * proxy, never from a header the browser can forge. Never sent with a `pk_` token (the\n * gateway already separates those by caller IP). Invalid values are dropped.\n */\n clientIp?: string | null\n /** Abort requests that take longer than this (default: no timeout). */\n timeoutMs?: number\n /**\n * Runs before every request. Return a `Response` to short-circuit the\n * network (e.g. an SSR cache hit); return nothing to continue.\n */\n onRequest?: (ctx: StorefrontRequestContext) => void | Response | Promise<void | Response>\n /** Runs after every response (including short-circuited ones), before parsing. */\n onResponse?: (ctx: StorefrontResponseContext) => void | Promise<void>\n}\n\n/** Per-call options. Unknown keys (e.g. Next.js `next`) are forwarded to `fetch` as-is. */\n/** Query of `client.addressSuggest`. */\nexport type AddressSuggestParams = {\n /** What the shopper typed so far (at least 3 characters). */\n q: string\n /** ISO 3166-1 alpha-2 of the address: candidates of another country are dropped. */\n country?: string\n /** Postal code already chosen: candidates of another code or state are dropped. */\n zip?: string\n /** 1 to 8 (server default 5). */\n limit?: number\n /** Bias point (with `lng`): ranks nearby first, never filters. */\n lat?: number\n lng?: number\n /** Language of the labels (`es`, `en`). Default: `Accept-Language`. */\n locale?: string\n}\n\nexport type RequestOptions = {\n cache?: RequestCache\n signal?: AbortSignal\n /** Framework fetch extensions, forwarded verbatim (e.g. `{ revalidate: 60, tags: ['products'] }`). */\n next?: Record<string, unknown>\n headers?: Record<string, string>\n /** Overrides the client-level timeout for this call. */\n timeoutMs?: number\n /** Overrides the client-level customer token for this call. */\n customerToken?: string | null\n /** Overrides the client-level shopper IP for this call (see `StorefrontClientOptions.clientIp`). */\n clientIp?: string | null\n [key: string]: unknown\n}\n\nexport type WriteOptions = RequestOptions & {\n /** `Idempotency-Key` header. Auto-generated for checkout when omitted. */\n idempotencyKey?: string\n}\n\nexport type PreviewOptions = RequestOptions & {\n /** Signed preview token: returns the draft (`private, no-store`). */\n preview?: string\n}\n\ntype HttpMethod = 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE'\n\ntype RequestSpec = {\n method: HttpMethod\n path: string\n query?: URLSearchParams | QueryParams\n body?: unknown\n options?: WriteOptions\n /** Resolve `null` instead of throwing on 404. */\n nullOn404?: boolean\n /**\n * Never follow a redirect (`redirect: 'error'`, and a redirected answer is refused): for answers that carry the\n * buyer's documents, so neither the customer token nor the request ever travels to another host.\n */\n noRedirect?: boolean\n}\n\nconst OWN_OPTION_KEYS = new Set(['headers', 'timeoutMs', 'customerToken', 'clientIp', 'idempotencyKey', 'preview', 'signal'])\n\n/** Header the gateway reads (only for tokens with `trust_client_ip`). */\nexport const CLIENT_IP_HEADER = 'X-Storefront-Client-IP'\n\n/**\n * Returns the single IP literal in `raw`, or undefined. Takes the form a server hands over\n * (`::ffff:1.2.3.4`, `[2001:db8::1]`) and rejects lists, ports, zones and text so the\n * header is never a forgery vector.\n */\nexport function normalizeClientIp(raw: string | null | undefined): string | undefined {\n if (!raw) return undefined\n let v = raw.trim()\n if (v.startsWith('[') && v.endsWith(']')) v = v.slice(1, -1)\n if (!v || v.length > 45 || /[\\s,%/]/.test(v)) return undefined\n if (/^[0-9]{1,3}(\\.[0-9]{1,3}){3}$/.test(v)) {\n return v.split('.').every((o) => Number(o) <= 255) ? v : undefined\n }\n // IPv6 (incl. IPv4-mapped): hex groups and colons, at most one \"::\".\n if (!v.includes(':') || !/^[0-9a-fA-F:.]+$/.test(v) || v.split('::').length > 2) return undefined\n try {\n new URL(`http://[${v}]/`)\n } catch {\n return undefined\n }\n return v\n}\n\n/** Generates an idempotency key (crypto.randomUUID when available). */\nexport function generateIdempotencyKey(): string {\n const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto\n if (c?.randomUUID) return c.randomUUID()\n // Non-cryptographic fallback for very old runtimes; the key only needs to be unique.\n return 'idem-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2) + Math.random().toString(36).slice(2)\n}\n\nfunction joinUrl(baseUrl: string, path: string): string {\n return baseUrl.replace(/\\/+$/, '') + path\n}\n\nfunction enc(segment: string): string {\n // `.` and `..` (also as `%2e`) are dot segments: the URL parser would resolve them and the request would land on\n // another route with the same credentials.\n if (typeof segment !== 'string' || /^(?:\\.|%2e){1,2}$/i.test(segment)) throw new TypeError(`Invalid path segment: ${String(segment)}`)\n return encodeURIComponent(segment)\n}\n\nfunction linkSignals(signals: (AbortSignal | undefined)[]): { signal: AbortSignal | undefined; cleanup: () => void } {\n const active = signals.filter((s): s is AbortSignal => !!s)\n if (active.length === 0) return { signal: undefined, cleanup: () => {} }\n if (active.length === 1) return { signal: active[0], cleanup: () => {} }\n const controller = new AbortController()\n const listeners: [AbortSignal, () => void][] = []\n for (const s of active) {\n if (s.aborted) {\n controller.abort(s.reason)\n break\n }\n const on = () => controller.abort(s.reason)\n s.addEventListener('abort', on, { once: true })\n listeners.push([s, on])\n }\n return {\n signal: controller.signal,\n cleanup: () => listeners.forEach(([s, on]) => s.removeEventListener('abort', on)),\n }\n}\n\nfunction scopeList(raw: unknown): string[] {\n return Array.isArray(raw) ? raw.filter((s): s is string => typeof s === 'string' && s.length > 0) : []\n}\n\nasync function readError(res: Response, url: string): Promise<StorefrontError> {\n let body: Partial<StorefrontErrorBody> | undefined\n try {\n const text = await res.text()\n body = text ? (JSON.parse(text) as Partial<StorefrontErrorBody>) : undefined\n } catch {\n body = undefined\n }\n const e = body?.error\n // The gateway may put `code` / `required_scopes` at the top level or inside `error` (or its `details`).\n const top = body as { code?: unknown; required_scopes?: unknown } | undefined\n const code = e?.code ?? (typeof top?.code === 'string' ? top.code : undefined)\n const requiredScopes = code === 'insufficient_scope' ? scopeList(e?.required_scopes ?? top?.required_scopes ?? (e?.details as { required_scopes?: unknown } | undefined)?.required_scopes) : []\n return new StorefrontError({\n status: res.status,\n code: code ?? defaultCodeForStatus(res.status),\n ...(requiredScopes.length ? { requiredScopes } : {}),\n message: e?.message ?? `Storefront API responded ${res.status}${res.statusText ? ' ' + res.statusText : ''}`,\n ...(e?.field ? { field: e.field } : {}),\n ...(e?.details !== undefined ? { details: e.details } : {}),\n ...(typeof e?.retryable === 'boolean' ? { retryable: e.retryable } : {}),\n ...(typeof e?.retry_after === 'number' && e.retry_after > 0 ? { retryAfter: e.retry_after } : {}),\n ...(typeof e?.checkout_id === 'string' && e.checkout_id ? { checkoutId: e.checkout_id } : {}),\n ...(e?.cost !== undefined ? { cost: e.cost } : {}),\n ...(typeof e?.message_en === 'string' && e.message_en ? { messageEn: e.message_en } : {}),\n url,\n })\n}\n\nexport function createStorefrontClient(config: StorefrontClientOptions) {\n if (!config.baseUrl) throw new TypeError('createStorefrontClient: baseUrl is required')\n if (!config.token) throw new TypeError('createStorefrontClient: token is required')\n const currentToken = (): string => {\n const t = typeof config.token === 'function' ? config.token() : config.token\n if (!t) throw new StorefrontError({ status: 0, code: 'unauthorized', message: 'Storefront token is empty (token source returned nothing)' })\n return t\n }\n const isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined'\n const initialToken = typeof config.token === 'string' ? config.token : ''\n if (isBrowser && initialToken.startsWith('sk_')) {\n console.warn('[@asteby/storefront] A private sk_ token is being used in a browser. Use a public pk_ token instead.')\n }\n\n async function request<T>(spec: RequestSpec & { nullOn404: true }): Promise<T | null>\n async function request<T>(spec: RequestSpec): Promise<T>\n async function request<T>(spec: RequestSpec): Promise<T | null> {\n const fetchImpl: FetchLike | undefined = config.fetch ?? (globalThis.fetch ? globalThis.fetch.bind(globalThis) : undefined)\n if (!fetchImpl) throw new TypeError('createStorefrontClient: no fetch available; pass `fetch` in options')\n\n const options: WriteOptions = spec.options ?? {}\n const search = spec.query instanceof URLSearchParams ? spec.query : appendParams(new URLSearchParams(), spec.query)\n const qs = search.toString()\n const url = joinUrl(config.baseUrl, spec.path) + (qs ? `?${qs}` : '')\n\n const headers = new Headers(config.headers)\n headers.set('Accept', 'application/json')\n const token = currentToken()\n headers.set('Authorization', `Bearer ${token}`)\n if (config.locale) headers.set('Accept-Language', config.locale)\n if (config.domain) headers.set('X-Storefront-Domain', storefrontDomainHeader(config.domain, config.market))\n const customerToken = options.customerToken !== undefined ? options.customerToken : config.customerToken\n if (customerToken) headers.set('X-Customer-Token', customerToken)\n const clientIp = options.clientIp !== undefined ? options.clientIp : config.clientIp\n // Server-side tokens only: a pk_ token already gets a per-caller bucket from the gateway.\n const ip = isTokenPublishable(token) ? undefined : normalizeClientIp(clientIp)\n if (ip) headers.set(CLIENT_IP_HEADER, ip)\n if (options.idempotencyKey) headers.set('Idempotency-Key', options.idempotencyKey)\n if (spec.body !== undefined) headers.set('Content-Type', 'application/json')\n for (const [k, v] of Object.entries(options.headers ?? {})) headers.set(k, v)\n\n // Forward passthrough options (cache, next, ...) to fetch.\n const passthrough: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(options)) if (!OWN_OPTION_KEYS.has(k) && v !== undefined) passthrough[k] = v\n\n const timeoutMs = options.timeoutMs ?? config.timeoutMs\n const timeoutController = timeoutMs && timeoutMs > 0 ? new AbortController() : undefined\n const timer = timeoutController\n ? setTimeout(() => timeoutController.abort(new StorefrontError({ status: 0, code: 'timeout', message: `Request timed out after ${timeoutMs}ms`, url })), timeoutMs)\n : undefined\n const linked = linkSignals([options.signal, timeoutController?.signal])\n\n const init: RequestInit & { headers: Headers } = {\n ...passthrough,\n ...(spec.noRedirect ? { redirect: 'error' as const } : {}),\n method: spec.method,\n headers,\n ...(spec.body !== undefined ? { body: JSON.stringify(spec.body) } : {}),\n ...(linked.signal ? { signal: linked.signal } : {}),\n }\n const ctx: StorefrontRequestContext = { method: spec.method, url, path: spec.path, init, options }\n\n const started = Date.now()\n let res: Response\n try {\n const hooked = config.onRequest ? await config.onRequest(ctx) : undefined\n res = hooked instanceof Response ? hooked : await fetchImpl(url, init)\n } catch (err) {\n if (timeoutController?.signal.aborted) {\n throw new StorefrontError({ status: 0, code: 'timeout', message: `Request timed out after ${timeoutMs}ms`, url, cause: err })\n }\n if (options.signal?.aborted) {\n throw new StorefrontError({ status: 0, code: 'aborted', message: 'Request aborted', url, cause: err })\n }\n if (err instanceof StorefrontError) throw err\n throw new StorefrontError({ status: 0, code: 'network', message: err instanceof Error ? err.message : 'Network error', url, cause: err })\n } finally {\n if (timer) clearTimeout(timer)\n linked.cleanup()\n }\n\n if (config.onResponse) await config.onResponse({ ...ctx, response: res, durationMs: Date.now() - started })\n\n if (spec.noRedirect && res.redirected) {\n await res.text().catch(() => undefined)\n throw new StorefrontError({ status: 502, code: 'invalid_response', message: 'The answer was redirected; it is refused', url })\n }\n\n if (res.status === 404 && spec.nullOn404) {\n // Drain the body so the connection can be reused.\n await res.text().catch(() => undefined)\n return null\n }\n if (res.status === 304) {\n throw new StorefrontError({ status: 304, code: 'not_modified', message: 'Not modified', url })\n }\n if (!res.ok) throw await readError(res, url)\n if (res.status === 204) return undefined as T\n\n const text = await res.text()\n if (!text) return undefined as T\n try {\n return JSON.parse(text) as T\n } catch (err) {\n throw new StorefrontError({ status: res.status, code: 'invalid_response', message: 'Response is not valid JSON', url, cause: err })\n }\n }\n\n const get = <T>(path: string, query?: URLSearchParams | QueryParams, options?: RequestOptions) =>\n request<T>({ method: 'GET', path, ...(query ? { query } : {}), ...(options ? { options } : {}) })\n const getOrNull = <T>(path: string, query?: URLSearchParams | QueryParams, options?: RequestOptions) =>\n request<T>({ method: 'GET', path, nullOn404: true, ...(query ? { query } : {}), ...(options ? { options } : {}) })\n const write = <T>(method: HttpMethod, path: string, body?: unknown, options?: WriteOptions) =>\n request<T>({ method, path, ...(body !== undefined ? { body } : {}), ...(options ? { options } : {}) })\n\n const cartPath = (id: string, rest = '') => `/storefront/carts/${enc(id)}${rest}`\n const previewQuery = (options?: PreviewOptions) => (options?.preview ? { preview: options.preview } : undefined)\n\n const client = {\n /** Resolved configuration (read-only). */\n config: Object.freeze({ ...config }) as Readonly<StorefrontClientOptions>,\n\n /** Low-level escape hatch: any route under `baseUrl`. */\n request,\n\n token: {\n /**\n * What the token in use is and can do (`GET {baseUrl}/_token`, a gateway route, not a `/storefront` one).\n * Needs no scope, so it answers even when the token is under-provisioned: `missing_scopes` says what to repair.\n */\n introspect: async (options?: RequestOptions): Promise<TokenIntrospection> => {\n // OPS answers with the kernel envelope `{success, data}`; a flat object is accepted too.\n const body = await get<TokenIntrospection | { success?: boolean; data?: TokenIntrospection }>('/_token', undefined, options)\n const env = body as { success?: unknown; data?: TokenIntrospection }\n return typeof env?.success === 'boolean' && env.data ? env.data : (body as TokenIntrospection)\n },\n },\n\n /** Returns a new client that sends the given buyer session token. */\n withCustomerToken(customerToken: string | null) {\n return createStorefrontClient({ ...config, customerToken })\n },\n\n /** Returns a new client that reports the shopper's IP (`X-Storefront-Client-IP`) on every call. */\n withClientIp(clientIp: string | null | undefined) {\n return createStorefrontClient({ ...config, clientIp: clientIp ?? null })\n },\n\n shop: {\n get: (options?: RequestOptions) => get<Shop>('/storefront/shop', undefined, options),\n },\n\n /**\n * How the market formats, taxes, addresses and invoices (`fiscal_id` carries the tax-id pattern, the regimes,\n * the invoice uses and the identity documents the buyer can upload). Cacheable; `null` when the organization\n * has no region configured.\n */\n region: (options?: RequestOptions) => getOrNull<Region>('/storefront/region', undefined, options),\n\n /**\n * State and municipality of a postal code from the region pack (`null` when the code is not in its catalog, or the\n * organization has no region pack). The source of `AddressFields.lookupPostalCode`: the state it fills is the one\n * the server checks the address against.\n */\n postalCode: (zip: string, options?: RequestOptions) => getOrNull<RegionPostalCode>('/storefront/region/postal-code', { zip: zip.trim() }, options),\n\n /**\n * Street and number suggestions for the address form (`GET /storefront/address/suggest`), from the geocoding\n * provider the market is assigned (a self-hosted Photon, ...). The server drops candidates of another country, postal\n * code or state than the catalog's, and answers `{ suggestions: [], available: false }` when there is no provider:\n * it never fails because of one. `q` needs at least 3 characters (the call rejects shorter ones without a request).\n * Browser forms call it through `AddressFields.suggestAddress`; do not call it per keystroke without a debounce.\n */\n addressSuggest: (params: AddressSuggestParams, options?: RequestOptions) => {\n const q = params.q.trim().replace(/\\s+/g, ' ')\n if ([...q].length < 3) return Promise.reject(new RangeError('addressSuggest: q needs at least 3 characters'))\n return get<AddressSuggestions>(\n '/storefront/address/suggest',\n { q, country: params.country?.toUpperCase(), zip: params.zip?.trim(), limit: params.limit, lat: params.lat, lng: params.lng, locale: params.locale },\n options,\n )\n },\n\n products: {\n list: (params?: ProductListParams, options?: RequestOptions) =>\n get<ProductConnection>('/storefront/products', productListQuery(params), options),\n /** `null` when the product does not exist or is unpublished. */\n get: (handle: string, options?: RequestOptions) =>\n getOrNull<Product>(`/storefront/products/${enc(handle)}`, undefined, options),\n recommendations: (handle: string, options?: RequestOptions) =>\n get<{ nodes: Product[] }>(`/storefront/products/${enc(handle)}/recommendations`, undefined, options),\n },\n\n collections: {\n list: (params?: CollectionListParams, options?: RequestOptions) =>\n get<Connection<Collection>>('/storefront/collections', params as QueryParams, options),\n /** `null` when the collection does not exist. */\n get: (handle: string, options?: RequestOptions) =>\n getOrNull<Collection>(`/storefront/collections/${enc(handle)}`, undefined, options),\n },\n\n locations: {\n /** Branches of the shop. With `postal_code` they come ordered by distance (`distance_km`). */\n list: (params?: LocationListParams, options?: RequestOptions) =>\n get<{ nodes: Location[] }>('/storefront/locations', params as QueryParams, options),\n /** `null` when the branch does not exist or is not visible. */\n get: (id: string, options?: RequestOptions) =>\n getOrNull<Location>(`/storefront/locations/${enc(id)}`, undefined, options),\n /**\n * Branches ordered by distance to a point, closest first. The server rounds the coordinates (0.01°, ~1 km)\n * and never stores them; this client does not log or keep them either. The answer is `private, no-store`\n * (it depends on the buyer's position), so do not put it in a shared cache. Note `onRequest` hooks and\n * `fetch` wrappers do see the URL: do not log it. Throws `TypeError` for an invalid point.\n */\n nearest: (point: GeoPoint, options?: RequestOptions) => {\n if (!isValidPoint(point)) throw new TypeError('locations.nearest: lat/lng must be a valid point')\n return get<{ nodes: NearestLocation[] }>('/storefront/locations/nearest', { lat: point.lat, lng: point.lng }, { cache: 'no-store', ...options })\n },\n },\n\n stock: {\n /** Stock for up to 250 SKUs. */\n get: (skus: string[], options?: RequestOptions) =>\n get<{ nodes: StockLevel[] }>('/storefront/stock', { sku: skus }, options),\n },\n\n restock: {\n /**\n * \"Notify me when it is back\". Idempotent per contact + SKU; always answers `202 pending`.\n * Only offered when `availability.notify_available` is true. Needs `customer:write`.\n */\n subscribe: (input: RestockSubscriptionInput, options?: WriteOptions) =>\n write<RestockSubscriptionResult>('POST', '/storefront/restock-subscriptions', input, options),\n },\n\n carts: {\n create: (input: { lines?: CartLineInput[] } = {}, options?: WriteOptions) =>\n write<Cart>('POST', '/storefront/carts', input, options),\n /** `null` when the cart does not exist (e.g. expired cookie). */\n get: (id: string, options?: RequestOptions) => getOrNull<Cart>(cartPath(id), undefined, options),\n addLines: (id: string, lines: CartLineInput[], options?: WriteOptions) =>\n write<Cart>('POST', cartPath(id, '/lines'), { lines }, options),\n /** Quantity `0` removes the line. */\n updateLines: (id: string, lines: CartLineUpdateInput[], options?: WriteOptions) =>\n write<Cart>('PATCH', cartPath(id, '/lines'), { lines }, options),\n removeLines: (id: string, lineIds: string[], options?: WriteOptions) =>\n write<Cart>('PATCH', cartPath(id, '/lines'), { lines: lineIds.map((lid) => ({ id: lid, quantity: 0 })) }, options),\n setDiscountCodes: (id: string, codes: string[], options?: WriteOptions) =>\n write<Cart>('PUT', cartPath(id, '/discount-codes'), { codes }, options),\n setBuyer: (id: string, buyer: CartBuyerInput, options?: WriteOptions) =>\n write<Cart>('PUT', cartPath(id, '/buyer'), buyer, options),\n setShippingAddress: (id: string, address: AddressInput, options?: WriteOptions) =>\n write<Cart>('PUT', cartPath(id, '/shipping-address'), address, options),\n deliveryOptions: (id: string, options?: RequestOptions) =>\n get<DeliveryOptions>(cartPath(id, '/delivery-options'), undefined, options),\n /** Payment providers active for the cart's market; send the chosen `key` as `payment_method`. */\n paymentMethods: (id: string, options?: RequestOptions) =>\n get<PaymentMethods>(cartPath(id, '/payment-methods'), undefined, options),\n setDelivery: (id: string, delivery: DeliveryInput, options?: WriteOptions) =>\n write<Cart>('PUT', cartPath(id, '/delivery'), delivery, options),\n /** Order note (up to 1000 characters). `null` or empty clears it. */\n setNote: (id: string, note: string | null, options?: WriteOptions) =>\n write<Cart>('PUT', cartPath(id, '/note'), { note }, options),\n /**\n * Asks for an invoice for this cart (`null` or `{ requested: false }` withdraws it). The server validates the\n * data against the region BEFORE any charge: `422` with `field: 'invoice.<field>'` (e.g. `invoice.tax_regime`)\n * names what to fix. `409 already_checked_out` when the cart is already an order. Checkout uses it when\n * `CheckoutInput.invoice` is omitted.\n */\n setInvoice: (id: string, invoice: InvoiceRequest | null, options?: WriteOptions) =>\n write<Cart>('PUT', cartPath(id, '/invoice'), invoice ?? { requested: false }, options),\n /**\n * Cross-sell suggestions: only sellable variants, with `unlocks` when adding one reaches the next\n * discount tier. `first` 1-8 (default 4). `private, no-store`; ask on demand, not on every render.\n */\n recommendations: (id: string, params: { first?: number; placement?: RecommendationPlacement } = {}, options?: RequestOptions) =>\n get<CartRecommendations>(cartPath(id, '/recommendations'), params as QueryParams, options),\n /** Reserves stock and creates the order. Sends `Idempotency-Key` (auto-generated if omitted). */\n checkout: (id: string, input: CheckoutInput, options: WriteOptions = {}) =>\n write<CheckoutResult>('POST', cartPath(id, '/checkout'), input, {\n ...options,\n idempotencyKey: options.idempotencyKey ?? generateIdempotencyKey(),\n }),\n },\n\n promotions: {\n /** Public promotions and the entry pop-up announcement for the request's market (cacheable). */\n list: (options?: RequestOptions) => get<PromotionsList>('/storefront/promotions', undefined, options),\n },\n\n checkouts: {\n /** What to mount for an embedded checkout (public key, options, amount) and whether it can still be paid. Never cache. */\n paymentConfig: (id: string, options?: RequestOptions) =>\n getOrNull<PaymentConfig>(`/storefront/checkouts/${enc(id)}/payment-config`, undefined, options),\n /**\n * Pays a checkout in the page. The browser brings only what the provider SDK returned (`provider_data`);\n * the amount is the server's. `idempotencyKey` is REQUIRED (use `paymentIdempotencyKey(checkoutId, attempt)`):\n * repeating a call with the same key never charges twice. Needs a server token (`checkout:write`).\n */\n pay: (id: string, input: PaymentSubmitInput, options: WriteOptions & { idempotencyKey: string }) => {\n if (!options || typeof options.idempotencyKey !== 'string' || !options.idempotencyKey.trim()) {\n throw new TypeError('checkouts.pay: idempotencyKey is required')\n }\n return write<PaymentAttemptResult>('POST', `/storefront/checkouts/${enc(id)}/payment`, input, options)\n },\n /**\n * Reads a placed checkout (same shape as the `carts.checkout` result). `order.number` is `null` until OPS\n * has created the order (a few hundred ms after checkout); poll once or twice and, if it is still `null`,\n * keep telling the buyer the number will arrive by email. Needs a server token (`checkout:write`).\n * `null` when the checkout does not exist. Never cache.\n */\n get: (id: string, options?: RequestOptions) =>\n getOrNull<CheckoutResult>(`/storefront/checkouts/${enc(id)}`, undefined, options),\n },\n\n customer: {\n /** Sends a one-time code by email or SMS/WhatsApp. */\n requestOtp: (identifier: CustomerIdentifier, options?: WriteOptions) =>\n write<void>('POST', '/storefront/customer/otp', identifier, options),\n /** Exchanges the code for a buyer session (`token` goes in `customerToken`). */\n createSession: (input: CustomerSessionInput, options?: WriteOptions) =>\n write<CustomerSession>('POST', '/storefront/customer/session', input, options),\n /** What the store supports (password login, email verification, OTP channels). Drives which forms to show. */\n capabilities: (options?: RequestOptions) =>\n get<CustomerCapabilities>('/storefront/customer/capabilities', undefined, options),\n /**\n * Creates an account with email + password. `verification_required` (202): a code was emailed, finish with\n * `verifyRegistration`. `created` (201): the account exists and `session` is ready. `409` when the email is taken.\n */\n register: async (input: CustomerRegisterInput, options?: WriteOptions): Promise<CustomerRegisterResult> => {\n const res = await write<{ status: 'verification_required' } | CustomerSession>('POST', '/storefront/customer/register', input, options)\n return res && 'token' in res ? { status: 'created', session: res } : { status: 'verification_required' }\n },\n /** Confirms the emailed registration code and returns the new buyer session. */\n verifyRegistration: (input: CustomerVerifyRegistrationInput, options?: WriteOptions) =>\n write<CustomerSession>('POST', '/storefront/customer/register/verify', input, options),\n /** Email + password login. `401` for wrong credentials. */\n loginWithPassword: (input: CustomerPasswordLoginInput, options?: WriteOptions) =>\n write<CustomerSession>('POST', '/storefront/customer/login', input, options),\n /** Sets or changes the password of the signed-in buyer (`options.customerToken`, or a `withCustomerToken` client). */\n setPassword: (input: CustomerSetPasswordInput, options?: WriteOptions) =>\n write<void>('PUT', '/storefront/customer/password', input, options),\n /** Resets a forgotten password with the code from `requestOtp({ email })`. */\n resetPassword: (input: CustomerResetPasswordInput, options?: WriteOptions) =>\n write<void>('POST', '/storefront/customer/password/reset', input, options),\n get: (options?: RequestOptions) => get<Customer>('/storefront/customer', undefined, options),\n /** Updates the profile and the saved fiscal data; `fiscal: null` deletes the latter. `422` with `field: 'fiscal.<field>'`. */\n update: (input: CustomerUpdateInput, options?: WriteOptions) =>\n write<Customer>('PATCH', '/storefront/customer', input, options),\n /**\n * Active sessions of the buyer («Devices»; contract 1.9). Private, never cached. The list carries no address\n * and no token: only what the buyer needs to recognize their own devices.\n */\n sessions: {\n list: async (options?: RequestOptions): Promise<CustomerSessionInfo[]> =>\n (await get<{ nodes: CustomerSessionInfo[] }>('/storefront/customer/sessions', undefined, { ...options, cache: 'no-store' })).nodes,\n /** Closes one session. Repeating it is fine. `404` for a session that is not the buyer's. Closing the current one is a sign-out. */\n revoke: (id: string, options?: WriteOptions) =>\n write<void>('DELETE', `/storefront/customer/sessions/${enc(id)}`, undefined, options),\n /** Closes every session except the one making the call. */\n revokeOthers: (options?: WriteOptions) => write<void>('DELETE', '/storefront/customer/sessions/others', undefined, options),\n },\n /**\n * Confirms the buyer's identity again with their password or a sign-in code (`requestOtp` first). The\n * confirmation lasts `valid_for_seconds` (a few minutes) and counts only for the session that made the call;\n * exporting data and deleting the account need it (`403 reauth_required` otherwise, see `isReauthRequired`).\n * A wrong credential is always the same `400`; too many tries is `429` (`StorefrontError.retryAfter`).\n */\n reauth: (input: ReauthInput, options?: WriteOptions) =>\n write<ReauthResult>('POST', '/storefront/customer/reauth', input, options),\n /**\n * The buyer's e-mail from their account (contract 1.15, `capabilities().email_change`). All four calls need the\n * buyer's session; a wrong or expired code is always the same `400` on `code`, too many tries is `429`.\n */\n email: {\n /**\n * Mails a code to the account's CURRENT e-mail so it can be verified. `422` when it is already verified, the\n * account has no e-mail or the store cannot send mail; `429` while a code was just sent.\n */\n requestVerification: (options?: WriteOptions) => write<void>('POST', '/storefront/customer/email/verification', undefined, options),\n /** Verifies the current e-mail with the code; answers the buyer with `email_verified: true`. */\n confirmVerification: (input: CustomerEmailCodeInput, options?: WriteOptions) =>\n write<Customer>('POST', '/storefront/customer/email/verification/confirm', input, options),\n /**\n * Asks to change the e-mail. Needs a recent `reauth` (`403 reauth_required`, see `isReauthRequired`). A code is\n * sent to the NEW address and nothing changes until `confirmChange`. The answer is the same whether or not the\n * new address already has an account (then nothing is sent and the code can never work): word your screen as\n * «if the address can be used, we sent a code». `400` on `email` for an invalid or unchanged address.\n */\n requestChange: (input: CustomerEmailChangeInput, options?: WriteOptions) =>\n write<CustomerEmailChangeRequested>('POST', '/storefront/customer/email/change', input, options),\n /**\n * Confirms the change with the code that arrived at the new address. The other sessions of the account are\n * closed (the one making the call stays) and the answer is the buyer with the new, verified e-mail.\n */\n confirmChange: (input: CustomerEmailChangeConfirmInput, options?: WriteOptions) =>\n write<Customer>('POST', '/storefront/customer/email/change/confirm', input, options),\n },\n /**\n * The buyer's data as a JSON file (contract 1.9, `capabilities().data_export`). Needs a recent `reauth`. It is\n * built on request and is neither stored nor emailed: call it from YOUR server, stream the bytes\n * (`dataExportBytes`, `safeExportFilename`) with `Cache-Control: no-store`, and keep nothing. Three a day per account.\n */\n exportData: async (options?: WriteOptions): Promise<DataExportFile> => {\n const file = await write<DataExportFile>('POST', '/storefront/customer/data-export', undefined, { ...options, cache: 'no-store' })\n if (!file || typeof file.content_base64 !== 'string' || typeof file.filename !== 'string' || typeof file.content_type !== 'string') {\n throw new StorefrontError({ status: 502, code: 'invalid_response', message: 'The data export answer is not a file' })\n }\n return { filename: file.filename, content_type: file.content_type, content_base64: file.content_base64 }\n },\n /**\n * Deletes the buyer's account (contract 1.9, `capabilities().account_delete`). Needs a recent `reauth` and the\n * text the buyer typed in `confirm`. Personal data is erased; orders and invoices are kept by the store.\n * `409` (see `isAccountDeleteBlocked`) while an order is on its way or a payment is pending. Idempotent: a\n * repeat after success is also fine. Afterwards the token is dead: drop it.\n */\n deleteAccount: (input: AccountDeleteInput, options?: WriteOptions) =>\n write<void>('DELETE', '/storefront/customer', input, options),\n orders: (params?: PaginationParams, options?: RequestOptions) =>\n get<Connection<Order>>('/storefront/customer/orders', params as QueryParams, options),\n /** `null` when the order does not exist or belongs to someone else. */\n order: (id: string, options?: RequestOptions) =>\n getOrNull<Order>(`/storefront/customer/orders/${enc(id)}`, undefined, options),\n requestReturn: (orderId: string, input: ReturnRequestInput, options?: WriteOptions) =>\n write<ReturnRequest>('POST', `/storefront/customer/orders/${enc(orderId)}/returns`, input, options),\n requestInvoice: (orderId: string, input: InvoiceRequest, options?: WriteOptions) =>\n write<InvoiceResult>('POST', `/storefront/customer/orders/${enc(orderId)}/invoice`, input, options),\n /**\n * Checkouts waiting for their payment (cash voucher: OXXO, SPEI). They are not orders yet; once the payment\n * confirms they leave this list and show up in `orders`.\n */\n pendingPayments: async (params?: PaginationParams, options?: RequestOptions): Promise<Connection<PendingPayment>> =>\n // An OPS older than the route answers 404: it has no pending payments to list (a 401 still throws).\n (await getOrNull<Connection<PendingPayment>>('/storefront/customer/pending-payments', params as QueryParams, options)) ?? {\n nodes: [],\n page_info: { has_next_page: false, end_cursor: null },\n total_count: 0,\n },\n /**\n * Reads one file (`pdf` | `xml`) of an invoice or credit note of the buyer's order, through the authenticated\n * route (`order_invoice_file`): the answer is the file itself (base64), never a URL, so neither the buyer token\n * nor a link of the PAC reaches the browser. Call it from YOUR server and stream the bytes\n * (`invoiceFileBytes`). `null` when the order, the document or the file does not exist or is not the buyer's.\n */\n invoiceFile: async (orderId: string, invoiceId: string, kind: InvoiceFileKind, options?: RequestOptions): Promise<InvoiceFile | null> => {\n if (kind !== 'pdf' && kind !== 'xml') throw new TypeError(\"invoiceFile: kind must be 'pdf' or 'xml'\")\n const file = await request<InvoiceFile>({\n method: 'GET',\n path: `/storefront/customer/orders/${enc(orderId)}/invoices/${enc(invoiceId)}/${kind}`,\n options: { ...options, cache: 'no-store' },\n nullOn404: true,\n noRedirect: true,\n })\n if (file === null) return null\n if (!file || typeof file.content_base64 !== 'string' || typeof file.filename !== 'string' || typeof file.content_type !== 'string') {\n throw new StorefrontError({ status: 502, code: 'invalid_response', message: 'The invoice file answer is not a file' })\n }\n return { filename: file.filename, content_type: file.content_type, content_base64: file.content_base64 }\n },\n /**\n * Saved fiscal profiles of the buyer (contract 1.9, `capabilities().fiscal_profiles`). Personal data: private,\n * never cached, never logged. `422` with `field: 'fiscal.<field>'` when the region rejects a value; `409` for a\n * repeated tax id or past the limit; `404` for a profile that is not the buyer's.\n */\n fiscalProfiles: {\n list: async (options?: RequestOptions): Promise<FiscalProfile[]> =>\n (await get<{ nodes: FiscalProfile[] }>('/storefront/customer/fiscal-profiles', undefined, { ...options, cache: 'no-store' })).nodes,\n create: (profile: FiscalProfileInput, options?: WriteOptions) =>\n write<FiscalProfile>('POST', '/storefront/customer/fiscal-profiles', profile, options),\n update: (id: string, profile: FiscalProfileInput, options?: WriteOptions) =>\n write<FiscalProfile>('PATCH', `/storefront/customer/fiscal-profiles/${enc(id)}`, profile, options),\n /** Physical delete (a profile leaves nothing behind). A saved default passes to another profile. */\n delete: (id: string, options?: WriteOptions) =>\n write<void>('DELETE', `/storefront/customer/fiscal-profiles/${enc(id)}`, undefined, options),\n },\n /**\n * Saved items of the buyer («My items», «My garage»; contract 1.9, `capabilities().subjects`). Personal data:\n * private, never cached, never logged. `422` with `field: 'attributes.<field>'` when the kind refuses a value\n * (it never echoes it); `409` for an item already saved or past the limit; `429` for too many saves; `404` for\n * an item that is not the buyer's. The server builds `label` and `fit_key`; private fields come back masked.\n */\n subjects: {\n list: async (params?: { kind?: string }, options?: RequestOptions): Promise<Subject[]> =>\n (await get<{ nodes: Subject[] }>('/storefront/customer/subjects', params as QueryParams | undefined, { ...options, cache: 'no-store' })).nodes,\n create: (input: SubjectInput, options?: WriteOptions) => write<Subject>('POST', '/storefront/customer/subjects', input, options),\n update: (id: string, patch: SubjectPatch, options?: WriteOptions) =>\n write<Subject>('PATCH', `/storefront/customer/subjects/${enc(id)}`, patch, options),\n /** Physical delete (the item leaves nothing behind). The default of its kind passes to another item. */\n delete: (id: string, options?: WriteOptions) => write<void>('DELETE', `/storefront/customer/subjects/${enc(id)}`, undefined, options),\n },\n addresses: {\n list: (options?: RequestOptions) => get<{ nodes: Address[] }>('/storefront/customer/addresses', undefined, options),\n create: (address: AddressInput, options?: WriteOptions) =>\n write<Address>('POST', '/storefront/customer/addresses', address, options),\n update: (id: string, address: Partial<AddressInput>, options?: WriteOptions) =>\n write<Address>('PATCH', `/storefront/customer/addresses/${enc(id)}`, address, options),\n delete: (id: string, options?: WriteOptions) =>\n write<void>('DELETE', `/storefront/customer/addresses/${enc(id)}`, undefined, options),\n },\n },\n\n content: {\n /**\n * The kinds of buyer item the organization declares («My garage») and their catalogs (contract 1.9; public,\n * cacheable). `[]` when it declares none or the server predates the route: the store has no such section.\n */\n subjectKinds: async (options?: RequestOptions): Promise<SubjectKind[]> =>\n (await getOrNull<{ nodes: SubjectKind[] }>('/storefront/subject-kinds', undefined, options))?.nodes ?? [],\n theme: (options?: RequestOptions) => get<Theme>('/storefront/content/theme', undefined, options),\n /** `null` when the page does not exist. */\n page: (handle: string, options?: PreviewOptions) =>\n getOrNull<Page>(`/storefront/content/pages/${enc(handle)}`, previewQuery(options), options),\n /** `null` when the menu does not exist. */\n menu: (handle: string, options?: RequestOptions) =>\n getOrNull<Menu>(`/storefront/content/menus/${enc(handle)}`, undefined, options),\n articles: (params?: ArticleListParams, options?: RequestOptions) =>\n get<Connection<Article>>('/storefront/content/articles', params as QueryParams, options),\n /** `null` when the article does not exist. */\n article: (handle: string, options?: PreviewOptions) =>\n getOrNull<Article>(`/storefront/content/articles/${enc(handle)}`, previewQuery(options), options),\n },\n }\n return client\n}\n\nexport type StorefrontClient = ReturnType<typeof createStorefrontClient>\n\n/** `X-Storefront-Domain` value: the host, plus `#<market>` when a valid market code is given. */\nexport function storefrontDomainHeader(domain: string, market?: string | null): string {\n const host = domain.trim()\n const code = (market ?? '').trim().toLowerCase()\n return code && /^[a-z0-9_-]{1,32}$/.test(code) ? `${host}#${code}` : host\n}\n","/**\n * Classification of the failures of a card payment (`POST pay` / `GET status`). No texts, no DOM, no server APIs: the\n * shop's server uses it to answer with `kind` and `retryable`, and the browser transport uses it to decide whether to\n * repeat, ask for the status or give up.\n *\n * Rule that never changes: an INDETERMINATE result (`transient`, `in_progress`) is never charged again with another\n * idempotency key; it is repeated with the SAME key or its status is read.\n */\n\nexport type PaymentErrorClassKind =\n /** OPS or the provider did not answer (5xx, timeout, network). The charge may or may not have happened. */\n | 'transient'\n /** A payment is already in progress for this order (409): read the status, do not charge again. */\n | 'in_progress'\n /** Too many attempts (429). */\n | 'rate_limited'\n /** Credentials or configuration of the merchant with the provider: not the buyer's fault. */\n | 'merchant_config'\n /** The provider refused the charge at API level (`payment_provider_rejected`): definitive, nothing was charged. */\n | 'provider_declined'\n /** The cart already became an order and OPS will not open a new attempt (`422 invalid_state`). */\n | 'stale_checkout'\n | 'expired'\n | 'price_mismatch'\n | 'store_closed'\n | 'validation'\n | 'other'\n\nexport type PaymentErrorClass = { kind: PaymentErrorClassKind; retryable: boolean }\n\nexport type PaymentErrorLike = {\n status?: number | null\n code?: string | null\n field?: string | null\n /** `error.retryable` as OPS declared it (`StorefrontError.retryable`). */\n retryable?: boolean | null\n /** `error.checkout_id` (`StorefrontError.checkoutId`). */\n checkoutId?: string | null\n /** Raw `error.details`; a `retryable` inside is honoured too (older bodies). */\n details?: unknown\n}\n\n/** Did OPS expressly say the failure must NOT be repeated (`retryable: false`, on the error or inside `details`)? */\nexport function opsSaysNotRetryable(err: PaymentErrorLike): boolean {\n if (err.retryable === false) return true\n const d = err.details\n return typeof d === 'object' && d !== null && (d as { retryable?: unknown }).retryable === false\n}\n\n/** Field the shop's server sets when IT refuses a payment row that is not offered (so it is not read as a stale checkout). */\nexport const PAYMENT_CHOICE_REFUSED_FIELD = 'payment_choice'\n\nconst MERCHANT_CONFIG_CODE = /credential|not_configured|unconfigured|invalid_access|access_token|provider_config|merchant|invalid_public_key|unauthorized/i\n\n/**\n * What a payment failure means and whether repeating it can help. What OPS declares (`retryable`, stable codes) wins\n * over the HTTP status: a 502 with a stable code is an answer, not \"no response\".\n */\nexport function classifyPaymentError(err: PaymentErrorLike): PaymentErrorClass {\n const status = typeof err.status === 'number' ? err.status : 0\n const code = typeof err.code === 'string' ? err.code : ''\n if (code === 'store_not_ready') return { kind: 'store_closed', retryable: false }\n if (code === 'price_mismatch' || (status === 422 && err.field === 'expected_total')) return { kind: 'price_mismatch', retryable: false }\n if (status === 409 && (code === 'payment_in_progress' || err.field === 'payment_in_progress')) return { kind: 'in_progress', retryable: true }\n if (status === 409 && code === 'expired') return { kind: 'expired', retryable: false }\n if (status === 429 || code === 'too_many_attempts' || code === 'rate_limited') return { kind: 'rate_limited', retryable: true }\n if (status === 422 && code === 'invalid_state') {\n if (err.field === PAYMENT_CHOICE_REFUSED_FIELD) return { kind: 'other', retryable: false }\n return { kind: 'stale_checkout', retryable: false }\n }\n if (code === 'payment_provider_misconfigured') return { kind: 'merchant_config', retryable: false }\n if (code === 'payment_provider_rejected') return { kind: 'provider_declined', retryable: false }\n if (MERCHANT_CONFIG_CODE.test(code) || status === 401 || status === 403) return { kind: 'merchant_config', retryable: false }\n // OPS answered and said \"do not repeat\": definitive, not indeterminate (there is no lost answer to verify).\n if (status >= 500 && opsSaysNotRetryable(err)) return { kind: 'other', retryable: false }\n if (status === 0 || status >= 500 || code === 'network' || code === 'timeout' || code === 'unavailable') return { kind: 'transient', retryable: true }\n if (status === 400 || code === 'validation') return { kind: 'validation', retryable: false }\n return { kind: 'other', retryable: false }\n}\n","import type { StorefrontClient } from './client.js'\nimport { isStorefrontError } from './errors.js'\nimport type { TokenIntrospection } from './types.js'\n\n/** `sk_…a91f`: the prefix and the last four characters, never enough to use the token. */\nexport function maskToken(token: string | null | undefined): string {\n if (!token) return '(sin token)'\n const prefix = /^[a-z]{2}_/.exec(token)?.[0] ?? ''\n return token.length <= prefix.length + 8 ? `${prefix}…` : `${prefix}…${token.slice(-4)}`\n}\n\nexport type DiagnoseOptions = {\n /** Where the warning goes (default `console.warn`). Receives ONE line per problem. */\n log?: (message: string) => void\n /** Name of the connection, shown in the repair path. */\n connectionName?: string\n /** Give up after this long (default 3000 ms). */\n timeoutMs?: number\n}\n\n/** Where the operator repairs a connection in OPS (es-MX, as the screen names it). */\nexport function repairPath(connectionName?: string): string {\n return `OPS → Conexiones y API → ${connectionName ?? '<conexión>'} → Reparar permisos`\n}\n\n/**\n * Startup check of the store's credential: asks `token.introspect()` and, when scopes are missing, logs ONE clear\n * warning with the repair path (never the token, only `sk_…a91f`). It NEVER throws and is meant to be fired and\n * forgotten, so it cannot delay or break the boot:\n *\n * ```ts\n * void diagnose(storefront)\n * ```\n *\n * Resolves with the introspection, or `null` when it could not be obtained (older OPS, outage, bad token).\n */\nexport async function diagnose(client: StorefrontClient, options: DiagnoseOptions = {}): Promise<TokenIntrospection | null> {\n const log = options.log ?? ((m: string) => console.warn(m))\n const timeoutMs = options.timeoutMs ?? 3000\n const raw = client.config.token\n let mask: string\n try {\n mask = maskToken(typeof raw === 'function' ? raw() : raw)\n } catch {\n mask = maskToken(null)\n }\n try {\n const info = await client.token.introspect({ signal: AbortSignal.timeout(timeoutMs) })\n const missing = Array.isArray(info?.missing_scopes) ? info.missing_scopes : []\n if (missing.length > 0) {\n log(\n `[@asteby/storefront] La credencial ${mask} no tiene permisos que la tienda necesita: ${missing.join(', ')}. ` +\n `Repáralo en ${repairPath(options.connectionName)} (no hace falta cambiar la clave ni reiniciar).`,\n )\n }\n return info ?? null\n } catch (err) {\n if (isStorefrontError(err) && err.status === 401) {\n try {\n log(`[@asteby/storefront] OPS rechazó la credencial ${mask} (401): está revocada o vencida. Vuelve a conectar la tienda en OPS → Conexiones y API.`)\n } catch {\n /* a broken logger must not break boot */\n }\n }\n return null\n }\n}\n","/**\n * Availability presentation: the single source of the texts and states a\n * storefront shows for stock. Pure functions, no DOM: safe in loaders, SSR and\n * edge runtimes.\n *\n * The server decides the state (`Availability.status`, already filtered by the\n * shop's `show_stock`); this module only turns it into labels. Shops may\n * override texts by key (`messages`) but never the logic. Numbers shown here\n * (\"Quedan 3\") come from `availability.quantity`, which the server sends only\n * when the shop allows it and past its own threshold: there is no threshold in\n * this code.\n */\nimport type { Availability, AvailabilityStatus, CartLineProblem, InsufficientStockLine, Product, ProductVariant } from './types.js'\n\nexport type AvailabilityTone = 'success' | 'warning' | 'danger' | 'info'\n\nexport type AvailabilityLocale = 'es' | 'en'\n\n/** Text keys, overridable per shop. `{n}` and `{date}` are replaced. */\nexport type AvailabilityMessageKey =\n | 'status.in_stock'\n | 'status.low_stock'\n | 'status.low_stock_n'\n | 'status.out_of_stock'\n | 'status.backorder'\n | 'status.preorder'\n | 'sub.backorder_eta'\n | 'sub.preorder_date'\n | 'cta.add'\n | 'cta.out_of_stock'\n | 'cta.backorder'\n | 'cta.preorder'\n | 'sr.in_stock'\n | 'sr.low_stock'\n | 'sr.low_stock_n'\n | 'sr.out_of_stock'\n | 'sr.backorder'\n | 'sr.preorder'\n | 'option.sold_out'\n | 'option.backorder'\n | 'option.preorder'\n | 'max_per_order'\n | 'notify.title'\n | 'notify.email'\n | 'notify.phone'\n | 'notify.consent'\n | 'notify.submit'\n | 'notify.done'\n | 'notify.error'\n | 'problem.out_of_stock'\n | 'problem.insufficient_stock'\n | 'problem.insufficient_stock_n'\n | 'problem.adjust'\n | 'problem.remove'\n | 'conflict.title'\n | 'conflict.body'\n | 'conflict.dismiss'\n\nexport type AvailabilityMessages = Record<AvailabilityMessageKey, string>\n\nconst ES: AvailabilityMessages = {\n 'status.in_stock': 'Disponible',\n 'status.low_stock': 'Pocas piezas',\n 'status.low_stock_n': 'Quedan {n}',\n 'status.out_of_stock': 'Agotado',\n 'status.backorder': 'Bajo pedido',\n 'status.preorder': 'Preventa',\n 'sub.backorder_eta': 'Se envía a partir del {date}',\n 'sub.preorder_date': 'Sale a la venta el {date}',\n 'cta.add': 'Agregar al carrito',\n 'cta.out_of_stock': 'Agotado',\n 'cta.backorder': 'Pedir bajo pedido',\n 'cta.preorder': 'Apartar en preventa',\n 'sr.in_stock': 'Disponible',\n 'sr.low_stock': 'Quedan pocas piezas',\n 'sr.low_stock_n': 'Quedan solo {n} piezas',\n 'sr.out_of_stock': 'Producto agotado',\n 'sr.backorder': 'Disponible bajo pedido',\n 'sr.preorder': 'Disponible en preventa',\n 'option.sold_out': 'agotado',\n 'option.backorder': 'bajo pedido',\n 'option.preorder': 'preventa',\n max_per_order: 'Máximo {n} por pedido',\n 'notify.title': 'Avísame cuando vuelva',\n 'notify.email': 'Correo electrónico',\n 'notify.phone': 'WhatsApp o teléfono',\n 'notify.consent': 'Acepto recibir un aviso cuando vuelva a estar disponible',\n 'notify.submit': 'Avísame',\n 'notify.done': 'Listo. Te avisaremos cuando vuelva a estar disponible.',\n 'notify.error': 'No pudimos guardar tu aviso. Revisa tus datos e inténtalo de nuevo.',\n 'problem.out_of_stock': 'Ya no hay existencias',\n 'problem.insufficient_stock': 'No hay suficientes piezas para esta cantidad',\n 'problem.insufficient_stock_n': 'Solo puedes llevar {n}',\n 'problem.adjust': 'Ajustar a {n}',\n 'problem.remove': 'Quitar',\n 'conflict.title': 'Algunos productos cambiaron de existencias',\n 'conflict.body': 'Revisa las líneas marcadas. Tu carrito y tus datos se conservaron; ajusta o quita lo que ya no está disponible y continúa.',\n 'conflict.dismiss': 'Entendido',\n}\n\nconst EN: AvailabilityMessages = {\n 'status.in_stock': 'In stock',\n 'status.low_stock': 'Low stock',\n 'status.low_stock_n': 'Only {n} left',\n 'status.out_of_stock': 'Sold out',\n 'status.backorder': 'Made to order',\n 'status.preorder': 'Pre-order',\n 'sub.backorder_eta': 'Ships from {date}',\n 'sub.preorder_date': 'Available on {date}',\n 'cta.add': 'Add to cart',\n 'cta.out_of_stock': 'Sold out',\n 'cta.backorder': 'Order now, ships later',\n 'cta.preorder': 'Pre-order',\n 'sr.in_stock': 'In stock',\n 'sr.low_stock': 'Low stock',\n 'sr.low_stock_n': 'Only {n} left in stock',\n 'sr.out_of_stock': 'Sold out',\n 'sr.backorder': 'Available to order, ships later',\n 'sr.preorder': 'Available for pre-order',\n 'option.sold_out': 'sold out',\n 'option.backorder': 'made to order',\n 'option.preorder': 'pre-order',\n max_per_order: 'Maximum {n} per order',\n 'notify.title': 'Notify me when it is back',\n 'notify.email': 'Email',\n 'notify.phone': 'WhatsApp or phone',\n 'notify.consent': 'I agree to receive a notice when it is back in stock',\n 'notify.submit': 'Notify me',\n 'notify.done': 'Done. We will let you know when it is back in stock.',\n 'notify.error': 'We could not save your request. Check your details and try again.',\n 'problem.out_of_stock': 'No longer in stock',\n 'problem.insufficient_stock': 'Not enough stock for this quantity',\n 'problem.insufficient_stock_n': 'You can take up to {n}',\n 'problem.adjust': 'Adjust to {n}',\n 'problem.remove': 'Remove',\n 'conflict.title': 'Some items changed stock',\n 'conflict.body': 'Review the marked lines. Your cart and your details were kept; adjust or remove what is no longer available and continue.',\n 'conflict.dismiss': 'Got it',\n}\n\nconst CATALOG: Record<AvailabilityLocale, AvailabilityMessages> = { es: ES, en: EN }\n\n/** `es-MX` -> `es`, `en-US` -> `en`; anything else falls back to Spanish. */\nexport function availabilityLocale(locale: string | null | undefined): AvailabilityLocale {\n return (locale ?? '').toLowerCase().startsWith('en') ? 'en' : 'es'\n}\n\n/** Catalog for a locale with the shop's per-key overrides applied. */\nexport function availabilityMessages(locale: string | null | undefined, overrides?: Partial<AvailabilityMessages> | null): AvailabilityMessages {\n const base = CATALOG[availabilityLocale(locale)]\n if (!overrides) return base\n const out = { ...base }\n for (const [k, v] of Object.entries(overrides)) if (typeof v === 'string' && k in base) out[k as AvailabilityMessageKey] = v\n return out\n}\n\n/** Replaces `{name}` placeholders. */\nexport function formatAvailabilityMessage(template: string, values: Record<string, string | number> = {}): string {\n return template.replace(/\\{(\\w+)\\}/g, (m, k: string) => (k in values ? String(values[k]) : m))\n}\n\nfunction formatDate(value: string | null | undefined, locale: string | null | undefined): string | null {\n if (!value) return null\n const d = /^\\d{4}-\\d{2}-\\d{2}$/.test(value) ? new Date(`${value}T00:00:00Z`) : new Date(value)\n if (Number.isNaN(d.getTime())) return null\n try {\n // UTC keeps server and client renders identical (no hydration mismatch).\n return new Intl.DateTimeFormat(locale || 'es', { dateStyle: 'long', timeZone: 'UTC' }).format(d)\n } catch {\n return value.slice(0, 10)\n }\n}\n\nexport type ResolveAvailabilityOptions = {\n /**\n * Polyfill only: shop-level \"low stock\" threshold to derive `low_stock` from\n * `quantity_available` on servers older than contract 1.1. Without it the\n * polyfill never reports `low_stock`. Ignored when the server sends `availability`.\n */\n lowStockThreshold?: number | null\n}\n\ntype AvailabilitySource = Pick<Product | ProductVariant, 'available_for_sale'> & {\n availability?: Availability | null\n quantity_available?: number | null\n}\n\n/**\n * The `Availability` of a variant or product. Uses the server's `availability`\n * when present; otherwise derives `in_stock | low_stock | out_of_stock` from\n * `available_for_sale` / `quantity_available` so storefronts can migrate before\n * the backend does. A malformed `availability` falls back to the polyfill.\n */\nexport function resolveAvailability(source: AvailabilitySource, options: ResolveAvailabilityOptions = {}): Availability {\n const a = source.availability\n if (a && typeof a === 'object' && typeof a.status === 'string') return a\n const qty = typeof source.quantity_available === 'number' ? source.quantity_available : null\n const sellable = source.available_for_sale && (qty === null || qty > 0)\n const threshold = options.lowStockThreshold\n const low = sellable && qty !== null && typeof threshold === 'number' && threshold > 0 && qty <= threshold\n const status: AvailabilityStatus = !sellable ? 'out_of_stock' : low ? 'low_stock' : 'in_stock'\n return {\n status,\n quantity: sellable ? qty : null,\n max_per_order: sellable ? qty : null,\n restock_eta: null,\n preorder_release_at: null,\n // Old servers have no subscription route: never offer a form that cannot work.\n notify_available: false,\n }\n}\n\nexport type AvailabilityView = {\n status: AvailabilityStatus\n tone: AvailabilityTone\n /** Short badge text: \"Agotado\", \"Quedan 3\", \"Bajo pedido\"... Never empty. */\n label: string\n /** ETA / release date text, or `null`. */\n sublabel: string | null\n /** Primary button text. */\n ctaLabel: string\n /** The primary button may be pressed (backorder/preorder are purchasable). */\n ctaEnabled: boolean\n /** Offer the \"Notify me when it is back\" form. */\n showNotify: boolean\n /** Full sentence for screen readers. */\n srText: string\n /** Units to cap the quantity picker at, or `null`. */\n maxPerOrder: number | null\n /** Show a badge on listing cards (everything but plain `in_stock`: do not clutter). */\n showOnCard: boolean\n}\n\nexport type AvailabilityViewOptions = {\n messages?: Partial<AvailabilityMessages> | null\n}\n\nconst TONES: Record<AvailabilityStatus, AvailabilityTone> = {\n in_stock: 'success',\n low_stock: 'warning',\n out_of_stock: 'danger',\n backorder: 'info',\n preorder: 'info',\n}\n\n/**\n * Texts and flags for one availability. `availability` accepts anything with an\n * unknown `status` (a future server): it is treated as `out_of_stock`.\n */\nexport function availabilityView(availability: Availability, locale: string | null | undefined, options: AvailabilityViewOptions = {}): AvailabilityView {\n const m = availabilityMessages(locale, options.messages)\n const known = (['in_stock', 'low_stock', 'out_of_stock', 'backorder', 'preorder'] as const).includes(availability.status)\n const status: AvailabilityStatus = known ? availability.status : 'out_of_stock'\n const qty = typeof availability.quantity === 'number' && availability.quantity > 0 ? availability.quantity : null\n const f = formatAvailabilityMessage\n\n let label: string\n let sr: string\n let cta: string\n let sublabel: string | null = null\n let enabled = true\n switch (status) {\n case 'in_stock':\n label = m['status.in_stock']\n sr = m['sr.in_stock']\n cta = m['cta.add']\n break\n case 'low_stock':\n // Without a visible quantity the server still says \"low\": no number is invented.\n label = qty !== null ? f(m['status.low_stock_n'], { n: qty }) : m['status.low_stock']\n sr = qty !== null ? f(m['sr.low_stock_n'], { n: qty }) : m['sr.low_stock']\n cta = m['cta.add']\n break\n case 'backorder': {\n label = m['status.backorder']\n sr = m['sr.backorder']\n cta = m['cta.backorder']\n const date = formatDate(availability.restock_eta, locale)\n if (date) sublabel = f(m['sub.backorder_eta'], { date })\n break\n }\n case 'preorder': {\n label = m['status.preorder']\n sr = m['sr.preorder']\n cta = m['cta.preorder']\n const date = formatDate(availability.preorder_release_at ?? availability.restock_eta, locale)\n if (date) sublabel = f(m['sub.preorder_date'], { date })\n break\n }\n default:\n label = m['status.out_of_stock']\n sr = m['sr.out_of_stock']\n cta = m['cta.out_of_stock']\n enabled = false\n }\n return {\n status,\n tone: TONES[status],\n label,\n sublabel,\n ctaLabel: cta,\n ctaEnabled: enabled,\n showNotify: status === 'out_of_stock' && availability.notify_available === true,\n srText: sublabel ? `${sr}. ${sublabel}` : sr,\n maxPerOrder: typeof availability.max_per_order === 'number' && availability.max_per_order > 0 ? availability.max_per_order : null,\n showOnCard: status !== 'in_stock',\n }\n}\n\nexport type CartLineProblemView = {\n code: CartLineProblem['code']\n /** \"Ya no hay existencias\" / \"Solo puedes llevar 2\". */\n message: string\n /** Quantity to adjust the line to, or `null` (remove only). */\n adjustTo: number | null\n adjustLabel: string | null\n removeLabel: string\n}\n\n/** Texts and actions for a cart line problem. Offers \"Adjust to N\" only when `max_quantity` is a positive number different from the line quantity (a refused change leaves the cart at its old quantity). */\nexport function cartLineProblemView(\n problem: CartLineProblem | InsufficientStockLine,\n locale: string | null | undefined,\n options: AvailabilityViewOptions & { lineQuantity?: number } = {},\n): CartLineProblemView {\n const m = availabilityMessages(locale, options.messages)\n const code: CartLineProblem['code'] = 'code' in problem ? problem.code : problem.status === 'out_of_stock' ? 'out_of_stock' : 'insufficient_stock'\n const max = typeof problem.max_quantity === 'number' && problem.max_quantity >= 0 ? problem.max_quantity : null\n const canAdjust = max !== null && max > 0 && (options.lineQuantity === undefined || max !== options.lineQuantity)\n const message =\n code === 'out_of_stock' || max === 0\n ? m['problem.out_of_stock']\n : max !== null\n ? formatAvailabilityMessage(m['problem.insufficient_stock_n'], { n: max })\n : m['problem.insufficient_stock']\n return {\n code,\n message,\n adjustTo: canAdjust ? max : null,\n adjustLabel: canAdjust ? formatAvailabilityMessage(m['problem.adjust'], { n: max }) : null,\n removeLabel: m['problem.remove'],\n }\n}\n\nconst SCHEMA_AVAILABILITY: Record<AvailabilityStatus, string> = {\n in_stock: 'https://schema.org/InStock',\n low_stock: 'https://schema.org/LimitedAvailability',\n out_of_stock: 'https://schema.org/OutOfStock',\n backorder: 'https://schema.org/BackOrder',\n preorder: 'https://schema.org/PreOrder',\n}\n\n/** schema.org `ItemAvailability` URL for a status (unknown -> `OutOfStock`). */\nexport function schemaAvailability(status: AvailabilityStatus | string): string {\n return SCHEMA_AVAILABILITY[status as AvailabilityStatus] ?? SCHEMA_AVAILABILITY.out_of_stock\n}\n\n/** Best state among variants for a product summary (when the server sends none). */\nexport function productAvailability(product: Pick<Product, 'variants' | 'available_for_sale' | 'availability'>, options: ResolveAvailabilityOptions = {}): Availability {\n if (product.availability) return product.availability\n const all = product.variants.map((v) => resolveAvailability(v, options))\n const rank: AvailabilityStatus[] = ['in_stock', 'low_stock', 'backorder', 'preorder', 'out_of_stock']\n const best = all.slice().sort((a, b) => rank.indexOf(a.status) - rank.indexOf(b.status))[0]\n return best ?? resolveAvailability(product, options)\n}\n","/**\n * Embedded payment presentation: the single source of the texts and states a\n * storefront shows around an in-page payment. Pure functions, no DOM: safe in\n * loaders, SSR and edge runtimes.\n *\n * Rules this module encodes (DISENO-PAGO-INTEGRADO-BRICKS):\n * - The server decides the outcome and the amount. Nothing here computes or\n * compares money; `expected_total` is the server's own number echoed back.\n * - A rejection is explained with an actionable text built from the neutral\n * `decline_code`. A raw provider code is never shown.\n * - Vouchers and redirects only trust https URLs.\n */\nimport { availabilityLocale, formatAvailabilityMessage, type AvailabilityLocale } from './availability.js'\nimport { StorefrontError } from './errors.js'\nimport type { DeclineCode, Money, PaymentAction, PaymentAttemptResult, PaymentNextStep, PaymentVoucher } from './types.js'\n\nexport type PaymentLocale = AvailabilityLocale\n\nexport type PaymentMessageKey =\n | `decline.${DeclineCode}`\n | 'state.loading'\n | 'state.processing'\n | 'state.approved'\n | 'state.in_review'\n | 'state.voucher'\n | 'state.challenge'\n | 'state.expired'\n | 'state.cancelled'\n | 'state.redirect'\n | 'state.fallback'\n | 'error.network'\n | 'error.card_data'\n | 'error.price_mismatch'\n | 'error.payment_in_progress'\n | 'error.expired'\n | 'error.too_many_attempts'\n | 'error.generic'\n | 'action.retry'\n | 'action.try_again'\n | 'action.pay'\n | 'action.cancel'\n | 'voucher.title'\n | 'voucher.point'\n | 'voucher.reference'\n | 'voucher.amount'\n | 'voucher.expires'\n | 'voucher.clabe'\n | 'voucher.barcode'\n | 'voucher.open'\n | 'voucher.email'\n | 'form.label'\n | 'challenge.title'\n | 'challenge.escape'\n | 'challenge.escape_hint'\n | 'challenge.left'\n\nexport type PaymentMessages = Record<PaymentMessageKey, string>\n\nconst ES: PaymentMessages = {\n 'decline.insufficient_funds': 'Tu tarjeta no tiene saldo suficiente. Prueba con otra tarjeta o paga en efectivo.',\n 'decline.invalid_cvc': 'El código de seguridad no es correcto. Revísalo e intenta de nuevo.',\n 'decline.invalid_expiry': 'La fecha de vencimiento no es correcta.',\n 'decline.invalid_card_data': 'Revisa los datos de tu tarjeta.',\n 'decline.call_issuer': 'Tu banco necesita que autorices este pago. Llama al número al reverso de tu tarjeta y vuelve a intentarlo.',\n 'decline.card_disabled': 'Tu tarjeta no está activa. Actívala con tu banco o usa otra.',\n 'decline.duplicate': 'Ya hiciste un pago igual hace un momento. Revisa tu correo antes de volver a pagar.',\n 'decline.max_attempts': 'Llegaste al límite de intentos con esta tarjeta. Usa otra o paga en efectivo.',\n 'decline.authentication_failed': 'Tu banco no pudo verificar el pago. Intenta de nuevo o usa otra tarjeta.',\n 'decline.declined': 'Tu banco rechazó el pago. Usa otra tarjeta o paga en efectivo.',\n 'state.loading': 'Cargando pago seguro…',\n 'state.processing': 'Procesando pago…',\n 'state.approved': '¡Pago aprobado!',\n 'state.in_review': 'Tu pago está en revisión. Te avisamos por correo en máximo 2 días hábiles. No vuelvas a pagar.',\n 'state.voucher': 'Tu ficha de pago está lista. El pedido se confirma cuando pagues.',\n 'state.challenge': 'Tu banco necesita verificar el pago. Termina la verificación para continuar.',\n 'state.expired': 'La ficha venció. Vuelve a armar tu carrito para pagar.',\n 'state.cancelled': 'El pago se canceló. Puedes intentarlo de nuevo.',\n 'state.redirect': 'Te llevamos a la página de pago…',\n 'state.fallback': 'No pudimos cargar el formulario seguro de tarjeta. Puedes pagar con tarjeta en el sitio del proveedor y regresar aquí.',\n 'error.network': 'No pudimos conectar. Revisa tu conexión e intenta de nuevo; no se te cobrará dos veces.',\n 'error.card_data': 'Revisa los datos de tu tarjeta.',\n 'error.price_mismatch': 'El total cambió. Revisa el nuevo total y vuelve a pagar.',\n 'error.payment_in_progress': 'Ya hay un pago en proceso para este pedido. No vuelvas a pagar; revisa tu correo.',\n 'error.expired': 'Tu apartado venció. Vuelve a armar tu carrito.',\n 'error.too_many_attempts': 'Por seguridad no podemos intentar con más tarjetas. Paga en efectivo o escríbenos.',\n 'error.generic': 'No pudimos procesar tu pago. Intenta de nuevo.',\n 'action.retry': 'Reintentar',\n 'action.try_again': 'Intentar de nuevo',\n 'action.pay': 'Pagar',\n 'action.cancel': 'Cancelar',\n 'voucher.title': 'Ficha de pago',\n 'voucher.point': 'Punto de pago',\n 'voucher.reference': 'Referencia',\n 'voucher.amount': 'Monto exacto',\n 'voucher.expires': 'Vence el {date}',\n 'voucher.clabe': 'CLABE',\n 'voucher.barcode': 'Código de barras',\n 'voucher.open': 'Ver o imprimir ficha',\n 'voucher.email': 'También te la enviamos a tu correo.',\n 'form.label': 'Datos de tu tarjeta',\n 'challenge.title': 'Verificación de tu banco',\n 'challenge.escape': 'Cancelar y volver al pago',\n 'challenge.escape_hint': '¿Tarda demasiado? Puedes cerrar la verificación. Si ya la aprobaste en tu banco, el pago aún puede completarse: te confirmamos aquí antes de dejarte pagar de nuevo.',\n 'challenge.left': 'Cerraste la verificación. Estamos confirmando con tu banco si el pago se completó; no vuelvas a pagar todavía.',\n}\n\nconst EN: PaymentMessages = {\n 'decline.insufficient_funds': 'Your card has insufficient funds. Try another card or pay in cash.',\n 'decline.invalid_cvc': 'The security code is not correct. Check it and try again.',\n 'decline.invalid_expiry': 'The expiry date is not correct.',\n 'decline.invalid_card_data': 'Check your card details.',\n 'decline.call_issuer': 'Your bank needs you to authorize this payment. Call the number on the back of your card and try again.',\n 'decline.card_disabled': 'Your card is not active. Activate it with your bank or use another one.',\n 'decline.duplicate': 'You already made the same payment a moment ago. Check your email before paying again.',\n 'decline.max_attempts': 'You reached the attempt limit for this card. Use another card or pay in cash.',\n 'decline.authentication_failed': 'Your bank could not verify the payment. Try again or use another card.',\n 'decline.declined': 'Your bank declined the payment. Use another card or pay in cash.',\n 'state.loading': 'Loading secure payment…',\n 'state.processing': 'Processing payment…',\n 'state.approved': 'Payment approved!',\n 'state.in_review': 'Your payment is under review. We will email you within 2 business days. Do not pay again.',\n 'state.voucher': 'Your payment voucher is ready. The order is confirmed once you pay.',\n 'state.challenge': 'Your bank needs to verify the payment. Finish the verification to continue.',\n 'state.expired': 'The voucher expired. Rebuild your cart to pay.',\n 'state.cancelled': 'The payment was cancelled. You can try again.',\n 'state.redirect': 'Taking you to the payment page…',\n 'state.fallback': 'We could not load the secure card form. You can pay by card on the provider site and come back here.',\n 'error.network': 'We could not connect. Check your connection and try again; you will not be charged twice.',\n 'error.card_data': 'Check your card details.',\n 'error.price_mismatch': 'The total changed. Review the new total and pay again.',\n 'error.payment_in_progress': 'A payment is already in progress for this order. Do not pay again; check your email.',\n 'error.expired': 'Your reservation expired. Rebuild your cart.',\n 'error.too_many_attempts': 'For security we cannot try more cards. Pay in cash or contact us.',\n 'error.generic': 'We could not process your payment. Please try again.',\n 'action.retry': 'Retry',\n 'action.try_again': 'Try again',\n 'action.pay': 'Pay',\n 'action.cancel': 'Cancel',\n 'voucher.title': 'Payment voucher',\n 'voucher.point': 'Payment point',\n 'voucher.reference': 'Reference',\n 'voucher.amount': 'Exact amount',\n 'voucher.expires': 'Expires on {date}',\n 'voucher.clabe': 'CLABE',\n 'voucher.barcode': 'Barcode',\n 'voucher.open': 'View or print voucher',\n 'voucher.email': 'We also emailed it to you.',\n 'form.label': 'Your card details',\n 'challenge.title': 'Your bank verification',\n 'challenge.escape': 'Cancel and go back to payment',\n 'challenge.escape_hint': 'Taking too long? You can close the verification. If you already approved it with your bank the payment may still go through: we confirm here before letting you pay again.',\n 'challenge.left': 'You closed the verification. We are checking with your bank whether the payment went through; do not pay again yet.',\n}\n\nconst CATALOG: Record<PaymentLocale, PaymentMessages> = { es: ES, en: EN }\n\n/** Catalog for a locale (`es-MX` -> es, `en-US` -> en) with the shop's per-key overrides applied. */\nexport function paymentMessages(locale: string | null | undefined, overrides?: Partial<PaymentMessages> | null): PaymentMessages {\n const base = CATALOG[availabilityLocale(locale)]\n if (!overrides) return base\n const out = { ...base }\n for (const [k, v] of Object.entries(overrides)) if (typeof v === 'string' && k in base) out[k as PaymentMessageKey] = v\n return out\n}\n\nconst DECLINE_CODES: ReadonlySet<string> = new Set<DeclineCode>([\n 'insufficient_funds',\n 'invalid_cvc',\n 'invalid_expiry',\n 'invalid_card_data',\n 'call_issuer',\n 'card_disabled',\n 'duplicate',\n 'max_attempts',\n 'authentication_failed',\n 'declined',\n])\n\n/** i18n key of a decline code; unknown or missing codes map to `declined` (never a raw provider code). */\nexport function declineMessageKey(code: string | null | undefined): `decline.${DeclineCode}` {\n return `decline.${code && DECLINE_CODES.has(code) ? (code as DeclineCode) : 'declined'}`\n}\n\n/** Actionable text for a decline code. */\nexport function declineMessage(code: string | null | undefined, locale?: string | null, overrides?: Partial<PaymentMessages> | null): string {\n return paymentMessages(locale, overrides)[declineMessageKey(code)]\n}\n\n/** The value only if it is an absolute `https:` URL without credentials; `null` otherwise. */\nexport function safeHttpsUrl(value: unknown): string | null {\n if (typeof value !== 'string' || value.length > 2048) return null\n try {\n const u = new URL(value)\n if (u.protocol !== 'https:' || u.username || u.password) return null\n return u.toString()\n } catch {\n return null\n }\n}\n\n/** What the UI should do with an attempt result. */\nexport type PaymentOutcomeKind =\n | 'approved' // paid: go to the thanks page\n | 'in_review' // pending without action: do not charge again\n | 'voucher' // cash/SPEI voucher with reference and expiry\n | 'challenge' // 3DS inside the page\n | 'redirect' // leave to the provider\n | 'rejected' // failed: show the reason and let the buyer retry\n | 'expired'\n | 'cancelled'\n\n/** A voucher ready to render: https-only link and the amount as `Money` (or `null` when the server sent none). */\nexport type PaymentOutcomeVoucher = Omit<PaymentVoucher, 'amount' | 'voucher_url' | 'currency'> & {\n voucher_url: string | null\n amount: Money | null\n}\n\nconst NEXT_STEP: Record<DeclineCode, PaymentNextStep> = {\n insufficient_funds: 'use_other_card',\n invalid_cvc: 'fix_card_data',\n invalid_expiry: 'fix_card_data',\n invalid_card_data: 'fix_card_data',\n call_issuer: 'contact_issuer',\n card_disabled: 'use_other_card',\n duplicate: 'check_email',\n max_attempts: 'use_other_card',\n authentication_failed: 'retry',\n declined: 'use_other_card',\n}\n\nfunction voucherMoney(v: PaymentVoucher): Money | null {\n const a = v.amount\n if (a && typeof a === 'object' && typeof a.amount === 'string') return a\n const text = typeof a === 'number' ? String(a) : typeof a === 'string' ? a : ''\n if (!text || !/^\\d+(\\.\\d+)?$/.test(text) || !v.currency) return null\n return { amount: text.includes('.') ? text : `${text}.00`, currency_code: v.currency }\n}\n\nexport type PaymentOutcome = {\n kind: PaymentOutcomeKind\n /** Text for the buyer (no codes). */\n message: string\n decline_code: DeclineCode | null\n /** `true` when the buyer can try again with the checkout still open. */\n retryable: boolean\n /** https-only. */\n redirect_url: string | null\n challenge: { url: string | null; creq: string | null } | null\n voucher: PaymentOutcomeVoucher | null\n attempts_left: number | null\n /** What to do next (server value, or derived from the decline code): fix the card, use another, rebuild the cart... */\n next_step: PaymentNextStep | null\n}\n\n/**\n * Classifies an attempt result. Unknown statuses are treated as `in_review`\n * (never as approved, never as a reason to charge again).\n */\nexport function paymentOutcome(result: PaymentAttemptResult, locale?: string | null, overrides?: Partial<PaymentMessages> | null): PaymentOutcome {\n const m = paymentMessages(locale, overrides)\n const p = result.payment\n const action: PaymentAction | null = p.action ?? null\n const base = {\n decline_code: null as DeclineCode | null,\n retryable: false,\n redirect_url: null as string | null,\n challenge: null as PaymentOutcome['challenge'],\n voucher: null as PaymentOutcome['voucher'],\n attempts_left: typeof result.attempts_left === 'number' ? result.attempts_left : null,\n next_step: (p.next_step ?? null) as PaymentNextStep | null,\n }\n const out = (kind: PaymentOutcomeKind, message: string, extra: Partial<PaymentOutcome> = {}): PaymentOutcome => ({ ...base, kind, message, ...extra })\n\n if (p.status === 'paid') return out('approved', m['state.approved'])\n if (p.status === 'failed') {\n const code = p.decline_code ?? 'declined'\n const known: DeclineCode = DECLINE_CODES.has(code) ? code : 'declined'\n return out('rejected', m[declineMessageKey(code)], {\n decline_code: known,\n next_step: p.next_step ?? NEXT_STEP[known],\n retryable: p.retryable !== false && base.attempts_left !== 0,\n })\n }\n if (p.status === 'expired') return out('expired', m['state.expired'], { next_step: 'rebuild_cart' })\n if (p.status === 'cancelled') return out('cancelled', m['state.cancelled'], { retryable: true, next_step: 'rebuild_cart' })\n\n if (action?.type === 'redirect') {\n const url = safeHttpsUrl(action.redirect_url)\n if (url) return out('redirect', m['state.redirect'], { redirect_url: url })\n }\n if (p.status === 'requires_action' || p.status === 'pending') {\n if (action?.type === 'voucher' && action.voucher) {\n const { amount: _a, currency: _c, voucher_url, ...rest } = action.voucher\n return out('voucher', m['state.voucher'], {\n next_step: 'pay_cash',\n voucher: { ...rest, voucher_url: safeHttpsUrl(voucher_url), amount: voucherMoney(action.voucher) },\n })\n }\n if (action?.type === 'challenge' && action.challenge) {\n return out('challenge', m['state.challenge'], {\n challenge: { url: safeHttpsUrl(action.challenge.url), creq: typeof action.challenge.creq === 'string' ? action.challenge.creq : null },\n })\n }\n }\n return out('in_review', m['state.in_review'])\n}\n\n/** Failures of `POST /payment` the form maps to a specific text and next step. */\nexport type PaymentErrorKind =\n | 'network' // no answer: retry with the SAME attempt (idempotent)\n | 'price_mismatch' // total changed: show it, remount, pay again with a NEW attempt\n | 'payment_in_progress' // 409 payment_in_progress: another attempt is paid/pending: do not retry\n | 'expired' // 409: reservation expired\n | 'too_many_attempts' // 429\n | 'generic'\n\nexport type PaymentErrorView = { kind: PaymentErrorKind; message: string; retrySameAttempt: boolean; canRetry: boolean }\n\n/**\n * Maps a transport error (a `StorefrontError` or anything with `status`/`code`)\n * to a view. Network failures and 502/503/504 are safe to retry with the same\n * idempotency key; 409/422/429 are answers, not outages.\n */\nexport function paymentErrorView(err: unknown, locale?: string | null, overrides?: Partial<PaymentMessages> | null): PaymentErrorView {\n const m = paymentMessages(locale, overrides)\n const e = (err ?? {}) as Partial<StorefrontError> & { status?: number; code?: string }\n const status = typeof e.status === 'number' ? e.status : 0\n const code = typeof e.code === 'string' ? e.code : ''\n if (code === 'price_mismatch') {\n return { kind: 'price_mismatch', message: m['error.price_mismatch'], retrySameAttempt: false, canRetry: true }\n }\n if (status === 409 && code === 'expired') return { kind: 'expired', message: m['error.expired'], retrySameAttempt: false, canRetry: false }\n if (status === 409 && code === 'payment_in_progress') {\n return { kind: 'payment_in_progress', message: m['error.payment_in_progress'], retrySameAttempt: false, canRetry: false }\n }\n // 409 conflict: that Idempotency-Key was already used with a DIFFERENT payment (e.g. a new card after a reload).\n // Not an outage and not \"in progress\": start a new attempt.\n if (status === 409) return { kind: 'generic', message: m['error.generic'], retrySameAttempt: false, canRetry: true }\n if (status === 429 || code === 'too_many_attempts') {\n return { kind: 'too_many_attempts', message: m['error.too_many_attempts'], retrySameAttempt: false, canRetry: false }\n }\n // What OPS declared wins over the status: `retryable:false` is an answer (generic), any other 5xx (also a 500 with no readable body) is an outage whose charge may have happened: same key.\n const declared = (e as { retryable?: unknown }).retryable\n if (status >= 500 && declared === false) return { kind: 'generic', message: m['error.generic'], retrySameAttempt: false, canRetry: true }\n if (status === 0 || status === 502 || status === 503 || status === 504 || code === 'network' || code === 'timeout' || status >= 500) {\n return { kind: 'network', message: m['error.network'], retrySameAttempt: true, canRetry: true }\n }\n return { kind: 'generic', message: m['error.generic'], retrySameAttempt: false, canRetry: true }\n}\n\n/** `Vence el 5 de noviembre de 2026, 18:00` style text for a voucher deadline; `null` when absent or invalid. */\nexport function formatVoucherExpiry(expiresAt: string | null | undefined, locale?: string | null, overrides?: Partial<PaymentMessages> | null): string | null {\n if (!expiresAt) return null\n const d = new Date(expiresAt)\n if (Number.isNaN(d.getTime())) return null\n let date: string\n try {\n date = new Intl.DateTimeFormat(locale ?? undefined, { dateStyle: 'long', timeStyle: 'short' }).format(d)\n } catch {\n date = d.toISOString()\n }\n return formatAvailabilityMessage(paymentMessages(locale, overrides)['voucher.expires'], { date })\n}\n\n/** Builds an idempotency key for a payment attempt: the same attempt always yields the same key. */\nexport function paymentIdempotencyKey(checkoutId: string, attempt: string): string {\n return `pay-${checkoutId}-${attempt}`\n}\n","/**\n * Promotion presentation: turns `Cart.promotions` (computed by OPS) into the\n * labels and bar states a storefront shows. Pure functions, no DOM.\n *\n * The shop never computes a discount here: `remaining`, `percent`, `reached`\n * and `percent_of_max` are the server's. The only arithmetic is clamping a\n * server percentage into 0-100 for `aria-valuenow`.\n */\nimport { availabilityLocale, formatAvailabilityMessage, type AvailabilityLocale } from './availability.js'\nimport { formatMoney } from './money.js'\nimport type { CartPromotions, Money, PromotionReward } from './types.js'\n\nexport type PromotionLocale = AvailabilityLocale\n\nexport type PromotionMessageKey =\n | 'discount.next'\n | 'discount.next_upgrade'\n | 'discount.applied'\n | 'discount.max'\n | 'discount.suppressed'\n | 'discount.unlocks'\n | 'discount.remaining'\n | 'shipping.progress'\n | 'shipping.reached'\n | 'shipping.always'\n | 'reward.free_shipping'\n | 'bar.discount'\n | 'bar.shipping'\n | 'popup.close'\n | 'popup.valid_until'\n | 'popup.limited_time'\n | 'popup.discount_tier'\n | 'popup.free_shipping_min'\n | 'popup.free_shipping_always'\n | 'upsell.title'\n | 'upsell.subtitle'\n | 'upsell.next_level'\n | 'upsell.you_miss'\n | 'upsell.unlocks_reward'\n | 'upsell.total_saved'\n | 'upsell.current_benefit'\n | 'upsell.status'\n | 'upsell.status_pending'\n | 'upsell.status_active'\n | 'upsell.next_reward'\n | 'upsell.suggestions'\n | 'upsell.add'\n | 'upsell.adding'\n | 'upsell.flavor'\n | 'upsell.unlocks_badge'\n | 'upsell.unlocked'\n | 'upsell.best'\n | 'upsell.skip'\n | 'upsell.continue'\n | 'upsell.footer'\n | 'upsell.sold_out'\n | 'upsell.error'\n | 'note.label'\n | 'note.placeholder'\n | 'note.save'\n | 'note.saving'\n | 'note.saved'\n | 'note.error'\n | 'note.counter'\n\nexport type PromotionMessages = Record<PromotionMessageKey, string>\n\nconst ES: PromotionMessages = {\n 'discount.next': 'Añade {remaining} para activar tu descuento automático',\n 'discount.next_upgrade': 'Añade {remaining} para subir a {reward}',\n 'discount.applied': '¡Tienes {reward} de descuento!',\n 'discount.max': '¡Tienes {reward} de descuento, el máximo!',\n 'discount.suppressed': 'Tu código de descuento ya te da un mejor precio.',\n 'discount.unlocks': 'Desbloqueas {reward} de descuento',\n 'discount.remaining': 'Te faltan {remaining}',\n 'shipping.progress': 'Añade {remaining} para envío gratis',\n 'shipping.reached': '¡Felicidades! Tienes envío gratis',\n 'shipping.always': 'Envío gratis en todo tu pedido',\n 'reward.free_shipping': 'Envío gratis',\n 'bar.discount': 'Progreso del descuento automático',\n 'bar.shipping': 'Progreso del envío gratis',\n 'popup.close': 'Cerrar',\n 'popup.valid_until': 'Válido hasta el {date}',\n 'popup.limited_time': 'Por tiempo limitado',\n 'popup.discount_tier': '{reward} comprando {threshold}',\n 'popup.free_shipping_min': 'Envío gratis desde {threshold}',\n 'popup.free_shipping_always': 'Envíos gratis sin mínimo de compra',\n 'upsell.title': 'Completa tu compra y desbloquea más',\n 'upsell.subtitle': 'Descuento automático',\n 'upsell.next_level': 'Siguiente nivel',\n 'upsell.you_miss': 'Te faltan {remaining}',\n 'upsell.unlocks_reward': 'Desbloqueas {reward} de descuento',\n 'upsell.total_saved': 'Total ahorrado',\n 'upsell.current_benefit': 'Beneficio actual',\n 'upsell.status': 'Estado',\n 'upsell.status_pending': 'Pendiente',\n 'upsell.status_active': 'Activo',\n 'upsell.next_reward': 'Siguiente recompensa {reward} · {threshold}',\n 'upsell.suggestions': 'Suma y desbloquea · Productos que pueden interesarte',\n 'upsell.add': 'Agregar y avanzar +',\n 'upsell.adding': 'Agregando…',\n 'upsell.flavor': 'Sabor',\n 'upsell.unlocks_badge': 'Desbloquea tu {reward}',\n 'upsell.unlocked': '¡Desbloqueaste {reward}!',\n 'upsell.best': 'Tienes el mejor descuento: {reward}',\n 'upsell.skip': 'Continuar sin agregar',\n 'upsell.continue': 'Continuar al pago',\n 'upsell.footer': 'Tu mejor descuento se aplica automáticamente',\n 'upsell.sold_out': 'Se agotó este sabor, elige otro.',\n 'upsell.error': 'No pudimos agregarlo. Intenta de nuevo.',\n 'note.label': 'Añadir nota',\n 'note.placeholder': 'Instrucciones para tu pedido',\n 'note.save': 'Guardar nota',\n 'note.saving': 'Guardando…',\n 'note.saved': 'Guardada',\n 'note.error': 'No se pudo guardar la nota. Intenta de nuevo.',\n 'note.counter': '{n} de {max} caracteres',\n}\n\nconst EN: PromotionMessages = {\n 'discount.next': 'Add {remaining} to unlock your automatic discount',\n 'discount.next_upgrade': 'Add {remaining} to move up to {reward}',\n 'discount.applied': 'You have {reward} off!',\n 'discount.max': 'You have {reward} off, the maximum!',\n 'discount.suppressed': 'Your discount code already gives you a better price.',\n 'discount.unlocks': 'Unlock {reward} off',\n 'discount.remaining': '{remaining} to go',\n 'shipping.progress': 'Add {remaining} for free shipping',\n 'shipping.reached': 'Congratulations! You get free shipping',\n 'shipping.always': 'Free shipping on your whole order',\n 'reward.free_shipping': 'Free shipping',\n 'bar.discount': 'Automatic discount progress',\n 'bar.shipping': 'Free shipping progress',\n 'popup.close': 'Close',\n 'popup.valid_until': 'Valid until {date}',\n 'popup.limited_time': 'Limited time',\n 'popup.discount_tier': '{reward} when you spend {threshold}',\n 'popup.free_shipping_min': 'Free shipping from {threshold}',\n 'popup.free_shipping_always': 'Free shipping, no minimum purchase',\n 'upsell.title': 'Complete your purchase and unlock more',\n 'upsell.subtitle': 'Automatic discount',\n 'upsell.next_level': 'Next level',\n 'upsell.you_miss': '{remaining} to go',\n 'upsell.unlocks_reward': 'Unlock {reward} off',\n 'upsell.total_saved': 'Total saved',\n 'upsell.current_benefit': 'Current benefit',\n 'upsell.status': 'Status',\n 'upsell.status_pending': 'Pending',\n 'upsell.status_active': 'Active',\n 'upsell.next_reward': 'Next reward {reward} · {threshold}',\n 'upsell.suggestions': 'Add and unlock · Products you may like',\n 'upsell.add': 'Add and move up +',\n 'upsell.adding': 'Adding…',\n 'upsell.flavor': 'Flavor',\n 'upsell.unlocks_badge': 'Unlocks your {reward}',\n 'upsell.unlocked': 'You unlocked {reward}!',\n 'upsell.best': 'You have the best discount: {reward}',\n 'upsell.skip': 'Continue without adding',\n 'upsell.continue': 'Continue to payment',\n 'upsell.footer': 'Your best discount is applied automatically',\n 'upsell.sold_out': 'This flavor sold out, pick another one.',\n 'upsell.error': 'We could not add it. Please try again.',\n 'note.label': 'Add a note',\n 'note.placeholder': 'Instructions for your order',\n 'note.save': 'Save note',\n 'note.saving': 'Saving…',\n 'note.saved': 'Saved',\n 'note.error': 'The note could not be saved. Please try again.',\n 'note.counter': '{n} of {max} characters',\n}\n\nconst CATALOG: Record<PromotionLocale, PromotionMessages> = { es: ES, en: EN }\n\n/** Catalog for a locale with the shop's per-key overrides applied. */\nexport function promotionMessages(locale: string | null | undefined, overrides?: Partial<PromotionMessages> | null): PromotionMessages {\n const base = CATALOG[availabilityLocale(locale)]\n if (!overrides) return base\n const out = { ...base }\n for (const [k, v] of Object.entries(overrides)) if (typeof v === 'string' && k in base) out[k as PromotionMessageKey] = v\n return out\n}\n\n/** Order-note limit enforced by the server (`validateNote`). */\nexport const NOTE_MAX_LENGTH = 1000\n\n/** Trims and caps a note; empty becomes `null` (the server clears the note). */\nexport function normalizeNote(note: string | null | undefined): string | null {\n const t = (note ?? '').trim()\n return t ? t.slice(0, NOTE_MAX_LENGTH) : null\n}\n\n/** `5 %` / `7.5 %` (es) or `5%` (en) / `$250` / `Envío gratis`. The values are the server's. */\nexport function rewardLabel(reward: PromotionReward, locale?: string | null, overrides?: Partial<PromotionMessages> | null): string {\n const m = promotionMessages(locale, overrides)\n if (reward.kind === 'free_shipping') return m['reward.free_shipping']\n if (reward.kind === 'fixed') return formatMoney(reward.amount, locale ?? undefined, { withoutTrailingZeros: true })\n const n = Number.parseFloat(reward.percent)\n let num = reward.percent\n try {\n if (Number.isFinite(n)) num = new Intl.NumberFormat(locale ?? undefined, { maximumFractionDigits: 4 }).format(n)\n } catch {\n /* keep the raw text */\n }\n return availabilityLocale(locale) === 'en' ? `${num}%` : `${num} %`\n}\n\n/** Display clamp for a server percentage (`aria-valuenow`). Not a calculation. */\nexport function clampPercent(value: unknown): number {\n const n = typeof value === 'number' ? value : Number.parseFloat(String(value))\n if (!Number.isFinite(n)) return 0\n return Math.min(100, Math.max(0, Math.round(n)))\n}\n\nexport type DiscountBarState = 'next' | 'upgrade' | 'max' | 'suppressed'\n\nexport type DiscountBarView = {\n state: DiscountBarState\n /** Server progress 0-100. */\n percent: number\n text: string\n /** `aria-valuetext`. */\n valueText: string\n remaining: Money | null\n /** Reward of the next tier (or the applied one at max). */\n rewardText: string | null\n appliedText: string | null\n nextText: string | null\n tiers: { id: string; label: string; threshold: string; reached: boolean; position: number }[]\n}\n\nexport type ShippingBarState = 'progress' | 'reached' | 'always'\n\nexport type ShippingBarView = {\n state: ShippingBarState\n percent: number\n text: string\n valueText: string\n remaining: Money | null\n /** `false` for `always`: there is nothing to fill. */\n showBar: boolean\n}\n\nexport type PromoProgressView = { discount: DiscountBarView | null; shipping: ShippingBarView | null }\n\nconst fmt = (money: Money, locale?: string | null) => formatMoney(money, locale ?? undefined, { withoutTrailingZeros: true })\n\n/**\n * Bars of the cart and the pre-payment modal. Both read the same `Cart.promotions`,\n * so they can never disagree. `null`/absent promotions give `{ discount: null, shipping: null }`.\n */\nexport function promoProgressView(\n promotions: CartPromotions | null | undefined,\n locale?: string | null,\n overrides?: Partial<PromotionMessages> | null,\n): PromoProgressView {\n if (!promotions) return { discount: null, shipping: null }\n const m = promotionMessages(locale, overrides)\n const f = (tpl: string, vars: Record<string, string>) => formatAvailabilityMessage(tpl, vars)\n\n let discount: DiscountBarView | null = null\n const hasTiers = promotions.tiers.length > 0 || promotions.next_tier !== null || promotions.applied !== null\n if (hasTiers) {\n const next = promotions.next_tier\n const applied = promotions.applied\n const appliedReward = applied ? rewardLabel(applied.reward, locale, overrides) : null\n let state: DiscountBarState\n let text: string\n if (promotions.suppressed?.reason === 'code_better' && !applied) {\n state = 'suppressed'\n text = m['discount.suppressed']\n } else if (!next) {\n state = 'max'\n text = appliedReward ? f(m['discount.max'], { reward: appliedReward }) : m['discount.suppressed']\n } else if (applied) {\n state = 'upgrade'\n text = f(m['discount.next_upgrade'], { remaining: fmt(next.remaining, locale), reward: rewardLabel(next.reward, locale, overrides) })\n } else {\n state = 'next'\n text = f(m['discount.next'], { remaining: fmt(next.remaining, locale) })\n }\n discount = {\n state,\n percent: clampPercent(promotions.percent_of_max),\n text,\n valueText: text,\n remaining: next?.remaining ?? null,\n rewardText: next ? rewardLabel(next.reward, locale, overrides) : appliedReward,\n appliedText: appliedReward ? f(m['discount.applied'], { reward: appliedReward }) : null,\n nextText: next ? f(m['discount.unlocks'], { reward: rewardLabel(next.reward, locale, overrides) }) : null,\n tiers: promotions.tiers.map((t) => ({\n id: t.id,\n label: rewardLabel(t.reward, locale, overrides),\n threshold: fmt(t.threshold, locale),\n reached: t.reached,\n position: clampPercent(t.percent_of_max),\n })),\n }\n }\n\n let shipping: ShippingBarView | null = null\n const fs = promotions.free_shipping\n if (fs) {\n const noMinimum = Number.parseFloat(fs.threshold.amount) === 0\n if (noMinimum) {\n shipping = { state: 'always', percent: 100, text: m['shipping.always'], valueText: m['shipping.always'], remaining: null, showBar: false }\n } else if (fs.reached) {\n shipping = { state: 'reached', percent: 100, text: m['shipping.reached'], valueText: m['shipping.reached'], remaining: null, showBar: true }\n } else {\n const text = f(m['shipping.progress'], { remaining: fmt(fs.remaining, locale) })\n shipping = { state: 'progress', percent: clampPercent(fs.percent), text, valueText: text, remaining: fs.remaining, showBar: true }\n }\n }\n return { discount, shipping }\n}\n","/**\n * Detección de mercado por visita (país + idioma), pura y sin DOM: sirve en el servidor de cualquier tienda.\n *\n * Reglas (mejores prácticas de i18n para comercio):\n * - El mercado canónico lo fija el DOMINIO (OPS liga cada dominio verificado a un mercado: org_domains.market_code).\n * Esto no lo decide la geolocalización: así cada URL tiene un solo idioma/moneda (SEO, hreflang, caché de CDN).\n * - La geolocalización solo SUGIERE (banner \"¿Ver la tienda de Estados Unidos?\"); nunca redirige sola, nunca a rastreadores\n * y respeta la elección guardada del comprador.\n * - Precios, impuestos y envío NO dependen de la IP: dependen del mercado del dominio y de la dirección de entrega.\n * - El país sale de las cabeceras que pone el CDN/proxy (no se puede confiar en ellas si el servidor está expuesto\n * directo a internet: solo se leen con `trustProxy`).\n */\n\nexport type MarketInfo = {\n /** Código del mercado en OPS (\"mx\", \"us\"). */\n code: string\n /** ISO 3166-1 alfa-2 a los que vende. */\n countries: string[]\n /** BCP 47 por defecto (\"es-MX\", \"en-US\"). */\n locale: string\n /** ISO 4217 (\"MXN\", \"USD\"). */\n currency: string\n /** Dominio público del mercado, si es distinto del actual (\"godsnutrition.com\"). */\n host?: string\n}\n\n/** Cabeceras de país de los CDN/proxies más comunes, en orden de preferencia. */\nexport const COUNTRY_HEADERS = ['cf-ipcountry', 'cloudfront-viewer-country', 'x-vercel-ip-country', 'x-appengine-country', 'x-country-code'] as const\n\nconst BOT = /bot|crawl|spider|slurp|bing|facebookexternalhit|embedly|preview|lighthouse|headless|curl|wget/i\n\n/** País del visitante según el CDN. `null` si no viene, es desconocido (XX), Tor (T1) o no es ISO alfa-2. */\nexport function visitorCountry(headers: Headers, { trustProxy = true }: { trustProxy?: boolean } = {}): string | null {\n if (!trustProxy) return null\n for (const name of COUNTRY_HEADERS) {\n const value = headers.get(name)?.trim().toUpperCase()\n if (value && /^[A-Z]{2}$/.test(value) && value !== 'XX' && value !== 'T1') return value\n }\n return null\n}\n\n/** Idiomas de Accept-Language ordenados por q (mayor primero), en minúsculas. */\nexport function preferredLanguages(acceptLanguage: string | null | undefined): string[] {\n if (!acceptLanguage) return []\n return acceptLanguage\n .split(',')\n .map((part, index) => {\n const [tag = '', ...params] = part.trim().split(';')\n const q = Number(params.find((p) => p.trim().startsWith('q='))?.split('=')[1] ?? 1)\n return { tag: tag.trim().toLowerCase(), q: Number.isFinite(q) ? q : 0, index }\n })\n .filter((l) => l.tag && l.tag !== '*' && l.q > 0)\n .sort((a, b) => b.q - a.q || a.index - b.index)\n .map((l) => l.tag)\n}\n\n/** Mejor idioma entre los que ofrece la tienda: coincidencia exacta, luego por idioma base; si no, el de `fallback`. */\nexport function negotiateLocale(acceptLanguage: string | null | undefined, available: string[], fallback: string): string {\n const lowered = new Map(available.map((l) => [l.toLowerCase(), l]))\n for (const wanted of preferredLanguages(acceptLanguage)) {\n const exact = lowered.get(wanted)\n if (exact) return exact\n const base = wanted.split('-')[0]\n const sameBase = available.find((l) => l.toLowerCase().split('-')[0] === base)\n if (sameBase) return sameBase\n }\n return fallback\n}\n\nexport type MarketSuggestion = {\n market: MarketInfo\n /** Qué disparó la sugerencia. El país manda; el idioma solo si el CDN no dio país. */\n reason: 'country' | 'language'\n}\n\n/**\n * ¿Conviene sugerir otro mercado a esta visita? `null` si no (ya está en el correcto, rastreador, ya eligió, o no hay otro).\n * `chosen` es el código que el comprador guardó al elegir a mano (\"market\" en cookie): si existe, no se vuelve a sugerir.\n */\nexport function suggestMarket({\n headers,\n markets,\n current,\n chosen,\n trustProxy = true,\n}: {\n headers: Headers\n markets: MarketInfo[]\n current: string\n chosen?: string | null\n trustProxy?: boolean\n}): MarketSuggestion | null {\n if (chosen || markets.length < 2) return null\n if (BOT.test(headers.get('user-agent') ?? '')) return null\n\n const country = visitorCountry(headers, { trustProxy })\n if (country) {\n const target = markets.find((m) => m.countries.includes(country))\n return target && target.code !== current ? { market: target, reason: 'country' } : null\n }\n // Sin país del CDN: la región del idioma del navegador (\"en-US\" → US), solo como pista débil.\n for (const tag of preferredLanguages(headers.get('accept-language'))) {\n const region = tag.split('-')[1]?.toUpperCase()\n if (!region) continue\n const target = markets.find((m) => m.countries.includes(region))\n if (target) return target.code !== current ? { market: target, reason: 'language' } : null\n }\n return null\n}\n\n/**\n * Enlaces `hreflang` para <head>: un alterno por mercado con dominio propio, más x-default (el mercado por defecto).\n * `path` es la ruta con query actual (\"/productos/x\"). Es lo que permite a buscadores servir cada país en su idioma.\n */\nexport function hreflangLinks(markets: MarketInfo[], path: string, defaultMarket: string, protocol = 'https'): { hrefLang: string; href: string }[] {\n const links = markets\n .filter((m) => m.host)\n .map((m) => ({ hrefLang: m.locale, href: `${protocol}://${m.host}${path}` }))\n const fallback = markets.find((m) => m.code === defaultMarket && m.host)\n if (fallback) links.push({ hrefLang: 'x-default', href: `${protocol}://${fallback.host}${path}` })\n return links\n}\n","/**\n * Pure helpers over an `Order` (contract 1.8): the unified progress, the one next action, shipment ordering and the\n * \"test\" rules. They READ what the server sent and only derive what an older server (no `progress` / `next_action`)\n * did not. Every enum is open: an unknown stage, step state or shipment status never throws, it is kept as is and the\n * UI shows its safe fallback.\n */\nimport { safeHttpsUrl } from './payments.js'\nimport type {\n InvoiceDoc,\n NextAction,\n Order,\n OrderProblem,\n OrderProgress,\n OrderProgressStep,\n OrderStage,\n OrderStepKey,\n Shipment,\n ShipmentEvent,\n ShipmentStatus,\n} from './types.js'\n\n/** Steps of an order that ships, in order. */\nexport const SHIPPING_STEPS = ['paid', 'preparing', 'shipped', 'in_transit', 'delivered'] as const\n/** Steps of an order the buyer picks up. */\nexport const PICKUP_STEPS = ['paid', 'preparing', 'ready_for_pickup', 'delivered'] as const\n\n/** Shipment statuses that mean the package is not where it should be. */\nconst SHIPMENT_PROBLEMS: Record<string, string> = { exception: 'delivery_exception', returned: 'returned', lost: 'lost' }\n\nconst RANK: Record<string, number> = { pending: 0, label_created: 1, in_transit: 2, out_for_delivery: 3, delivered: 4 }\n\nconst isRecord = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v)\n\n/** A shipment the buyer can be told about as real: not a sandbox one. */\nexport function isTestShipment(s: Pick<Shipment, 'test_mode' | 'environment'> | null | undefined): boolean {\n return !!s && (s.test_mode === true || s.environment === 'sandbox')\n}\n\n/** An invoice or credit note from a sandbox PAC. */\nexport function isTestInvoice(d: Pick<InvoiceDoc, 'test_mode' | 'environment'> | null | undefined): boolean {\n return !!d && (d.test_mode === true || d.environment === 'sandbox')\n}\n\n/** `https` URL with no credentials, or `null`. The only kind of link a tracking or voucher button may carry. */\nexport function safeTrackingUrl(value: unknown): string | null {\n return safeHttpsUrl(value)\n}\n\nfunction time(iso: string | null | undefined): number {\n const t = iso ? Date.parse(iso) : NaN\n return Number.isNaN(t) ? -Infinity : t\n}\n\n/** Newest first, invalid dates last, ties keep the server's order; at most `limit` (default 50, the contract's cap). */\nexport function sortTrackingEvents(events: readonly ShipmentEvent[] | null | undefined, limit = 50): ShipmentEvent[] {\n if (!Array.isArray(events)) return []\n return events\n .filter(isRecord as (e: unknown) => e is ShipmentEvent)\n .map((e, i) => ({ e, i }))\n .sort((a, b) => time(b.e.occurred_at) - time(a.e.occurred_at) || a.i - b.i)\n .slice(0, Math.max(0, limit))\n .map((x) => x.e)\n}\n\n/** The shipments of the order that count: outbound/pickup/local first, returns after; stable otherwise. */\nexport function orderShipments(order: Pick<Order, 'shipments'> | null | undefined): Shipment[] {\n const list = Array.isArray(order?.shipments) ? order!.shipments!.filter(isRecord as (s: unknown) => s is Shipment) : []\n return [...list.filter((s) => s.kind !== 'return'), ...list.filter((s) => s.kind === 'return')]\n}\n\nfunction validProgress(p: unknown): p is OrderProgress {\n return isRecord(p) && typeof p.stage === 'string' && Array.isArray(p.steps)\n}\n\nconst validStep = (s: unknown): s is OrderProgressStep => isRecord(s) && typeof s.key === 'string' && typeof s.state === 'string'\n\n/** The server's progress with anything malformed dropped: a bad step or problem never reaches the UI. */\nfunction cleanProgress(p: OrderProgress): OrderProgress {\n if (p.steps.every(validStep) && (p.problem === undefined || p.problem === null || (isRecord(p.problem) && typeof p.problem.code === 'string'))) return p\n const problem = isRecord(p.problem) && typeof p.problem.code === 'string' ? p.problem : null\n return { stage: p.stage, problem, steps: p.steps.filter(validStep) }\n}\n\n/** Shipments that tell the buyer something real about delivery: not returns, not sandbox. */\nconst liveShipments = (shipments: Shipment[]) => shipments.filter((s) => s.kind !== 'return' && !isTestShipment(s))\n\n/** The stage of an order from its legacy `status` / `payment_status` and its shipments (servers before contract 1.8). */\nfunction legacyStage(order: Order, shipments: Shipment[]): OrderStage {\n const status = typeof order.status === 'string' ? order.status.toLowerCase() : ''\n const pickup = order.delivery_method === 'pickup'\n if (status === 'cancelled' || status === 'canceled') return 'cancelled'\n if (status === 'refunded') return 'refunded'\n if (status === 'pending_payment' || order.payment_status === 'pending') return 'pending_payment'\n if (status === 'delivered' || status === 'fulfilled') return 'delivered'\n // The order is as far as its LEAST advanced live shipment (a partial delivery is not a delivered order); cancelled\n // legs and legs with a problem (flagged apart) do not hold it back. Same rule as the server.\n const live = liveShipments(shipments)\n const ranked = live.filter((s) => RANK[s.status] !== undefined)\n const least = ranked.reduce<string | null>((acc, s) => (acc === null || RANK[s.status]! < RANK[acc]! ? s.status : acc), null)\n if (least === 'delivered') return 'delivered'\n if (least === 'out_for_delivery') return 'out_for_delivery'\n if (least === 'in_transit') return 'in_transit'\n if (status === 'ready_for_pickup' || (status === 'ready' && pickup)) return 'ready_for_pickup'\n // A `shipped` status whose every shipment is a sandbox one: the package is not really on its way.\n const onlySandbox = shipments.some((s) => s.kind !== 'return') && live.length === 0\n if ((status === 'shipped' && !onlySandbox) || least === 'label_created') return 'shipped'\n if (status === 'fulfilling' || status === 'accepted' || status === 'ready' || status === 'shipped') return 'preparing'\n return 'paid'\n}\n\nconst STAGE_TO_STEP: Record<string, OrderStepKey> = {\n paid: 'paid',\n preparing: 'preparing',\n ready_for_pickup: 'ready_for_pickup',\n shipped: 'shipped',\n in_transit: 'in_transit',\n out_for_delivery: 'in_transit',\n delivered: 'delivered',\n}\n\n/** When the payment was confirmed (not when the order was placed: a cash voucher is paid days later), or `null`. */\nfunction paidAt(order: Order): string | null {\n const paid = Array.isArray(order.payments) ? order.payments.find((p) => isRecord(p) && typeof p.paid_at === 'string' && p.paid_at) : undefined\n return paid?.paid_at ?? null\n}\n\n/**\n * The unified progress. The server's `order.progress` wins when it is well formed; otherwise it is derived, so a store\n * on an older OPS still gets a timeline. Pending payment, cancelled and refunded orders have no steps to walk: `steps`\n * lists them as `pending` (or `[]` when cancelled/refunded) and the stage says why.\n */\nexport function orderProgress(order: Order): OrderProgress {\n if (validProgress(order.progress)) return cleanProgress(order.progress)\n const shipments = orderShipments(order)\n const stage = legacyStage(order, shipments)\n const keys: readonly string[] = order.delivery_method === 'pickup' ? PICKUP_STEPS : SHIPPING_STEPS\n const dead = stage === 'cancelled' || stage === 'refunded'\n const awaiting = stage === 'pending_payment'\n const current = STAGE_TO_STEP[stage] ?? 'paid'\n const at = keys.indexOf(current)\n const failed = liveShipments(shipments).find((s) => SHIPMENT_PROBLEMS[s.status])\n const problem: OrderProblem | null = failed\n ? { code: SHIPMENT_PROBLEMS[failed.status]!, at: sortTrackingEvents(failed.events)[0]?.occurred_at ?? null }\n : order.payment_status === 'failed'\n ? { code: 'payment_failed' }\n : null\n const steps: OrderProgressStep[] = dead\n ? []\n : keys.map((key, i) => {\n if (awaiting) return { key, state: 'pending', at: null }\n const state = i < at || stage === 'delivered' ? 'done' : i === at ? (problem && i >= keys.indexOf('shipped') ? 'problem' : 'current') : 'pending'\n return { key, state, at: key === 'paid' && state === 'done' ? paidAt(order) : null }\n })\n return { stage, problem, steps }\n}\n\n/**\n * The action to put first. The server's `next_action` wins (its `href` is re-checked: only `https`); an older server\n * gets one derived from the order and its invoice. Never `null`: `{ kind: 'none' }` means \"nothing to offer\".\n */\nexport function nextAction(order: Order): NextAction {\n // A 1.8 server that sends `next_action: null` means \"nothing to offer\"; only an older server (no key) is derived.\n if (order.next_action === null) return { kind: 'none', href: null, ref: null }\n if (isRecord(order.next_action) && typeof order.next_action.kind === 'string') {\n const href = safeTrackingUrl(order.next_action.href)\n return { kind: order.next_action.kind, href, ref: typeof order.next_action.ref === 'string' ? order.next_action.ref : null }\n }\n const progress = orderProgress(order)\n if (progress.stage === 'pending_payment') return { kind: 'pay', href: null, ref: null }\n if (progress.stage === 'cancelled' || progress.stage === 'refunded') return { kind: 'none', href: null, ref: null }\n const live = orderShipments(order).find((s) => s.kind !== 'return' && !isTestShipment(s) && s.status !== 'delivered' && s.status !== 'cancelled')\n const trackUrl = safeTrackingUrl(live?.tracking_url)\n if (live && trackUrl) return { kind: 'track', href: trackUrl, ref: live.id }\n if (progress.stage === 'ready_for_pickup') return { kind: 'pickup', href: null, ref: null }\n const inv = isRecord(order.invoice) ? order.invoice : undefined\n // The server's `action` wins over the stage: an issued invoice it does not offer (no file yet) is not a button.\n if (inv?.action === 'download' || (inv?.action === undefined && inv?.stage === 'issued')) {\n const docs = Array.isArray(order.invoices) ? order.invoices.filter((d) => isRecord(d) && d.kind === 'invoice' && d.status !== 'cancelled') : []\n const real = docs.find((d) => !isTestInvoice(d))\n // Detail with only sandbox invoices: never offer one as the buyer's invoice.\n if (docs.length === 0 || real) return { kind: 'download_invoice', href: null, ref: real?.id ?? null }\n }\n if (inv?.action === 'correct_data') return { kind: 'correct_invoice_data', href: null, ref: null }\n if (inv?.action === 'contact_store') return { kind: 'contact_store', href: null, ref: null }\n if (inv?.can_request === true && inv.stage !== 'requested') return { kind: 'request_invoice', href: null, ref: null }\n return { kind: 'none', href: null, ref: null }\n}\n\n/** Latest known status among the live (non-sandbox, non-return) shipments, or `null`. */\nexport function shipmentsStatus(order: Order): ShipmentStatus | null {\n if (order.shipments_summary && typeof order.shipments_summary.status === 'string') return order.shipments_summary.status\n const live = orderShipments(order).filter((s) => s.kind !== 'return' && !isTestShipment(s))\n return live.length ? live[0]!.status : null\n}\n","import type { StorefrontError } from './errors.js'\n\n/**\n * Account settings of the buyer (contract 1.9): active sessions, recent re-authentication, language and\n * notification preferences, data export and account deletion. Types and small pure helpers; the calls live on\n * `client.customer`.\n */\n\n/** Notification preferences: event → channel → on. Only optional events can be configured (never the order confirmation or the invoice). */\nexport type CustomerPreferences = {\n notifications?: Record<string, Record<string, boolean>>\n}\n\n/** One session of the buyer for a «Devices» list. The server never sends an address or a token. */\nexport type CustomerSessionInfo = {\n id: string\n /** `true` for the session that made the request. */\n current: boolean\n /** A summary such as «Chrome · Windows». Never a full user agent. */\n device_label: string\n login_method: 'email' | 'phone' | 'password' | (string & {})\n last_used_at?: string | null\n created_at: string\n}\n\n/** What proves the buyer is who they say: the password, or a sign-in code requested with `customer.requestOtp`. Exactly one. */\nexport type ReauthInput = { password: string; otp_code?: never } | { otp_code: string; password?: never }\n\nexport type ReauthResult = {\n reauth_at: string\n /** How long the confirmation lasts (seconds). It applies to the session that made the call, nowhere else. */\n valid_for_seconds?: number\n}\n\n/** The buyer's data as a JSON file, in memory. `content_base64` is the file; serve it as a download and do not keep it. */\nexport type DataExportFile = {\n filename: string\n content_type: string\n content_base64: string\n}\n\n/** `DELETE /customer`. `confirm` is the text your interface asked the buyer to type. */\nexport type AccountDeleteInput = { confirm: string }\n\n/**\n * `true` when a call was refused because the buyer must confirm their password or a code first\n * (`403` with code `reauth_required`): show your confirmation step, call `customer.reauth`, and repeat the call.\n */\nexport function isReauthRequired(error: unknown): error is StorefrontError {\n const e = error as { status?: unknown; code?: unknown } | null\n return !!e && typeof e === 'object' && e.status === 403 && e.code === 'reauth_required'\n}\n\n/**\n * `true` when deleting the account was refused because an order is on its way or a payment is still pending\n * (`409`; `field` says which: `orders` or `pending_payments`).\n */\nexport function isAccountDeleteBlocked(error: unknown): error is StorefrontError & { field: 'orders' | 'pending_payments' } {\n const e = error as { status?: unknown; field?: unknown } | null\n return !!e && typeof e === 'object' && e.status === 409 && (e.field === 'orders' || e.field === 'pending_payments')\n}\n\n/** Decodes `content_base64` of a data export. Throws `TypeError` when it is not valid base64. */\nexport function dataExportBytes(file: Pick<DataExportFile, 'content_base64'>): Uint8Array {\n const raw = typeof file.content_base64 === 'string' ? file.content_base64.replace(/\\s+/g, '') : ''\n if (!/^[A-Za-z0-9+/]*={0,2}$/.test(raw) || raw.length % 4 === 1) throw new TypeError('data export is not valid base64')\n const bin = atob(raw)\n const out = new Uint8Array(bin.length)\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i)\n return out\n}\n\n/** A download filename that is safe in a `Content-Disposition` header: no path, quotes, control characters or spaces. */\nexport function safeExportFilename(name: unknown, fallback = 'account-data.json'): string {\n const base = typeof name === 'string' ? (name.split(/[\\\\/]/).pop() ?? '') : ''\n const clean = base.replace(/[^A-Za-z0-9._-]+/g, '_').replace(/^\\.+/, '').slice(0, 80)\n return clean || fallback\n}\n","/** Invoices and credit notes of an order, and the bytes of a downloaded file. Pure; no URL of the PAC ever passes here. */\nimport type { InvoiceDoc, InvoiceFile } from './types.js'\n\nexport type InvoiceGroup = { invoice: InvoiceDoc; creditNotes: InvoiceDoc[] }\n\n/**\n * Groups credit notes under the invoice they correct (`related_to`), keeping the server's order. A credit note whose\n * invoice is not in the list (or has no `related_to`) is returned in `orphans`, never dropped.\n */\nexport function groupInvoiceDocs(docs: readonly InvoiceDoc[] | null | undefined): { groups: InvoiceGroup[]; orphans: InvoiceDoc[] } {\n const list = Array.isArray(docs) ? docs.filter((d): d is InvoiceDoc => !!d && typeof d === 'object') : []\n const groups: InvoiceGroup[] = list.filter((d) => d.kind !== 'credit_note').map((invoice) => ({ invoice, creditNotes: [] }))\n const orphans: InvoiceDoc[] = []\n for (const d of list) {\n if (d.kind !== 'credit_note') continue\n const group = d.related_to ? groups.find((g) => g.invoice.id === d.related_to) : undefined\n if (group) group.creditNotes.push(d)\n else orphans.push(d)\n }\n return { groups, orphans }\n}\n\n/** Decodes `content_base64` of a downloaded invoice file. Throws `TypeError` when it is not valid base64. */\nexport function invoiceFileBytes(file: Pick<InvoiceFile, 'content_base64'>): Uint8Array {\n const raw = typeof file.content_base64 === 'string' ? file.content_base64.replace(/\\s+/g, '') : ''\n if (!/^[A-Za-z0-9+/]*={0,2}$/.test(raw) || raw.length % 4 === 1) throw new TypeError('invoice file is not valid base64')\n const bin = atob(raw)\n const out = new Uint8Array(bin.length)\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i)\n return out\n}\n\n/** A download filename that is safe in a `Content-Disposition` header: no path, quotes, control characters or spaces. */\nexport function safeInvoiceFilename(name: unknown, fallback = 'factura'): string {\n const base = typeof name === 'string' ? (name.split(/[\\\\/]/).pop() ?? '') : ''\n const clean = base.replace(/[^A-Za-z0-9._-]+/g, '_').replace(/^\\.+/, '').slice(0, 80)\n return clean || fallback\n}\n","// «My items» (contract 1.9): the pure side. The cascade of options a form shows, the same validation the server runs\n// (the server is the authority; this gives the buyer the answer without a round trip), the compatibility key and the\n// product tags it filters with. No UI, no storage, no copy, and no kind is named here: a kind is data the organization\n// publishes (`content.subjectKinds()`), and what a field \"means\" (make, size, breed) is only its label.\n//\n// Privacy: a `private` field (a licence plate) is kept apart. It is never part of `label`, `fit_key` or any tag, and\n// `maskedValue` / `isMasked` are how the server's mask is recognized so it is never sent back as if it were a value.\n\nimport type { SubjectCatalogNode, SubjectField, SubjectKind } from './types.js'\n\nexport const MIN_SUBJECT_YEAR = 1900\nexport const MAX_SUBJECT_YEAR = 2100\nconst MAX_VALUE_LENGTH = 80\nconst MAX_LABEL_LENGTH = 120\nconst MAX_FIT_KEY_LENGTH = 100\n\nexport type SubjectOption = { value: string; label: string }\nexport type SubjectValues = Record<string, string | number | null | undefined>\n\n/** Why a value was refused (the server answers `422` with the field `attributes.<key>` and never the value). */\nexport type SubjectProblemCode = 'required' | 'unknown' | 'invalid' | 'not_in_catalog' | 'year_range' | 'catalog_unavailable'\nexport type SubjectProblems = Record<string, SubjectProblemCode>\n\nexport type ResolvedSubject = {\n /** Built from the labels of the catalog and the public values, in field order. */\n label: string\n /** `''` when a placeholder of the template has no value (the item then never matches a product). */\n fit_key: string\n /** Public values, as the server stores them in `attributes`. */\n attributes: Record<string, string | number>\n /** Private values: never in the label, the key or a tag. */\n private: Record<string, string>\n}\n\nconst isPresent = (v: unknown): boolean => v !== null && v !== undefined && v !== ''\n\nconst asYear = (v: unknown): number | null => {\n const n = typeof v === 'number' ? v : typeof v === 'string' && /^\\s*\\d+\\s*$/.test(v) ? Number(v) : NaN\n return Number.isInteger(n) && n >= MIN_SUBJECT_YEAR && n <= MAX_SUBJECT_YEAR ? n : null\n}\n\n/** Collapses whitespace; `null` for a non-string, a control character or a value over `max` characters. */\nconst cleanText = (v: unknown, max: number): string | null => {\n if (typeof v !== 'string') return null\n const s = v.split(/\\s+/).filter(Boolean).join(' ')\n // eslint-disable-next-line no-control-regex\n return [...s].length > max || /[\\u0000-\\u001f\\u007f-\\u009f]/.test(s) ? null : s\n}\n\nconst slug = (s: string): string => s.toLowerCase().replace(/[^a-z0-9._+-]+/g, '-').replace(/^-+|-+$/g, '')\n\n/** Does the option cover the model year? Declared `ranges` win; else `from`/`to`; an option with none covers any year. */\nexport function coversYear(node: Pick<SubjectCatalogNode, 'from' | 'to' | 'ranges'>, year: number): boolean {\n if (node.ranges && node.ranges.length > 0) return node.ranges.some(([a, b]) => year >= a && year <= b)\n if (node.from !== undefined && year < node.from) return false\n if (node.to !== undefined && year > node.to) return false\n return true\n}\n\nconst declaresYears = (n: SubjectCatalogNode): boolean => n.from !== undefined || n.to !== undefined || (n.ranges?.length ?? 0) > 0\n\n/** The catalog fields that make the tree's levels, in order: `source: catalog` and not a year. */\nexport function subjectLevels(kind: Pick<SubjectKind, 'fields'>): SubjectField[] {\n return kind.fields.filter((f) => f.source === 'catalog' && f.type !== 'year')\n}\n\n/** The visible fields of a form: everything the buyer fills in, in the order of the kind. */\nexport function subjectFields(kind: Pick<SubjectKind, 'fields'>): SubjectField[] {\n return kind.fields\n}\n\n/** Walks the chosen values down the tree; stops at the first level without a (valid) choice. */\nfunction walk(kind: SubjectKind, values: SubjectValues): { path: SubjectCatalogNode[]; ids: Record<string, string>; next: Record<string, SubjectCatalogNode> | undefined } {\n const path: SubjectCatalogNode[] = []\n const ids: Record<string, string> = {}\n let tree: Record<string, SubjectCatalogNode> | undefined = kind.catalog?.tree\n for (const f of subjectLevels(kind)) {\n const raw = values[f.key]\n const s = isPresent(raw) ? cleanText(raw, MAX_VALUE_LENGTH) : null\n const node: SubjectCatalogNode | undefined = s && tree ? (tree[s] ?? tree[s.toLowerCase()]) : undefined\n if (!s || !node) return { path, ids, next: tree }\n ids[f.key] = tree && tree[s] ? s : s.toLowerCase()\n path.push(node)\n tree = node.children\n if (!tree) return { path, ids, next: undefined }\n }\n return { path, ids, next: tree }\n}\n\nconst byLabel = (a: SubjectOption, b: SubjectOption) => a.label.localeCompare(b.label, undefined, { sensitivity: 'base', numeric: true })\n\n/**\n * The options a catalog field offers given what is already chosen (a cascade: a level shows nothing until the previous\n * one is chosen). A level narrows by the chosen year when the option declares years; a year field offers the model\n * years the chosen options cover (newest first), or nothing when no option declares years (a free number then).\n */\nexport function subjectOptions(kind: SubjectKind, fieldKey: string, values: SubjectValues): SubjectOption[] {\n const field = kind.fields.find((f) => f.key === fieldKey)\n if (!field || field.source !== 'catalog' || !kind.catalog) return []\n if (field.type === 'year') {\n // Only the options chosen BEFORE the year constrain it (a stale choice after it is reconciled against the year).\n const upto = kind.fields.slice(0, kind.fields.indexOf(field))\n const { path } = walk({ ...kind, fields: upto }, values)\n const declared = path.filter(declaresYears)\n if (declared.length === 0) return []\n let lo = Infinity\n let hi = -Infinity\n for (const n of declared) {\n for (const [a, b] of n.ranges?.length ? n.ranges : [[n.from ?? MIN_SUBJECT_YEAR, n.to ?? MAX_SUBJECT_YEAR] as [number, number]]) {\n lo = Math.min(lo, a)\n hi = Math.max(hi, b)\n }\n }\n const out: SubjectOption[] = []\n for (let y = Math.min(hi, MAX_SUBJECT_YEAR); y >= Math.max(lo, MIN_SUBJECT_YEAR); y--) if (declared.every((n) => coversYear(n, y))) out.push({ value: String(y), label: String(y) })\n return out\n }\n const levels = subjectLevels(kind)\n const at = levels.findIndex((f) => f.key === fieldKey)\n if (at < 0) return []\n // Only the levels before this one must be chosen.\n const before = Object.fromEntries(levels.slice(0, at).map((f) => [f.key, values[f.key]]))\n const { path, next } = walk({ ...kind, fields: kind.fields.filter((f) => levels.slice(0, at).includes(f) || f.type === 'year') }, before)\n if (path.length < at || !next) return []\n const year = asYear(values[kind.fields.find((f) => f.type === 'year' && f.source === 'catalog')?.key ?? ''])\n return Object.entries(next)\n .filter(([, n]) => year === null || coversYear(n, year))\n .map(([value, n]) => ({ value, label: n.label }))\n .sort(byLabel)\n}\n\n/**\n * Drops what was chosen and is no longer valid after a change (a new make clears the model; a year the model does not\n * cover is cleared), in field order. Free values are never touched.\n */\nexport function reconcileSubjectValues(kind: SubjectKind, values: SubjectValues): SubjectValues {\n const out: SubjectValues = { ...values }\n for (const f of kind.fields) {\n if (f.source !== 'catalog' || !isPresent(out[f.key])) continue\n const options = subjectOptions(kind, f.key, out)\n const v = String(out[f.key])\n const ok = f.type === 'year' ? options.length === 0 || options.some((o) => o.value === v) : options.some((o) => o.value === v || o.value === v.toLowerCase())\n if (!ok) out[f.key] = ''\n }\n return out\n}\n\n/**\n * Validates and resolves the values the way the server does: unknown field, wrong type, a value missing from the\n * catalog and a year outside the chosen options' years are refused, naming the field only.\n */\nexport function resolveSubject(kind: SubjectKind, values: SubjectValues): { ok: true; subject: ResolvedSubject } | { ok: false; problems: SubjectProblems } {\n const problems: SubjectProblems = {}\n const known = new Set(kind.fields.map((f) => f.key))\n for (const key of Object.keys(values)) if (isPresent(values[key]) && !known.has(key)) problems[key] = 'unknown'\n\n const attributes: Record<string, string | number> = {}\n const priv: Record<string, string> = {}\n const display: Record<string, string> = {}\n const ids: Record<string, string> = {}\n const path: SubjectCatalogNode[] = []\n let tree: Record<string, SubjectCatalogNode> | undefined = kind.catalog?.tree\n const years: string[] = []\n const put = (f: SubjectField, v: string | number) => {\n if (f.private) priv[f.key] = String(v)\n else attributes[f.key] = v\n }\n for (const f of kind.fields) {\n const raw = values[f.key]\n if (!isPresent(raw)) {\n if (f.required) problems[f.key] = 'required'\n if (f.source === 'catalog' && f.type !== 'year') tree = undefined // a skipped level ends the walk\n continue\n }\n const max = f.max ?? MAX_VALUE_LENGTH\n if (f.type === 'year') {\n const y = asYear(raw)\n if (y === null) {\n problems[f.key] = 'invalid'\n continue\n }\n put(f, y)\n display[f.key] = ids[f.key] = String(y)\n if (f.source === 'catalog') years.push(f.key)\n } else if (f.source === 'catalog') {\n if (!kind.catalog) {\n problems[f.key] = 'catalog_unavailable'\n continue\n }\n const s = cleanText(raw, max)\n if (s === null) {\n problems[f.key] = 'invalid'\n continue\n }\n const node: SubjectCatalogNode | undefined = tree?.[s] ?? tree?.[s.toLowerCase()]\n if (!node) {\n problems[f.key] = 'not_in_catalog'\n continue\n }\n const id = tree?.[s] ? s : s.toLowerCase()\n path.push(node)\n tree = node.children\n put(f, id)\n display[f.key] = node.label\n ids[f.key] = id\n } else {\n const s = cleanText(raw, max)\n if (s === null) {\n problems[f.key] = 'invalid'\n continue\n }\n put(f, s)\n display[f.key] = s\n ids[f.key] = slug(s)\n }\n }\n for (const key of years) {\n const y = attributes[key] as number | undefined\n if (y !== undefined && !problems[key] && !path.every((n) => coversYear(n, y))) problems[key] = 'year_range'\n }\n if (Object.keys(problems).length > 0) return { ok: false, problems }\n\n const label = [...kind.fields.filter((f) => !f.private).map((f) => display[f.key]).filter(Boolean).join(' ')].slice(0, MAX_LABEL_LENGTH).join('').trim()\n if (!label) return { ok: false, problems: { _: 'required' } }\n let complete = true\n const key = kind.fit_key_template.replace(/\\{([a-z][a-z0-9_]*)\\}/g, (_m, name: string) => {\n const id = ids[name]\n if (!id) complete = false\n return id ?? ''\n })\n return { ok: true, subject: { label, fit_key: complete && key.length <= MAX_FIT_KEY_LENGTH ? key.toLowerCase() : '', attributes, private: priv } }\n}\n\n/** The mask the server puts in place of a private value («••34»). */\nexport const PRIVATE_MASK = '••'\nexport const isMasked = (v: unknown): boolean => typeof v === 'string' && v.startsWith(PRIVATE_MASK)\n\n/** Prefix of the tag that publishes compatibility (`<prefix><fit_key>`), as in `FitmentConfig.tagPrefix`. */\nexport const DEFAULT_FIT_TAG_PREFIX = 'fit:'\n\n/** The product tag that marks a part as fitting the item with this key. */\nexport const fitTag = (fitKey: string, prefix: string = DEFAULT_FIT_TAG_PREFIX): string => `${prefix}${fitKey}`\n\n/**\n * The `tags_any` of a listing \"only what fits my item\": its own tag plus the universal one (`<prefix>universal`).\n * `[]` when the item has no key (it does not resolve completely): ask for nothing rather than for the wrong thing.\n */\nexport function fitTagsAny(fitKey: string | null | undefined, opts: { prefix?: string; universal?: boolean } = {}): string[] {\n if (!fitKey) return []\n const prefix = opts.prefix ?? DEFAULT_FIT_TAG_PREFIX\n return opts.universal === false ? [fitTag(fitKey, prefix)] : [fitTag(fitKey, prefix), `${prefix}universal`]\n}\n\n/**\n * Budget of one catalog page, in bytes of the `tree` prop as OPS stores it (text, so every quote is escaped). Publishing\n * a page is ONE write of at most 64 KiB that carries the draft and the published copy: ~28 KB of tree per page.\n */\nexport const SUBJECT_CATALOG_PAGE_BYTES = 28 * 1024\n\nconst utf8Bytes = (s: string): number => new TextEncoder().encode(s).length\n\n/**\n * Splits a catalog tree by its first level into parts that each fit one page (`subject_catalog` section, prop `tree`).\n * Publish part `i` on its own page and name them all in the kind's `catalog_ref` (`[\"page:x-1\", \"page:x-2\", …]`); the\n * server joins them back. A real parts catalog (make → model → engine) does not fit in one page. Throws `RangeError`\n * when a single first-level option is larger than the budget on its own (split that level by hand, or trim labels).\n */\nexport function splitSubjectTree(\n tree: Record<string, SubjectCatalogNode>,\n maxBytes: number = SUBJECT_CATALOG_PAGE_BYTES,\n): Record<string, SubjectCatalogNode>[] {\n const size = (part: Record<string, SubjectCatalogNode>) => utf8Bytes(JSON.stringify(JSON.stringify(part)))\n const parts: Record<string, SubjectCatalogNode>[] = []\n let current: Record<string, SubjectCatalogNode> = {}\n for (const [id, node] of Object.entries(tree)) {\n if (size({ [id]: node }) > maxBytes) throw new RangeError(`splitSubjectTree: option ${id} alone exceeds ${maxBytes} bytes`)\n const next = { ...current, [id]: node }\n if (Object.keys(current).length > 0 && size(next) > maxBytes) {\n parts.push(current)\n current = { [id]: node }\n } else current = next\n }\n if (Object.keys(current).length > 0) parts.push(current)\n return parts\n}\n","import type { DeliveryInput, DeliveryMethod, DeliveryOptions, UnavailableRateProvider } from './types.js'\n\n/** Kind of a delivery radio: `ship` (address only, quote later), `rate` (a quoted rate) or `pickup` (a branch). */\nexport type DeliveryChoiceKind = 'ship' | 'rate' | 'pickup'\n\nexport type DeliveryChoice = {\n kind: DeliveryChoiceKind\n /** Everything after the first `:` — a rate id may contain more colons (`rate:skydropx:<id>`). */\n id: string\n method: DeliveryMethod\n /** `ship:` — only the address is saved; the rate is picked on the next pass. */\n addressOnly: boolean\n}\n\n/**\n * Parses the value of the single delivery radio group: `ship:`, `rate:<id>` or `pickup:<branch>`.\n * Splits on the FIRST colon only, so ids like `skydropx:<id>` survive intact (`split(':', 2)` would\n * silently drop everything after the second colon). Anything unknown is treated as `rate`.\n */\nexport function parseDelivery(value: string | null | undefined): DeliveryChoice {\n const raw = (value ?? '').trim()\n const i = raw.indexOf(':')\n const head = i === -1 ? raw : raw.slice(0, i)\n const id = i === -1 ? '' : raw.slice(i + 1)\n const kind: DeliveryChoiceKind = head === 'pickup' ? 'pickup' : head === 'ship' ? 'ship' : 'rate'\n return { kind, id, method: kind === 'pickup' ? 'pickup' : 'shipping', addressOnly: kind === 'ship' }\n}\n\n/** The `setDelivery` payload for a choice; `null` when it only saves the address (`ship:`). */\nexport function deliveryInput(choice: DeliveryChoice): DeliveryInput | null {\n if (choice.addressOnly) return null\n if (choice.kind === 'pickup') return { method: 'pickup', branch_id: choice.id }\n return { method: 'shipping', rate_id: choice.id || undefined }\n}\n\n/** Reason code a rate provider reports when the cart has items without weight. */\nexport const MISSING_WEIGHT = 'missing_weight'\n\nexport type DeliveryNotices = {\n /** Providers that could not quote because some item has no weight. */\n missingWeight: UnavailableRateProvider[]\n /** Providers that failed for any other reason (timeouts, errors). */\n unavailable: UnavailableRateProvider[]\n /** `true` when the shopper should be told something is off with the quote. */\n hasNotices: boolean\n}\n\n/** Splits `delivery.unavailable` into the `missing_weight` notice and the generic one. */\nexport function deliveryNotices(delivery: Pick<DeliveryOptions, 'unavailable' | 'partial'> | null | undefined): DeliveryNotices {\n const all = delivery?.unavailable ?? []\n const missingWeight = all.filter((u) => u.code === MISSING_WEIGHT)\n const unavailable = all.filter((u) => u.code !== MISSING_WEIGHT)\n return {\n missingWeight,\n unavailable,\n hasNotices: missingWeight.length > 0 || unavailable.length > 0 || delivery?.partial === true,\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/errors.ts","../src/geo.ts","../src/money.ts","../src/query.ts","../src/client.ts","../src/payment-errors.ts","../src/diagnose.ts","../src/availability.ts","../src/payments.ts","../src/promotions.ts","../src/market.ts","../src/order-progress.ts","../src/account-settings.ts","../src/invoice-docs.ts","../src/subjects.ts","../src/delivery.ts","../src/account-lists.ts"],"names":["fmt","ES","EN","CATALOG","path","key"],"mappings":";;;AA8BO,IAAM,eAAA,GAAN,cAA8B,KAAA,CAAM;AAAA,EACvB,IAAA,GAAO,iBAAA;AAAA,EAChB,MAAA;AAAA,EACA,IAAA;AAAA,EACA,KAAA;AAAA,EACA,OAAA;AAAA,EACA,GAAA;AAAA;AAAA,EAEA,cAAA;AAAA;AAAA,EAEA,SAAA;AAAA;AAAA,EAEA,UAAA;AAAA;AAAA,EAEA,UAAA;AAAA;AAAA,EAEA,IAAA;AAAA;AAAA,EAEA,SAAA;AAAA,EAET,YAAY,IAAA,EAA2B;AACrC,IA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CAAA,EAAE,GAAI,EAAC,EAAG;AACzG;AAGO,SAAS,UAAU,KAAA,EAAmJ;AAC3K,EAAA,MAAM,IAAA,GAAO,aAAa,KAAK,CAAA;AAC/B,EAAA,IAAI,CAAC,IAAA,IAAQ,KAAA,CAAM,KAAA,KAAU,GAAG,OAAO,IAAA;AACvC,EAAA,OAAO,EAAE,IAAA,EAAM,EAAA,EAAI,IAAA,GAAO,KAAA,CAAM,QAAQ,CAAA,EAAG,KAAA,EAAO,OAAO,KAAA,CAAM,UAAU,QAAA,IAAY,KAAA,CAAM,SAAS,CAAA,GAAI,KAAA,CAAM,QAAQ,IAAA,EAAK;AAC7H","file":"index.cjs","sourcesContent":["import type { InsufficientStockLine, StorefrontErrorCode } from './types.js'\n\nexport type StorefrontErrorInit = {\n status: number\n code: StorefrontErrorCode\n message: string\n field?: string\n /** Raw `error.details` from the body (untrusted shape). */\n details?: unknown\n /** Request URL that failed (without credentials). */\n url?: string\n cause?: unknown\n /** Scopes named by the gateway on a `403 insufficient_scope`. */\n requiredScopes?: string[]\n /** `error.retryable` as OPS declared it (payment failures). `undefined` = OPS did not say. */\n retryable?: boolean\n /** `error.retry_after` in seconds. */\n retryAfter?: number\n /** `error.checkout_id`: the checkout a refused cart write can resume. */\n checkoutId?: string\n /** `error.cost` of a `price_mismatch` (the cart's current cost; untrusted shape). */\n cost?: unknown\n /** `error.message_en`. */\n messageEn?: string\n}\n\n/**\n * Error thrown by the client for any non-2xx response, network failure,\n * timeout or abort. `status` is `0` when no HTTP response was received.\n */\nexport class StorefrontError extends Error {\n override readonly name = 'StorefrontError'\n readonly status: number\n readonly code: StorefrontErrorCode\n readonly field: string | undefined\n readonly details: unknown\n readonly url: string | undefined\n /** Scopes a `403 insufficient_scope` says the route needs (empty for any other error). */\n readonly requiredScopes: string[]\n /** `true`: repeating the request (same idempotency key) can succeed. `false`: not until someone fixes something. `undefined`: OPS did not say. */\n readonly retryable: boolean | undefined\n /** Seconds OPS asks to wait before retrying. */\n readonly retryAfter: number | undefined\n /** Checkout that a refused cart write can resume. */\n readonly checkoutId: string | undefined\n /** Current cart cost sent with a `price_mismatch` (untrusted shape). */\n readonly cost: unknown\n /** English version of `message`, when OPS sent one. */\n readonly messageEn: string | undefined\n\n constructor(init: StorefrontErrorInit) {\n super(init.message, init.cause === undefined ? undefined : { cause: init.cause })\n this.status = init.status\n this.code = init.code\n this.field = init.field\n this.details = init.details\n this.url = init.url\n this.requiredScopes = init.requiredScopes ?? []\n this.retryable = init.retryable\n this.retryAfter = init.retryAfter\n this.checkoutId = init.checkoutId\n this.cost = init.cost\n this.messageEn = init.messageEn\n }\n\n /**\n * Affected lines of a `409 insufficient_stock` (empty for any other error or a\n * server older than contract 1.1). The cart is untouched: show the lines and\n * let the buyer adjust or remove them.\n */\n get stockLines(): InsufficientStockLine[] {\n const lines = (this.details as { lines?: unknown } | null | undefined)?.lines\n if (this.code !== 'insufficient_stock' || !Array.isArray(lines)) return []\n return lines.filter((l): l is InsufficientStockLine => typeof l === 'object' && l !== null && typeof (l as { sku?: unknown }).sku === 'string')\n }\n\n toJSON() {\n return {\n name: this.name,\n status: this.status,\n code: this.code,\n message: this.message,\n field: this.field,\n ...(this.requiredScopes.length ? { requiredScopes: this.requiredScopes } : {}),\n ...(this.retryable !== undefined ? { retryable: this.retryable } : {}),\n ...(this.retryAfter !== undefined ? { retryAfter: this.retryAfter } : {}),\n ...(this.checkoutId ? { checkoutId: this.checkoutId } : {}),\n }\n }\n}\n\nexport function isStorefrontError(err: unknown): err is StorefrontError {\n return err instanceof StorefrontError || (typeof err === 'object' && err !== null && (err as { name?: unknown }).name === 'StorefrontError')\n}\n\nconst STATUS_CODES: Record<number, StorefrontErrorCode> = {\n 400: 'validation',\n 401: 'unauthorized',\n 403: 'forbidden',\n 404: 'not_found',\n 409: 'conflict',\n 422: 'invalid_state',\n 429: 'rate_limited',\n}\n\nexport function defaultCodeForStatus(status: number): StorefrontErrorCode {\n return STATUS_CODES[status] ?? (status >= 500 ? 'server_error' : 'invalid_response')\n}\n","/**\n * Geo helpers: pure TypeScript, no network and no DOM. Works in Node 20, edge\n * runtimes and browsers. Behaviour is pinned by `geo-vectors.json`, which the\n * Go side copies verbatim, so keep both implementations in sync.\n */\n\nexport type GeoPoint = { lat: number; lng: number }\n\n/** `(0, 0)` means \"unset\" on this platform, so it is never a valid point. */\ntype MaybePoint = { lat?: number | null; lng?: number | null } | null | undefined\n\nexport type OpeningHours = {\n /** `day`: 1 = Monday ... 7 = Sunday. Several entries per day are allowed. A `close` at or before `open` crosses midnight. */\n weekly: { day: number; open: string; close: string }[]\n /** Dated overrides of the weekly rule. `closed`, or both `open` and `close`. */\n exceptions?: { date: string; closed?: true; open?: string; close?: string; note?: string }[]\n}\n\nexport type OpenStatus = {\n open: boolean\n /** ISO instant (UTC) when the current interval ends; `null` when closed. */\n closesAt: string | null\n /** ISO instant (UTC) of the next opening; `null` when open or none within 8 days. */\n nextOpenAt: string | null\n}\n\nconst RAD = Math.PI / 180\n\n/** Great-circle distance in km (haversine, earth radius 6371.0088 km). */\nexport function distanceKm(a: GeoPoint, b: GeoPoint): number {\n const dLat = (b.lat - a.lat) * RAD\n const dLng = (b.lng - a.lng) * RAD\n const h = Math.sin(dLat / 2) ** 2 + Math.cos(a.lat * RAD) * Math.cos(b.lat * RAD) * Math.sin(dLng / 2) ** 2\n return 2 * 6371.0088 * Math.atan2(Math.sqrt(h), Math.sqrt(1 - h))\n}\n\n/** Finite, in range and not the `(0, 0)` \"unset\" pair. */\nexport function isValidPoint(p: MaybePoint): p is GeoPoint {\n const { lat, lng } = p ?? {}\n // Number.isFinite is false for null, undefined and non-numbers.\n return Number.isFinite(lat) && Number.isFinite(lng) && Math.abs(lat!) <= 90 && Math.abs(lng!) <= 180 && !(lat === 0 && lng === 0)\n}\n\n/** `'19.43,-99.13'` (spaces allowed) to a point; `null` when malformed or invalid. */\nexport function parseLatLng(s: string | null | undefined): GeoPoint | null {\n const [a, b, ...rest] = (s ?? '').split(',')\n const p = !rest.length && a?.trim() && b?.trim() ? { lat: Number(a), lng: Number(b) } : null\n return isValidPoint(p) ? p : null\n}\n\nexport type RankOptions<T> = {\n /** Keep items at most this far away (inclusive). */\n radiusKm?: number\n /** Keep the first N after sorting. */\n limit?: number\n /** Defaults to reading `lat` / `lng` from the item. */\n getPoint?: (item: T) => MaybePoint\n}\n\n/**\n * Sorts by distance from `origin` (stable: ties keep input order). Items without\n * a valid point are EXCLUDED, not placed last, because they have no distance.\n */\nexport function rankByDistance<T>(\n items: readonly T[],\n origin: GeoPoint,\n { radiusKm, limit, getPoint = (i) => i as MaybePoint }: RankOptions<T> = {},\n): { item: T; distanceKm: number }[] {\n const out: { item: T; distanceKm: number }[] = []\n for (const item of items) {\n const p = getPoint(item)\n if (!isValidPoint(p)) continue\n const d = distanceKm(origin, p)\n if (radiusKm === undefined || d <= radiusKm) out.push({ item, distanceKm: d })\n }\n // Array.prototype.sort is stable (ES2019), so ties keep input order.\n out.sort((x, y) => x.distanceKm - y.distanceKm)\n return limit === undefined ? out : out.slice(0, Math.max(0, limit))\n}\n\n/** Under 1 km: meters rounded to 50 m. Otherwise km with one decimal. */\nexport function formatDistance(km: number, locale = 'es-MX'): string {\n const m = Math.round((km * 1000) / 50) * 50\n const [value, unit, digits] = m < 1000 ? [m, 'meter', 0] : [km, 'kilometer', 1]\n return new Intl.NumberFormat(locale, {\n style: 'unit', unit, minimumFractionDigits: digits, maximumFractionDigits: digits,\n }).format(value)\n}\n\n/** Destination for directions: coordinates when valid, else the address text. */\nexport function directionsUrl(\n location: { lat?: number | null; lng?: number | null; address?: string | null; city?: string | null },\n { provider = 'google' }: { provider?: 'google' | 'apple' | 'geo' } = {},\n): string | null {\n const ll = isValidPoint(location) ? `${location.lat},${location.lng}` : null\n const text = [location.address, location.city].filter(Boolean).join(', ')\n const dest = ll ?? text\n if (!dest) return null\n const q = encodeURIComponent(dest)\n if (provider === 'apple') return `https://maps.apple.com/?daddr=${q}`\n if (provider === 'geo') return ll ? `geo:${ll}?q=${ll}` : `geo:0,0?q=${q}`\n return `https://www.google.com/maps/dir/?api=1&destination=${q}`\n}\n\n// --- opening hours -------------------------------------------------------\n\nconst toMin = (t: string | undefined): number => {\n const m = /^(\\d{1,2}):(\\d{2})$/.exec(t ?? '')\n return m ? Number(m[1]) * 60 + Number(m[2]) : NaN\n}\n\ntype Iv = [number, number]\n\n/** Intervals in minutes; an end at or before the start crosses midnight. */\nconst interval = (open: string | undefined, close: string | undefined): Iv[] => {\n const s = toMin(open)\n let e = toMin(close)\n if (Number.isNaN(s) || Number.isNaN(e)) return []\n if (e <= s) e += 1440\n return [[s, e]]\n}\n\nconst dayIntervals = (h: OpeningHours, day: number, date: string): Iv[] => {\n const x = h.exceptions?.find((e) => e.date === date)\n if (x?.closed) return []\n if (x && x.open && x.close) return interval(x.open, x.close)\n return h.weekly.filter((w) => w.day === day).flatMap((w) => interval(w.open, w.close))\n}\n\n/**\n * Whether the place is open at `now` in the IANA `timeZone` (throws RangeError\n * for an unknown zone). Looks 8 days ahead for the next opening. Handles\n * intervals crossing midnight, several per day, dated exceptions and DST.\n */\nexport function openStatus(hours: OpeningHours, timeZone: string, now: Date = new Date()): OpenStatus {\n const fmt = new Intl.DateTimeFormat('en-US', {\n timeZone, hourCycle: 'h23', year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric',\n })\n // Wall-clock minutes since the epoch as seen in `timeZone`.\n const wall = (ms: number): number => {\n const p: Record<string, number> = {}\n for (const { type, value } of fmt.formatToParts(ms)) p[type] = Number(value)\n return Date.UTC(p.year!, p.month! - 1, p.day!, (p.hour ?? 0) % 24, p.minute!) / 60000\n }\n const nowMs = now.getTime()\n const w = wall(nowMs)\n const day0 = Math.floor(w / 1440) * 1440\n // Offset from UTC, in minutes, at an instant.\n const offset = (ms: number): number => wall(ms) - Math.floor(ms / 60000)\n const toInstant = (t: number): string => {\n const guess = (t - offset(nowMs)) * 60000\n return new Date((t - offset(guess)) * 60000).toISOString()\n }\n\n const all: Iv[] = []\n for (let d = -1; d <= 8; d++) {\n const at = new Date((day0 + d * 1440) * 60000)\n const day = at.getUTCDay() || 7\n for (const [s, e] of dayIntervals(hours, day, at.toISOString().slice(0, 10))) all.push([day0 + d * 1440 + s, day0 + d * 1440 + e])\n }\n all.sort((a, b) => a[0] - b[0])\n const merged: Iv[] = []\n for (const iv of all) {\n const last = merged[merged.length - 1]\n if (last && iv[0] <= last[1]) last[1] = Math.max(last[1], iv[1])\n else merged.push([iv[0], iv[1]])\n }\n const current = merged.find(([s, e]) => s <= w && w < e)\n if (current) return { open: true, closesAt: toInstant(current[1]), nextOpenAt: null }\n const next = merged.find(([s]) => s > w)\n return { open: false, closesAt: null, nextOpenAt: next ? toInstant(next[0]) : null }\n}\n\ntype Run = { from: number; to: number; iv: Iv[] }\n\n/** Consecutive days (1..7) with identical intervals, in week order. */\nconst runs = (h: OpeningHours): Run[] => {\n const out: Run[] = []\n for (let day = 1; day <= 7; day++) {\n const iv = h.weekly.filter((x) => x.day === day).flatMap((x) => interval(x.open, x.close)).sort((a, b) => a[0] - b[0])\n if (!iv.length) continue\n const last = out[out.length - 1]\n if (last && last.to === day - 1 && JSON.stringify(last.iv) === JSON.stringify(iv)) last.to = day\n else out.push({ from: day, to: day, iv })\n }\n return out\n}\n\n/** Hour (24 for an end at midnight) and padded minutes of a minute-of-day value. */\nconst hm = (min: number): [number, string] => [min && min % 1440 === 0 ? 24 : Math.floor(min / 60) % 24, String(min % 60).padStart(2, '0')]\n\n/** Compact text, e.g. `Lun–Vie 9:00–19:00 · Sáb 9:00–14:00` (24 h) or `Mon–Fri 9:00 AM–7:00 PM` (en). */\nexport function formatOpeningHours(hours: OpeningHours, locale = 'es-MX'): string {\n const en = /^en/i.test(locale)\n const name = (d: number): string => {\n const s = new Intl.DateTimeFormat(locale, { weekday: 'short', timeZone: 'UTC' }).format(Date.UTC(2024, 0, d)).replace(/\\.$/, '')\n return s.charAt(0).toUpperCase() + s.slice(1)\n }\n const time = (min: number): string => {\n const [h, m] = hm(min)\n return en ? `${h % 12 || 12}:${m} ${h % 24 < 12 ? 'AM' : 'PM'}` : `${h}:${m}`\n }\n return runs(hours)\n .map((r) => `${name(r.from)}${r.from === r.to ? '' : '–' + name(r.to)} ${r.iv.map(([s, e]) => `${time(s)}–${time(e)}`).join(', ')}`)\n .join(' · ')\n}\n\n/** schema.org `openingHours` strings, one per interval, e.g. `Mo-Fr 09:00-19:00`. */\nexport function toSchemaOpeningHours(hours: OpeningHours): string[] {\n const code = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su']\n const t = (min: number): string => { const [h, m] = hm(min); return `${String(h).padStart(2, '0')}:${m}` }\n return runs(hours).flatMap((r) =>\n r.iv.map(([s, e]) => `${code[r.from - 1]}${r.from === r.to ? '' : '-' + code[r.to - 1]} ${t(s)}-${t(e)}`),\n )\n}\n","import type { Money } from './types.js'\n\nexport type FormatMoneyOptions = {\n /** Drop `.00` when the amount is a whole number. */\n withoutTrailingZeros?: boolean\n /** Format as a plain number, without the currency symbol. */\n withoutCurrency?: boolean\n /** `symbol` (default), `narrowSymbol`, `code` or `name`. */\n currencyDisplay?: 'symbol' | 'narrowSymbol' | 'code' | 'name'\n}\n\n/** Parses a contract `Money` amount into a JS number (`\"1899.00\"` → `1899`). */\nexport function parseMoney(money: Money | string | null | undefined): number {\n if (money == null) return 0\n const raw = typeof money === 'string' ? money : money.amount\n const n = Number.parseFloat(raw)\n return Number.isFinite(n) ? n : 0\n}\n\n/**\n * Formats `Money` with `Intl.NumberFormat`. Works in every runtime (no DOM).\n * Falls back to `\"<amount> <code>\"` when the runtime lacks the currency.\n */\nexport function formatMoney(money: Money, locale?: string, options: FormatMoneyOptions = {}): string {\n const value = parseMoney(money)\n const whole = Number.isInteger(value)\n const digits = options.withoutTrailingZeros && whole ? 0 : undefined\n try {\n const fmt = new Intl.NumberFormat(locale, {\n ...(options.withoutCurrency\n ? { style: 'decimal', minimumFractionDigits: digits ?? 2, maximumFractionDigits: digits ?? 2 }\n : {\n style: 'currency',\n currency: money.currency_code,\n currencyDisplay: options.currencyDisplay ?? 'symbol',\n ...(digits === 0 ? { minimumFractionDigits: 0, maximumFractionDigits: 0 } : {}),\n }),\n })\n return fmt.format(value)\n } catch {\n const amount = digits === 0 ? String(value) : value.toFixed(2)\n return options.withoutCurrency ? amount : `${amount} ${money.currency_code}`\n }\n}\n\n/** Builds a `Money` from a number, rounding to cents. */\nexport function toMoney(value: number, currencyCode: string): Money {\n return { amount: (Math.round(value * 100) / 100).toFixed(2), currency_code: currencyCode }\n}\n\n/**\n * True for public (`pk_`) tokens, the only ones that may reach a browser.\n * Private (`sk_`) tokens must stay on the server.\n */\nexport function isTokenPublishable(token: string | null | undefined): boolean {\n return typeof token === 'string' && token.startsWith('pk_')\n}\n","import type { ProductSort } from './types.js'\n\nexport type QueryValue = string | number | boolean | null | undefined\nexport type QueryParams = Record<string, QueryValue | QueryValue[]>\n\nexport type PaginationParams = {\n /** Page size (1–100; articles accept at most 50). */\n first?: number\n /** Cursor from `page_info.end_cursor`. */\n after?: string | null\n}\n\n/**\n * Cursor paging of the account lists (contract 1.19). `first` is 10 by default; a page has at most 50 (51–100 is cut to 50,\n * more is a 400). `after` goes to the next\n * (older) page with `page_info.end_cursor`; `before` goes back with `page_info.start_cursor`; never both.\n */\nexport type AccountListParams = {\n first?: number\n after?: string | null\n before?: string | null\n /** From this day (UTC, inclusive; `YYYY-MM-DD`) or an RFC 3339 instant. */\n from?: string\n /** Until this day (UTC, inclusive; `YYYY-MM-DD`) or an RFC 3339 instant (exclusive). */\n to?: string\n /** An exact order number (case-insensitive; a leading «#» is fine). */\n q?: string\n}\n\n/** Filters of `customer.orders.list` (derived ones are applied to bounded batches: a short page with `has_next_page` is valid). */\nexport type OrderListParams = AccountListParams & {\n /** An order status (`placed`, `accepted`, `fulfilling`, `ready`, `shipped`, `delivered`, `cancelled`) or progress stage (`pending_payment`, `paid`, `preparing`, `ready_for_pickup`, `in_transit`, `out_for_delivery`, `refunded`). */\n status?: string\n delivery_method?: 'shipping' | 'pickup'\n /** With an invoice (issued or on its way) or without one. */\n has_invoice?: boolean\n}\n\nexport type InvoiceListParams = AccountListParams & {\n /** `issued`, `pending`, `cancelled` or `error`. */\n status?: string\n}\n\nexport type ShipmentListParams = AccountListParams & {\n /** A parcel status: `pending`, `label_created`, `in_transit`, `out_for_delivery`, `delivered`, `exception`, `returned`, `lost`, `cancelled`. */\n status?: string\n}\n\nexport type ProductListParams = PaginationParams & {\n /** Free-text search. */\n q?: string\n /** Collection handle. */\n collection?: string\n sort?: ProductSort\n /** Only products available for sale. */\n available?: boolean\n price_min?: number | string\n price_max?: number | string\n /**\n * Attribute filters, serialized as repeated `filter.<key>=<value>` params.\n * Values of one key are OR-ed; different keys are AND-ed.\n * e.g. `{ vendor: ['A', 'B'], rim: 16 }`.\n */\n filters?: Record<string, QueryValue | QueryValue[]>\n /** Restrict to these handles (max 100). Serialized comma-separated. */\n handles?: string[]\n /**\n * Only products carrying at least one of these tags (OR, at most 5 of 120 characters; contract 1.9). Serialized\n * comma-separated. A parts store passes `fitTagsAny(fitKey)` (`fit:<key>`, `fit:universal`); any tag works.\n */\n tags_any?: string[]\n}\n\nexport type CollectionListParams = PaginationParams\n\nexport type ArticleListParams = Omit<PaginationParams, 'first'> & {\n /** Page size (1–50). The API answers 400 `validation` above 50. */\n first?: number\n tag?: string\n q?: string\n}\n\n/** The query of an account list: only what is set (no empty strings, no `undefined`), booleans as `true` / `false`. */\nexport function accountListQuery(params: (AccountListParams & Record<string, QueryValue | undefined>) | undefined): QueryParams | undefined {\n if (!params) return undefined\n const out: QueryParams = {}\n for (const [key, value] of Object.entries(params)) {\n if (value === undefined || value === null || value === '') continue\n out[key] = value\n }\n return out\n}\n\n/** Appends params to a URLSearchParams, repeating keys for arrays and skipping nullish values. */\nexport function appendParams(search: URLSearchParams, params: QueryParams | undefined): URLSearchParams {\n if (!params) return search\n for (const [key, raw] of Object.entries(params)) {\n const values = Array.isArray(raw) ? raw : [raw]\n for (const v of values) {\n if (v === undefined || v === null || v === '') continue\n search.append(key, String(v))\n }\n }\n return search\n}\n\n/** Serializes product list params per the contract (`filter.<attr>` repeated, `handles` comma-separated). */\nexport function productListQuery(params: ProductListParams = {}): URLSearchParams {\n const { filters, handles, tags_any, ...rest } = params\n const search = appendParams(new URLSearchParams(), rest as QueryParams)\n if (handles && handles.length > 0) search.set('handles', handles.join(','))\n if (tags_any && tags_any.length > 0) {\n if (tags_any.length > 5) throw new RangeError('tags_any takes at most 5 tags')\n // The API splits on commas: a tag that holds one would become two.\n if (tags_any.some((t) => t.includes(',') || t.length > 120)) throw new TypeError('tags_any: a tag has at most 120 characters and no comma')\n search.set('tags_any', tags_any.join(','))\n }\n if (filters) {\n for (const [key, raw] of Object.entries(filters)) {\n const name = key.startsWith('filter.') ? key : `filter.${key}`\n appendParams(search, { [name]: raw })\n }\n }\n return search\n}\n\n/** Reads `filter.<key>` params back into a filters record (useful in route loaders). */\nexport function parseProductFilters(search: URLSearchParams): Record<string, string[]> {\n const out: Record<string, string[]> = {}\n for (const [key, value] of search) {\n if (!key.startsWith('filter.')) continue\n const name = key.slice('filter.'.length)\n ;(out[name] ??= []).push(value)\n }\n return out\n}\n","import type { AccountDeleteInput, CustomerSessionInfo, DataExportFile, ReauthInput, ReauthResult } from './account-settings.js'\nimport { StorefrontError, defaultCodeForStatus } from './errors.js'\nimport { isValidPoint, type GeoPoint } from './geo.js'\nimport { isTokenPublishable } from './money.js'\nimport {\n accountListQuery,\n appendParams,\n productListQuery,\n type ArticleListParams,\n type CollectionListParams,\n type InvoiceListParams,\n type OrderListParams,\n type PaginationParams,\n type ShipmentListParams,\n type ProductListParams,\n type QueryParams,\n} from './query.js'\nimport type {\n InvoiceConnection,\n InvoiceListNode,\n OrderRef,\n ShipmentConnection,\n ShipmentListNode,\n Address,\n AddressInput,\n Article,\n Cart,\n CartBuyerInput,\n CartLineInput,\n CartLineUpdateInput,\n CartRecommendations,\n PaymentAttemptResult,\n PaymentConfig,\n PaymentSubmitInput,\n PromotionsList,\n RecommendationPlacement,\n CheckoutInput,\n CheckoutResult,\n Collection,\n Connection,\n Customer,\n CustomerIdentifier,\n CustomerCapabilities,\n CustomerUpdateInput,\n CustomerPasswordLoginInput,\n CustomerRegisterInput,\n CustomerRegisterResult,\n CustomerResetPasswordInput,\n CustomerSession,\n CustomerSessionInput,\n CustomerSetPasswordInput,\n CustomerEmailChangeConfirmInput,\n CustomerEmailChangeInput,\n CustomerEmailChangeRequested,\n CustomerEmailCodeInput,\n CustomerVerifyRegistrationInput,\n DeliveryInput,\n DeliveryOptions,\n PaymentMethods,\n FiscalProfile,\n FiscalProfileInput,\n InvoiceFile,\n InvoiceFileKind,\n InvoiceRequest,\n Location,\n LocationListParams,\n NearestLocation,\n InvoiceResult,\n Menu,\n Order,\n Page,\n PendingPayment,\n Product,\n ProductConnection,\n Region,\n RegionPostalCode,\n AddressSuggestions,\n ReturnRequest,\n ReturnRequestInput,\n Shop,\n RestockSubscriptionInput,\n RestockSubscriptionResult,\n StockLevel,\n StorefrontErrorBody,\n Subject,\n SubjectInput,\n SubjectKind,\n SubjectPatch,\n Theme,\n TokenIntrospection,\n} from './types.js'\n\nexport type FetchLike = (input: string | URL | Request, init?: RequestInit) => Promise<Response>\n\n/** Context passed to `onRequest` / `onResponse` hooks. */\nexport type StorefrontRequestContext = {\n method: string\n /** Absolute URL, including the query string. */\n url: string\n /** Route path relative to `baseUrl`, e.g. `/storefront/products/abc`. */\n path: string\n /** Final `RequestInit` (headers already merged). Hooks may mutate it. */\n init: RequestInit & { headers: Headers }\n /** Per-call options as given by the caller. */\n options: RequestOptions\n}\n\nexport type StorefrontResponseContext = StorefrontRequestContext & {\n response: Response\n /** Milliseconds spent waiting for the response. */\n durationMs: number\n}\n\nexport type StorefrontClientOptions = {\n /** Base URL of the gateway, e.g. `https://ops.example.com/api/gw`. Routes are appended as `/storefront/...`. */\n baseUrl: string\n /**\n * `pk_...` (browser) or `sk_...` (server only). Sent as `Authorization: Bearer <token>`. A function is called on\n * EVERY request, so a token read from a file (`createFileTokenSource` in `@asteby/storefront/node`) can rotate\n * without restarting the server.\n */\n token: string | (() => string)\n /** Buyer session (`X-Customer-Token`) for `/storefront/customer/*` routes. */\n customerToken?: string | null\n /** Custom fetch (defaults to `globalThis.fetch`). */\n fetch?: FetchLike\n /** Sent as `Accept-Language`. */\n locale?: string\n /**\n * Public host of the storefront (`godsnutrition.com`), sent as `X-Storefront-Domain`. Platform (`pt_`)\n * tokens need it to pick the organization; with an org-scoped token it only scopes the market.\n */\n domain?: string\n /**\n * Market the request is for (`mx`, `us`), sent as `<domain>#<market>` in `X-Storefront-Domain`. It lets ONE\n * public domain serve several markets (the storefront routes by path prefix, e.g. `/us`): OPS honors it\n * when the organization has that market active and otherwise falls back to the domain's own market.\n * Ignored without `domain`.\n */\n market?: string\n /** Extra headers on every request. */\n headers?: Record<string, string>\n /**\n * IP address of the shopper, for SERVER-side calls (SSR, route actions) made with an\n * `sk_`/`pt_` token. Sent as `X-Storefront-Client-IP`, which the gateway honors only for\n * tokens issued with the `trust_client_ip` option: the rate limit is then charged per\n * shopper instead of to the store's single token bucket, and the OTP flow limits the\n * shopper's IP instead of the server's. Pass the IP from your own connection or trusted\n * proxy, never from a header the browser can forge. Never sent with a `pk_` token (the\n * gateway already separates those by caller IP). Invalid values are dropped.\n */\n clientIp?: string | null\n /** Abort requests that take longer than this (default: no timeout). */\n timeoutMs?: number\n /**\n * Runs before every request. Return a `Response` to short-circuit the\n * network (e.g. an SSR cache hit); return nothing to continue.\n */\n onRequest?: (ctx: StorefrontRequestContext) => void | Response | Promise<void | Response>\n /** Runs after every response (including short-circuited ones), before parsing. */\n onResponse?: (ctx: StorefrontResponseContext) => void | Promise<void>\n}\n\n/** Per-call options. Unknown keys (e.g. Next.js `next`) are forwarded to `fetch` as-is. */\n/** Query of `client.addressSuggest`. */\nexport type AddressSuggestParams = {\n /** What the shopper typed so far (at least 3 characters). */\n q: string\n /** ISO 3166-1 alpha-2 of the address: candidates of another country are dropped. */\n country?: string\n /** Postal code already chosen: candidates of another code or state are dropped. */\n zip?: string\n /** 1 to 8 (server default 5). */\n limit?: number\n /** Bias point (with `lng`): ranks nearby first, never filters. */\n lat?: number\n lng?: number\n /** Language of the labels (`es`, `en`). Default: `Accept-Language`. */\n locale?: string\n}\n\nexport type RequestOptions = {\n cache?: RequestCache\n signal?: AbortSignal\n /** Framework fetch extensions, forwarded verbatim (e.g. `{ revalidate: 60, tags: ['products'] }`). */\n next?: Record<string, unknown>\n headers?: Record<string, string>\n /** Overrides the client-level timeout for this call. */\n timeoutMs?: number\n /** Overrides the client-level customer token for this call. */\n customerToken?: string | null\n /** Overrides the client-level shopper IP for this call (see `StorefrontClientOptions.clientIp`). */\n clientIp?: string | null\n [key: string]: unknown\n}\n\nexport type WriteOptions = RequestOptions & {\n /** `Idempotency-Key` header. Auto-generated for checkout when omitted. */\n idempotencyKey?: string\n}\n\nexport type PreviewOptions = RequestOptions & {\n /** Signed preview token: returns the draft (`private, no-store`). */\n preview?: string\n}\n\ntype HttpMethod = 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE'\n\ntype RequestSpec = {\n method: HttpMethod\n path: string\n query?: URLSearchParams | QueryParams\n body?: unknown\n options?: WriteOptions\n /** Resolve `null` instead of throwing on 404. */\n nullOn404?: boolean\n /**\n * Never follow a redirect (`redirect: 'error'`, and a redirected answer is refused): for answers that carry the\n * buyer's documents, so neither the customer token nor the request ever travels to another host.\n */\n noRedirect?: boolean\n}\n\nconst OWN_OPTION_KEYS = new Set(['headers', 'timeoutMs', 'customerToken', 'clientIp', 'idempotencyKey', 'preview', 'signal'])\n\n/** Header the gateway reads (only for tokens with `trust_client_ip`). */\nexport const CLIENT_IP_HEADER = 'X-Storefront-Client-IP'\n\n/**\n * Returns the single IP literal in `raw`, or undefined. Takes the form a server hands over\n * (`::ffff:1.2.3.4`, `[2001:db8::1]`) and rejects lists, ports, zones and text so the\n * header is never a forgery vector.\n */\nexport function normalizeClientIp(raw: string | null | undefined): string | undefined {\n if (!raw) return undefined\n let v = raw.trim()\n if (v.startsWith('[') && v.endsWith(']')) v = v.slice(1, -1)\n if (!v || v.length > 45 || /[\\s,%/]/.test(v)) return undefined\n if (/^[0-9]{1,3}(\\.[0-9]{1,3}){3}$/.test(v)) {\n return v.split('.').every((o) => Number(o) <= 255) ? v : undefined\n }\n // IPv6 (incl. IPv4-mapped): hex groups and colons, at most one \"::\".\n if (!v.includes(':') || !/^[0-9a-fA-F:.]+$/.test(v) || v.split('::').length > 2) return undefined\n try {\n new URL(`http://[${v}]/`)\n } catch {\n return undefined\n }\n return v\n}\n\n/** Generates an idempotency key (crypto.randomUUID when available). */\nexport function generateIdempotencyKey(): string {\n const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto\n if (c?.randomUUID) return c.randomUUID()\n // Non-cryptographic fallback for very old runtimes; the key only needs to be unique.\n return 'idem-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2) + Math.random().toString(36).slice(2)\n}\n\nfunction joinUrl(baseUrl: string, path: string): string {\n return baseUrl.replace(/\\/+$/, '') + path\n}\n\nfunction enc(segment: string): string {\n // `.` and `..` (also as `%2e`) are dot segments: the URL parser would resolve them and the request would land on\n // another route with the same credentials.\n if (typeof segment !== 'string' || /^(?:\\.|%2e){1,2}$/i.test(segment)) throw new TypeError(`Invalid path segment: ${String(segment)}`)\n return encodeURIComponent(segment)\n}\n\nfunction linkSignals(signals: (AbortSignal | undefined)[]): { signal: AbortSignal | undefined; cleanup: () => void } {\n const active = signals.filter((s): s is AbortSignal => !!s)\n if (active.length === 0) return { signal: undefined, cleanup: () => {} }\n if (active.length === 1) return { signal: active[0], cleanup: () => {} }\n const controller = new AbortController()\n const listeners: [AbortSignal, () => void][] = []\n for (const s of active) {\n if (s.aborted) {\n controller.abort(s.reason)\n break\n }\n const on = () => controller.abort(s.reason)\n s.addEventListener('abort', on, { once: true })\n listeners.push([s, on])\n }\n return {\n signal: controller.signal,\n cleanup: () => listeners.forEach(([s, on]) => s.removeEventListener('abort', on)),\n }\n}\n\nfunction scopeList(raw: unknown): string[] {\n return Array.isArray(raw) ? raw.filter((s): s is string => typeof s === 'string' && s.length > 0) : []\n}\n\nasync function readError(res: Response, url: string): Promise<StorefrontError> {\n let body: Partial<StorefrontErrorBody> | undefined\n try {\n const text = await res.text()\n body = text ? (JSON.parse(text) as Partial<StorefrontErrorBody>) : undefined\n } catch {\n body = undefined\n }\n const e = body?.error\n // The gateway may put `code` / `required_scopes` at the top level or inside `error` (or its `details`).\n const top = body as { code?: unknown; required_scopes?: unknown } | undefined\n const code = e?.code ?? (typeof top?.code === 'string' ? top.code : undefined)\n const requiredScopes = code === 'insufficient_scope' ? scopeList(e?.required_scopes ?? top?.required_scopes ?? (e?.details as { required_scopes?: unknown } | undefined)?.required_scopes) : []\n return new StorefrontError({\n status: res.status,\n code: code ?? defaultCodeForStatus(res.status),\n ...(requiredScopes.length ? { requiredScopes } : {}),\n message: e?.message ?? `Storefront API responded ${res.status}${res.statusText ? ' ' + res.statusText : ''}`,\n ...(e?.field ? { field: e.field } : {}),\n ...(e?.details !== undefined ? { details: e.details } : {}),\n ...(typeof e?.retryable === 'boolean' ? { retryable: e.retryable } : {}),\n ...(typeof e?.retry_after === 'number' && e.retry_after > 0 ? { retryAfter: e.retry_after } : {}),\n ...(typeof e?.checkout_id === 'string' && e.checkout_id ? { checkoutId: e.checkout_id } : {}),\n ...(e?.cost !== undefined ? { cost: e.cost } : {}),\n ...(typeof e?.message_en === 'string' && e.message_en ? { messageEn: e.message_en } : {}),\n url,\n })\n}\n\nexport function createStorefrontClient(config: StorefrontClientOptions) {\n if (!config.baseUrl) throw new TypeError('createStorefrontClient: baseUrl is required')\n if (!config.token) throw new TypeError('createStorefrontClient: token is required')\n const currentToken = (): string => {\n const t = typeof config.token === 'function' ? config.token() : config.token\n if (!t) throw new StorefrontError({ status: 0, code: 'unauthorized', message: 'Storefront token is empty (token source returned nothing)' })\n return t\n }\n const isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined'\n const initialToken = typeof config.token === 'string' ? config.token : ''\n if (isBrowser && initialToken.startsWith('sk_')) {\n console.warn('[@asteby/storefront] A private sk_ token is being used in a browser. Use a public pk_ token instead.')\n }\n\n async function request<T>(spec: RequestSpec & { nullOn404: true }): Promise<T | null>\n async function request<T>(spec: RequestSpec): Promise<T>\n async function request<T>(spec: RequestSpec): Promise<T | null> {\n const fetchImpl: FetchLike | undefined = config.fetch ?? (globalThis.fetch ? globalThis.fetch.bind(globalThis) : undefined)\n if (!fetchImpl) throw new TypeError('createStorefrontClient: no fetch available; pass `fetch` in options')\n\n const options: WriteOptions = spec.options ?? {}\n const search = spec.query instanceof URLSearchParams ? spec.query : appendParams(new URLSearchParams(), spec.query)\n const qs = search.toString()\n const url = joinUrl(config.baseUrl, spec.path) + (qs ? `?${qs}` : '')\n\n const headers = new Headers(config.headers)\n headers.set('Accept', 'application/json')\n const token = currentToken()\n headers.set('Authorization', `Bearer ${token}`)\n if (config.locale) headers.set('Accept-Language', config.locale)\n if (config.domain) headers.set('X-Storefront-Domain', storefrontDomainHeader(config.domain, config.market))\n const customerToken = options.customerToken !== undefined ? options.customerToken : config.customerToken\n if (customerToken) headers.set('X-Customer-Token', customerToken)\n const clientIp = options.clientIp !== undefined ? options.clientIp : config.clientIp\n // Server-side tokens only: a pk_ token already gets a per-caller bucket from the gateway.\n const ip = isTokenPublishable(token) ? undefined : normalizeClientIp(clientIp)\n if (ip) headers.set(CLIENT_IP_HEADER, ip)\n if (options.idempotencyKey) headers.set('Idempotency-Key', options.idempotencyKey)\n if (spec.body !== undefined) headers.set('Content-Type', 'application/json')\n for (const [k, v] of Object.entries(options.headers ?? {})) headers.set(k, v)\n\n // Forward passthrough options (cache, next, ...) to fetch.\n const passthrough: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(options)) if (!OWN_OPTION_KEYS.has(k) && v !== undefined) passthrough[k] = v\n\n const timeoutMs = options.timeoutMs ?? config.timeoutMs\n const timeoutController = timeoutMs && timeoutMs > 0 ? new AbortController() : undefined\n const timer = timeoutController\n ? setTimeout(() => timeoutController.abort(new StorefrontError({ status: 0, code: 'timeout', message: `Request timed out after ${timeoutMs}ms`, url })), timeoutMs)\n : undefined\n const linked = linkSignals([options.signal, timeoutController?.signal])\n\n const init: RequestInit & { headers: Headers } = {\n ...passthrough,\n ...(spec.noRedirect ? { redirect: 'error' as const } : {}),\n method: spec.method,\n headers,\n ...(spec.body !== undefined ? { body: JSON.stringify(spec.body) } : {}),\n ...(linked.signal ? { signal: linked.signal } : {}),\n }\n const ctx: StorefrontRequestContext = { method: spec.method, url, path: spec.path, init, options }\n\n const started = Date.now()\n let res: Response\n try {\n const hooked = config.onRequest ? await config.onRequest(ctx) : undefined\n res = hooked instanceof Response ? hooked : await fetchImpl(url, init)\n } catch (err) {\n if (timeoutController?.signal.aborted) {\n throw new StorefrontError({ status: 0, code: 'timeout', message: `Request timed out after ${timeoutMs}ms`, url, cause: err })\n }\n if (options.signal?.aborted) {\n throw new StorefrontError({ status: 0, code: 'aborted', message: 'Request aborted', url, cause: err })\n }\n if (err instanceof StorefrontError) throw err\n throw new StorefrontError({ status: 0, code: 'network', message: err instanceof Error ? err.message : 'Network error', url, cause: err })\n } finally {\n if (timer) clearTimeout(timer)\n linked.cleanup()\n }\n\n if (config.onResponse) await config.onResponse({ ...ctx, response: res, durationMs: Date.now() - started })\n\n if (spec.noRedirect && res.redirected) {\n await res.text().catch(() => undefined)\n throw new StorefrontError({ status: 502, code: 'invalid_response', message: 'The answer was redirected; it is refused', url })\n }\n\n if (res.status === 404 && spec.nullOn404) {\n // Drain the body so the connection can be reused.\n await res.text().catch(() => undefined)\n return null\n }\n if (res.status === 304) {\n throw new StorefrontError({ status: 304, code: 'not_modified', message: 'Not modified', url })\n }\n if (!res.ok) throw await readError(res, url)\n if (res.status === 204) return undefined as T\n\n const text = await res.text()\n if (!text) return undefined as T\n try {\n return JSON.parse(text) as T\n } catch (err) {\n throw new StorefrontError({ status: res.status, code: 'invalid_response', message: 'Response is not valid JSON', url, cause: err })\n }\n }\n\n const get = <T>(path: string, query?: URLSearchParams | QueryParams, options?: RequestOptions) =>\n request<T>({ method: 'GET', path, ...(query ? { query } : {}), ...(options ? { options } : {}) })\n const getOrNull = <T>(path: string, query?: URLSearchParams | QueryParams, options?: RequestOptions) =>\n request<T>({ method: 'GET', path, nullOn404: true, ...(query ? { query } : {}), ...(options ? { options } : {}) })\n const write = <T>(method: HttpMethod, path: string, body?: unknown, options?: WriteOptions) =>\n request<T>({ method, path, ...(body !== undefined ? { body } : {}), ...(options ? { options } : {}) })\n\n const cartPath = (id: string, rest = '') => `/storefront/carts/${enc(id)}${rest}`\n const previewQuery = (options?: PreviewOptions) => (options?.preview ? { preview: options.preview } : undefined)\n\n const client = {\n /** Resolved configuration (read-only). */\n config: Object.freeze({ ...config }) as Readonly<StorefrontClientOptions>,\n\n /** Low-level escape hatch: any route under `baseUrl`. */\n request,\n\n token: {\n /**\n * What the token in use is and can do (`GET {baseUrl}/_token`, a gateway route, not a `/storefront` one).\n * Needs no scope, so it answers even when the token is under-provisioned: `missing_scopes` says what to repair.\n */\n introspect: async (options?: RequestOptions): Promise<TokenIntrospection> => {\n // OPS answers with the kernel envelope `{success, data}`; a flat object is accepted too.\n const body = await get<TokenIntrospection | { success?: boolean; data?: TokenIntrospection }>('/_token', undefined, options)\n const env = body as { success?: unknown; data?: TokenIntrospection }\n return typeof env?.success === 'boolean' && env.data ? env.data : (body as TokenIntrospection)\n },\n },\n\n /** Returns a new client that sends the given buyer session token. */\n withCustomerToken(customerToken: string | null) {\n return createStorefrontClient({ ...config, customerToken })\n },\n\n /** Returns a new client that reports the shopper's IP (`X-Storefront-Client-IP`) on every call. */\n withClientIp(clientIp: string | null | undefined) {\n return createStorefrontClient({ ...config, clientIp: clientIp ?? null })\n },\n\n shop: {\n get: (options?: RequestOptions) => get<Shop>('/storefront/shop', undefined, options),\n },\n\n /**\n * How the market formats, taxes, addresses and invoices (`fiscal_id` carries the tax-id pattern, the regimes,\n * the invoice uses and the identity documents the buyer can upload). Cacheable; `null` when the organization\n * has no region configured.\n */\n region: (options?: RequestOptions) => getOrNull<Region>('/storefront/region', undefined, options),\n\n /**\n * State and municipality of a postal code from the region pack (`null` when the code is not in its catalog, or the\n * organization has no region pack). The source of `AddressFields.lookupPostalCode`: the state it fills is the one\n * the server checks the address against.\n */\n postalCode: (zip: string, options?: RequestOptions) => getOrNull<RegionPostalCode>('/storefront/region/postal-code', { zip: zip.trim() }, options),\n\n /**\n * Street and number suggestions for the address form (`GET /storefront/address/suggest`), from the geocoding\n * provider the market is assigned (a self-hosted Photon, ...). The server drops candidates of another country, postal\n * code or state than the catalog's, and answers `{ suggestions: [], available: false }` when there is no provider:\n * it never fails because of one. `q` needs at least 3 characters (the call rejects shorter ones without a request).\n * Browser forms call it through `AddressFields.suggestAddress`; do not call it per keystroke without a debounce.\n */\n addressSuggest: (params: AddressSuggestParams, options?: RequestOptions) => {\n const q = params.q.trim().replace(/\\s+/g, ' ')\n if ([...q].length < 3) return Promise.reject(new RangeError('addressSuggest: q needs at least 3 characters'))\n return get<AddressSuggestions>(\n '/storefront/address/suggest',\n { q, country: params.country?.toUpperCase(), zip: params.zip?.trim(), limit: params.limit, lat: params.lat, lng: params.lng, locale: params.locale },\n options,\n )\n },\n\n products: {\n list: (params?: ProductListParams, options?: RequestOptions) =>\n get<ProductConnection>('/storefront/products', productListQuery(params), options),\n /** `null` when the product does not exist or is unpublished. */\n get: (handle: string, options?: RequestOptions) =>\n getOrNull<Product>(`/storefront/products/${enc(handle)}`, undefined, options),\n recommendations: (handle: string, options?: RequestOptions) =>\n get<{ nodes: Product[] }>(`/storefront/products/${enc(handle)}/recommendations`, undefined, options),\n },\n\n collections: {\n list: (params?: CollectionListParams, options?: RequestOptions) =>\n get<Connection<Collection>>('/storefront/collections', params as QueryParams, options),\n /** `null` when the collection does not exist. */\n get: (handle: string, options?: RequestOptions) =>\n getOrNull<Collection>(`/storefront/collections/${enc(handle)}`, undefined, options),\n },\n\n locations: {\n /** Branches of the shop. With `postal_code` they come ordered by distance (`distance_km`). */\n list: (params?: LocationListParams, options?: RequestOptions) =>\n get<{ nodes: Location[] }>('/storefront/locations', params as QueryParams, options),\n /** `null` when the branch does not exist or is not visible. */\n get: (id: string, options?: RequestOptions) =>\n getOrNull<Location>(`/storefront/locations/${enc(id)}`, undefined, options),\n /**\n * Branches ordered by distance to a point, closest first. The server rounds the coordinates (0.01°, ~1 km)\n * and never stores them; this client does not log or keep them either. The answer is `private, no-store`\n * (it depends on the buyer's position), so do not put it in a shared cache. Note `onRequest` hooks and\n * `fetch` wrappers do see the URL: do not log it. Throws `TypeError` for an invalid point.\n */\n nearest: (point: GeoPoint, options?: RequestOptions) => {\n if (!isValidPoint(point)) throw new TypeError('locations.nearest: lat/lng must be a valid point')\n return get<{ nodes: NearestLocation[] }>('/storefront/locations/nearest', { lat: point.lat, lng: point.lng }, { cache: 'no-store', ...options })\n },\n },\n\n stock: {\n /** Stock for up to 250 SKUs. */\n get: (skus: string[], options?: RequestOptions) =>\n get<{ nodes: StockLevel[] }>('/storefront/stock', { sku: skus }, options),\n },\n\n restock: {\n /**\n * \"Notify me when it is back\". Idempotent per contact + SKU; always answers `202 pending`.\n * Only offered when `availability.notify_available` is true. Needs `customer:write`.\n */\n subscribe: (input: RestockSubscriptionInput, options?: WriteOptions) =>\n write<RestockSubscriptionResult>('POST', '/storefront/restock-subscriptions', input, options),\n },\n\n carts: {\n create: (input: { lines?: CartLineInput[] } = {}, options?: WriteOptions) =>\n write<Cart>('POST', '/storefront/carts', input, options),\n /** `null` when the cart does not exist (e.g. expired cookie). */\n get: (id: string, options?: RequestOptions) => getOrNull<Cart>(cartPath(id), undefined, options),\n addLines: (id: string, lines: CartLineInput[], options?: WriteOptions) =>\n write<Cart>('POST', cartPath(id, '/lines'), { lines }, options),\n /** Quantity `0` removes the line. */\n updateLines: (id: string, lines: CartLineUpdateInput[], options?: WriteOptions) =>\n write<Cart>('PATCH', cartPath(id, '/lines'), { lines }, options),\n removeLines: (id: string, lineIds: string[], options?: WriteOptions) =>\n write<Cart>('PATCH', cartPath(id, '/lines'), { lines: lineIds.map((lid) => ({ id: lid, quantity: 0 })) }, options),\n setDiscountCodes: (id: string, codes: string[], options?: WriteOptions) =>\n write<Cart>('PUT', cartPath(id, '/discount-codes'), { codes }, options),\n setBuyer: (id: string, buyer: CartBuyerInput, options?: WriteOptions) =>\n write<Cart>('PUT', cartPath(id, '/buyer'), buyer, options),\n setShippingAddress: (id: string, address: AddressInput, options?: WriteOptions) =>\n write<Cart>('PUT', cartPath(id, '/shipping-address'), address, options),\n deliveryOptions: (id: string, options?: RequestOptions) =>\n get<DeliveryOptions>(cartPath(id, '/delivery-options'), undefined, options),\n /** Payment providers active for the cart's market; send the chosen `key` as `payment_method`. */\n paymentMethods: (id: string, options?: RequestOptions) =>\n get<PaymentMethods>(cartPath(id, '/payment-methods'), undefined, options),\n setDelivery: (id: string, delivery: DeliveryInput, options?: WriteOptions) =>\n write<Cart>('PUT', cartPath(id, '/delivery'), delivery, options),\n /** Order note (up to 1000 characters). `null` or empty clears it. */\n setNote: (id: string, note: string | null, options?: WriteOptions) =>\n write<Cart>('PUT', cartPath(id, '/note'), { note }, options),\n /**\n * Asks for an invoice for this cart (`null` or `{ requested: false }` withdraws it). The server validates the\n * data against the region BEFORE any charge: `422` with `field: 'invoice.<field>'` (e.g. `invoice.tax_regime`)\n * names what to fix. `409 already_checked_out` when the cart is already an order. Checkout uses it when\n * `CheckoutInput.invoice` is omitted.\n */\n setInvoice: (id: string, invoice: InvoiceRequest | null, options?: WriteOptions) =>\n write<Cart>('PUT', cartPath(id, '/invoice'), invoice ?? { requested: false }, options),\n /**\n * Cross-sell suggestions: only sellable variants, with `unlocks` when adding one reaches the next\n * discount tier. `first` 1-8 (default 4). `private, no-store`; ask on demand, not on every render.\n */\n recommendations: (id: string, params: { first?: number; placement?: RecommendationPlacement } = {}, options?: RequestOptions) =>\n get<CartRecommendations>(cartPath(id, '/recommendations'), params as QueryParams, options),\n /** Reserves stock and creates the order. Sends `Idempotency-Key` (auto-generated if omitted). */\n checkout: (id: string, input: CheckoutInput, options: WriteOptions = {}) =>\n write<CheckoutResult>('POST', cartPath(id, '/checkout'), input, {\n ...options,\n idempotencyKey: options.idempotencyKey ?? generateIdempotencyKey(),\n }),\n },\n\n promotions: {\n /** Public promotions and the entry pop-up announcement for the request's market (cacheable). */\n list: (options?: RequestOptions) => get<PromotionsList>('/storefront/promotions', undefined, options),\n },\n\n checkouts: {\n /** What to mount for an embedded checkout (public key, options, amount) and whether it can still be paid. Never cache. */\n paymentConfig: (id: string, options?: RequestOptions) =>\n getOrNull<PaymentConfig>(`/storefront/checkouts/${enc(id)}/payment-config`, undefined, options),\n /**\n * Pays a checkout in the page. The browser brings only what the provider SDK returned (`provider_data`);\n * the amount is the server's. `idempotencyKey` is REQUIRED (use `paymentIdempotencyKey(checkoutId, attempt)`):\n * repeating a call with the same key never charges twice. Needs a server token (`checkout:write`).\n */\n pay: (id: string, input: PaymentSubmitInput, options: WriteOptions & { idempotencyKey: string }) => {\n if (!options || typeof options.idempotencyKey !== 'string' || !options.idempotencyKey.trim()) {\n throw new TypeError('checkouts.pay: idempotencyKey is required')\n }\n return write<PaymentAttemptResult>('POST', `/storefront/checkouts/${enc(id)}/payment`, input, options)\n },\n /**\n * Reads a placed checkout (same shape as the `carts.checkout` result). `order.number` is `null` until OPS\n * has created the order (a few hundred ms after checkout); poll once or twice and, if it is still `null`,\n * keep telling the buyer the number will arrive by email. Needs a server token (`checkout:write`).\n * `null` when the checkout does not exist. Never cache.\n */\n get: (id: string, options?: RequestOptions) =>\n getOrNull<CheckoutResult>(`/storefront/checkouts/${enc(id)}`, undefined, options),\n },\n\n customer: {\n /** Sends a one-time code by email or SMS/WhatsApp. */\n requestOtp: (identifier: CustomerIdentifier, options?: WriteOptions) =>\n write<void>('POST', '/storefront/customer/otp', identifier, options),\n /** Exchanges the code for a buyer session (`token` goes in `customerToken`). */\n createSession: (input: CustomerSessionInput, options?: WriteOptions) =>\n write<CustomerSession>('POST', '/storefront/customer/session', input, options),\n /** What the store supports (password login, email verification, OTP channels). Drives which forms to show. */\n capabilities: (options?: RequestOptions) =>\n get<CustomerCapabilities>('/storefront/customer/capabilities', undefined, options),\n /**\n * Creates an account with email + password. `verification_required` (202): a code was emailed, finish with\n * `verifyRegistration`. `created` (201): the account exists and `session` is ready. `409` when the email is taken.\n */\n register: async (input: CustomerRegisterInput, options?: WriteOptions): Promise<CustomerRegisterResult> => {\n const res = await write<{ status: 'verification_required' } | CustomerSession>('POST', '/storefront/customer/register', input, options)\n return res && 'token' in res ? { status: 'created', session: res } : { status: 'verification_required' }\n },\n /** Confirms the emailed registration code and returns the new buyer session. */\n verifyRegistration: (input: CustomerVerifyRegistrationInput, options?: WriteOptions) =>\n write<CustomerSession>('POST', '/storefront/customer/register/verify', input, options),\n /** Email + password login. `401` for wrong credentials. */\n loginWithPassword: (input: CustomerPasswordLoginInput, options?: WriteOptions) =>\n write<CustomerSession>('POST', '/storefront/customer/login', input, options),\n /** Sets or changes the password of the signed-in buyer (`options.customerToken`, or a `withCustomerToken` client). */\n setPassword: (input: CustomerSetPasswordInput, options?: WriteOptions) =>\n write<void>('PUT', '/storefront/customer/password', input, options),\n /** Resets a forgotten password with the code from `requestOtp({ email })`. */\n resetPassword: (input: CustomerResetPasswordInput, options?: WriteOptions) =>\n write<void>('POST', '/storefront/customer/password/reset', input, options),\n get: (options?: RequestOptions) => get<Customer>('/storefront/customer', undefined, options),\n /** Updates the profile and the saved fiscal data; `fiscal: null` deletes the latter. `422` with `field: 'fiscal.<field>'`. */\n update: (input: CustomerUpdateInput, options?: WriteOptions) =>\n write<Customer>('PATCH', '/storefront/customer', input, options),\n /**\n * Active sessions of the buyer («Devices»; contract 1.9). Private, never cached. The list carries no address\n * and no token: only what the buyer needs to recognize their own devices.\n */\n sessions: {\n list: async (options?: RequestOptions): Promise<CustomerSessionInfo[]> =>\n (await get<{ nodes: CustomerSessionInfo[] }>('/storefront/customer/sessions', undefined, { ...options, cache: 'no-store' })).nodes,\n /** Closes one session. Repeating it is fine. `404` for a session that is not the buyer's. Closing the current one is a sign-out. */\n revoke: (id: string, options?: WriteOptions) =>\n write<void>('DELETE', `/storefront/customer/sessions/${enc(id)}`, undefined, options),\n /** Closes every session except the one making the call. */\n revokeOthers: (options?: WriteOptions) => write<void>('DELETE', '/storefront/customer/sessions/others', undefined, options),\n },\n /**\n * Confirms the buyer's identity again with their password or a sign-in code (`requestOtp` first). The\n * confirmation lasts `valid_for_seconds` (a few minutes) and counts only for the session that made the call;\n * exporting data and deleting the account need it (`403 reauth_required` otherwise, see `isReauthRequired`).\n * A wrong credential is always the same `400`; too many tries is `429` (`StorefrontError.retryAfter`).\n */\n reauth: (input: ReauthInput, options?: WriteOptions) =>\n write<ReauthResult>('POST', '/storefront/customer/reauth', input, options),\n /**\n * The buyer's e-mail from their account (contract 1.15, `capabilities().email_change`). All four calls need the\n * buyer's session; a wrong or expired code is always the same `400` on `code`, too many tries is `429`.\n */\n email: {\n /**\n * Mails a code to the account's CURRENT e-mail so it can be verified. `422` when it is already verified, the\n * account has no e-mail or the store cannot send mail; `429` while a code was just sent.\n */\n requestVerification: (options?: WriteOptions) => write<void>('POST', '/storefront/customer/email/verification', undefined, options),\n /** Verifies the current e-mail with the code; answers the buyer with `email_verified: true`. */\n confirmVerification: (input: CustomerEmailCodeInput, options?: WriteOptions) =>\n write<Customer>('POST', '/storefront/customer/email/verification/confirm', input, options),\n /**\n * Asks to change the e-mail. Needs a recent `reauth` (`403 reauth_required`, see `isReauthRequired`). A code is\n * sent to the NEW address and nothing changes until `confirmChange`. The answer is the same whether or not the\n * new address already has an account (then nothing is sent and the code can never work): word your screen as\n * «if the address can be used, we sent a code». `400` on `email` for an invalid or unchanged address.\n */\n requestChange: (input: CustomerEmailChangeInput, options?: WriteOptions) =>\n write<CustomerEmailChangeRequested>('POST', '/storefront/customer/email/change', input, options),\n /**\n * Confirms the change with the code that arrived at the new address. The other sessions of the account are\n * closed (the one making the call stays) and the answer is the buyer with the new, verified e-mail.\n */\n confirmChange: (input: CustomerEmailChangeConfirmInput, options?: WriteOptions) =>\n write<Customer>('POST', '/storefront/customer/email/change/confirm', input, options),\n },\n /**\n * The buyer's data as a JSON file (contract 1.9, `capabilities().data_export`). Needs a recent `reauth`. It is\n * built on request and is neither stored nor emailed: call it from YOUR server, stream the bytes\n * (`dataExportBytes`, `safeExportFilename`) with `Cache-Control: no-store`, and keep nothing. Three a day per account.\n */\n exportData: async (options?: WriteOptions): Promise<DataExportFile> => {\n const file = await write<DataExportFile>('POST', '/storefront/customer/data-export', undefined, { ...options, cache: 'no-store' })\n if (!file || typeof file.content_base64 !== 'string' || typeof file.filename !== 'string' || typeof file.content_type !== 'string') {\n throw new StorefrontError({ status: 502, code: 'invalid_response', message: 'The data export answer is not a file' })\n }\n return { filename: file.filename, content_type: file.content_type, content_base64: file.content_base64 }\n },\n /**\n * Deletes the buyer's account (contract 1.9, `capabilities().account_delete`). Needs a recent `reauth` and the\n * text the buyer typed in `confirm`. Personal data is erased; orders and invoices are kept by the store.\n * `409` (see `isAccountDeleteBlocked`) while an order is on its way or a payment is pending. Idempotent: a\n * repeat after success is also fine. Afterwards the token is dead: drop it.\n */\n deleteAccount: (input: AccountDeleteInput, options?: WriteOptions) =>\n write<void>('DELETE', '/storefront/customer', input, options),\n /**\n * The buyer's orders, newest first. Callable as before (`orders({ first })`) and, since contract 1.19, with\n * `orders.list({ first, after, before, status, delivery_method, has_invoice, from, to, q })`: cursor paging\n * (keyset, stable while new orders arrive), `page_info.start_cursor` / `has_previous_page` to go back, and\n * `total_count` when it is cheap to know. An OPS older than 1.19 ignores the new parameters.\n */\n orders: Object.assign(\n (params?: PaginationParams, options?: RequestOptions) => get<Connection<Order>>('/storefront/customer/orders', params as QueryParams, options),\n {\n list: (params?: OrderListParams, options?: RequestOptions) =>\n get<Connection<Order>>('/storefront/customer/orders', accountListQuery(params), { ...options, cache: 'no-store' }),\n },\n ),\n /**\n * The buyer's invoices, one node per order that has them (`{ order, invoices }`), cursor-paged like `orders.list`.\n * It replaces opening the detail of every order. An OPS older than 1.19 (no such route) is served from one page of\n * orders and their details, so the account keeps working until the addon is updated.\n */\n invoices: {\n list: async (params?: InvoiceListParams, options?: RequestOptions): Promise<InvoiceConnection> => {\n const page = await getOrNull<InvoiceConnection>('/storefront/customer/invoices', accountListQuery(params), { ...options, cache: 'no-store' })\n return page ?? legacyAccountList<InvoiceListNode>(client, params, options, (o) => (o.invoice ? !['not_requested', 'awaiting_payment', 'window_closed'].includes(o.invoice.stage ?? 'not_requested') : true), (o) => ((o.invoices ?? []).length ? { order: orderRef(o), invoices: o.invoices ?? [] } : null))\n },\n },\n /**\n * The buyer's shipments, one node per delivered order with its service and parcels (`{ order, stage, service,\n * shipments }`), cursor-paged like `orders.list`, without tracking events or map (those come with `order(id)`).\n * An OPS older than 1.19 is served from one page of orders and their details.\n */\n shipments: {\n list: async (params?: ShipmentListParams, options?: RequestOptions): Promise<ShipmentConnection> => {\n const page = await getOrNull<ShipmentConnection>('/storefront/customer/shipments', accountListQuery(params), { ...options, cache: 'no-store' })\n return (\n page ??\n legacyAccountList<ShipmentListNode>(\n client,\n params,\n options,\n (o) => o.delivery_method !== 'pickup' && !['cancelled', 'refunded', 'pending_payment'].includes(o.status),\n (o) => {\n const service = o.shipping_service ?? null\n const shipments = o.shipments ?? []\n return service || shipments.length ? { order: orderRef(o), stage: o.progress?.stage ?? o.status, service, shipments } : null\n },\n )\n )\n },\n },\n /** `null` when the order does not exist or belongs to someone else. */\n order: (id: string, options?: RequestOptions) =>\n getOrNull<Order>(`/storefront/customer/orders/${enc(id)}`, undefined, options),\n requestReturn: (orderId: string, input: ReturnRequestInput, options?: WriteOptions) =>\n write<ReturnRequest>('POST', `/storefront/customer/orders/${enc(orderId)}/returns`, input, options),\n requestInvoice: (orderId: string, input: InvoiceRequest, options?: WriteOptions) =>\n write<InvoiceResult>('POST', `/storefront/customer/orders/${enc(orderId)}/invoice`, input, options),\n /**\n * Checkouts waiting for their payment (cash voucher: OXXO, SPEI). They are not orders yet; once the payment\n * confirms they leave this list and show up in `orders`.\n */\n pendingPayments: async (params?: PaginationParams, options?: RequestOptions): Promise<Connection<PendingPayment>> =>\n // An OPS older than the route answers 404: it has no pending payments to list (a 401 still throws).\n (await getOrNull<Connection<PendingPayment>>('/storefront/customer/pending-payments', params as QueryParams, options)) ?? {\n nodes: [],\n page_info: { has_next_page: false, end_cursor: null },\n total_count: 0,\n },\n /**\n * Reads one file (`pdf` | `xml`) of an invoice or credit note of the buyer's order, through the authenticated\n * route (`order_invoice_file`): the answer is the file itself (base64), never a URL, so neither the buyer token\n * nor a link of the PAC reaches the browser. Call it from YOUR server and stream the bytes\n * (`invoiceFileBytes`). `null` when the order, the document or the file does not exist or is not the buyer's.\n */\n invoiceFile: async (orderId: string, invoiceId: string, kind: InvoiceFileKind, options?: RequestOptions): Promise<InvoiceFile | null> => {\n if (kind !== 'pdf' && kind !== 'xml') throw new TypeError(\"invoiceFile: kind must be 'pdf' or 'xml'\")\n const file = await request<InvoiceFile>({\n method: 'GET',\n path: `/storefront/customer/orders/${enc(orderId)}/invoices/${enc(invoiceId)}/${kind}`,\n options: { ...options, cache: 'no-store' },\n nullOn404: true,\n noRedirect: true,\n })\n if (file === null) return null\n if (!file || typeof file.content_base64 !== 'string' || typeof file.filename !== 'string' || typeof file.content_type !== 'string') {\n throw new StorefrontError({ status: 502, code: 'invalid_response', message: 'The invoice file answer is not a file' })\n }\n return { filename: file.filename, content_type: file.content_type, content_base64: file.content_base64 }\n },\n /**\n * Saved fiscal profiles of the buyer (contract 1.9, `capabilities().fiscal_profiles`). Personal data: private,\n * never cached, never logged. `422` with `field: 'fiscal.<field>'` when the region rejects a value; `409` for a\n * repeated tax id or past the limit; `404` for a profile that is not the buyer's.\n */\n fiscalProfiles: {\n list: async (options?: RequestOptions): Promise<FiscalProfile[]> =>\n (await get<{ nodes: FiscalProfile[] }>('/storefront/customer/fiscal-profiles', undefined, { ...options, cache: 'no-store' })).nodes,\n create: (profile: FiscalProfileInput, options?: WriteOptions) =>\n write<FiscalProfile>('POST', '/storefront/customer/fiscal-profiles', profile, options),\n update: (id: string, profile: FiscalProfileInput, options?: WriteOptions) =>\n write<FiscalProfile>('PATCH', `/storefront/customer/fiscal-profiles/${enc(id)}`, profile, options),\n /** Physical delete (a profile leaves nothing behind). A saved default passes to another profile. */\n delete: (id: string, options?: WriteOptions) =>\n write<void>('DELETE', `/storefront/customer/fiscal-profiles/${enc(id)}`, undefined, options),\n },\n /**\n * Saved items of the buyer («My items», «My garage»; contract 1.9, `capabilities().subjects`). Personal data:\n * private, never cached, never logged. `422` with `field: 'attributes.<field>'` when the kind refuses a value\n * (it never echoes it); `409` for an item already saved or past the limit; `429` for too many saves; `404` for\n * an item that is not the buyer's. The server builds `label` and `fit_key`; private fields come back masked.\n */\n subjects: {\n list: async (params?: { kind?: string }, options?: RequestOptions): Promise<Subject[]> =>\n (await get<{ nodes: Subject[] }>('/storefront/customer/subjects', params as QueryParams | undefined, { ...options, cache: 'no-store' })).nodes,\n create: (input: SubjectInput, options?: WriteOptions) => write<Subject>('POST', '/storefront/customer/subjects', input, options),\n update: (id: string, patch: SubjectPatch, options?: WriteOptions) =>\n write<Subject>('PATCH', `/storefront/customer/subjects/${enc(id)}`, patch, options),\n /** Physical delete (the item leaves nothing behind). The default of its kind passes to another item. */\n delete: (id: string, options?: WriteOptions) => write<void>('DELETE', `/storefront/customer/subjects/${enc(id)}`, undefined, options),\n },\n addresses: {\n list: (options?: RequestOptions) => get<{ nodes: Address[] }>('/storefront/customer/addresses', undefined, options),\n create: (address: AddressInput, options?: WriteOptions) =>\n write<Address>('POST', '/storefront/customer/addresses', address, options),\n update: (id: string, address: Partial<AddressInput>, options?: WriteOptions) =>\n write<Address>('PATCH', `/storefront/customer/addresses/${enc(id)}`, address, options),\n delete: (id: string, options?: WriteOptions) =>\n write<void>('DELETE', `/storefront/customer/addresses/${enc(id)}`, undefined, options),\n },\n },\n\n content: {\n /**\n * The kinds of buyer item the organization declares («My garage») and their catalogs (contract 1.9; public,\n * cacheable). `[]` when it declares none or the server predates the route: the store has no such section.\n */\n subjectKinds: async (options?: RequestOptions): Promise<SubjectKind[]> =>\n (await getOrNull<{ nodes: SubjectKind[] }>('/storefront/subject-kinds', undefined, options))?.nodes ?? [],\n theme: (options?: RequestOptions) => get<Theme>('/storefront/content/theme', undefined, options),\n /** `null` when the page does not exist. */\n page: (handle: string, options?: PreviewOptions) =>\n getOrNull<Page>(`/storefront/content/pages/${enc(handle)}`, previewQuery(options), options),\n /** `null` when the menu does not exist. */\n menu: (handle: string, options?: RequestOptions) =>\n getOrNull<Menu>(`/storefront/content/menus/${enc(handle)}`, undefined, options),\n articles: (params?: ArticleListParams, options?: RequestOptions) =>\n get<Connection<Article>>('/storefront/content/articles', params as QueryParams, options),\n /** `null` when the article does not exist. */\n article: (handle: string, options?: PreviewOptions) =>\n getOrNull<Article>(`/storefront/content/articles/${enc(handle)}`, previewQuery(options), options),\n },\n }\n return client\n}\n\nconst orderRef = (o: Order): OrderRef => ({ id: o.id, number: o.number, created_at: o.created_at })\n\n/**\n * The invoices / shipments lists on an OPS that has no such route (older than contract 1.19): ONE page of orders,\n * the detail of those that can have the data, folded into the same nodes. A 401 still throws; an order that fails\n * to open is skipped.\n */\nasync function legacyAccountList<N>(\n client: ReturnType<typeof createStorefrontClient>,\n params: (InvoiceListParams | ShipmentListParams) | undefined,\n options: RequestOptions | undefined,\n keep: (summary: Order) => boolean,\n toNode: (detail: Order) => N | null,\n): Promise<Connection<N>> {\n const page = await client.customer.orders.list({ ...(params?.first ? { first: params.first } : {}), ...(params?.after ? { after: params.after } : {}), ...(params?.from ? { from: params.from } : {}), ...(params?.to ? { to: params.to } : {}), ...(params?.q ? { q: params.q } : {}) }, options)\n const details = await Promise.all(\n page.nodes.filter(keep).map((o) =>\n client.customer.order(o.id, options).catch((err: unknown) => {\n if (err instanceof StorefrontError && err.status === 401) throw err\n return null\n }),\n ),\n )\n const nodes = details.map((d) => (d ? toNode(d) : null)).filter((n): n is N => n !== null)\n return { nodes, page_info: { has_next_page: page.page_info.has_next_page, end_cursor: page.page_info.end_cursor } }\n}\n\nexport type StorefrontClient = ReturnType<typeof createStorefrontClient>\n\n/** `X-Storefront-Domain` value: the host, plus `#<market>` when a valid market code is given. */\nexport function storefrontDomainHeader(domain: string, market?: string | null): string {\n const host = domain.trim()\n const code = (market ?? '').trim().toLowerCase()\n return code && /^[a-z0-9_-]{1,32}$/.test(code) ? `${host}#${code}` : host\n}\n","/**\n * Classification of the failures of a card payment (`POST pay` / `GET status`). No texts, no DOM, no server APIs: the\n * shop's server uses it to answer with `kind` and `retryable`, and the browser transport uses it to decide whether to\n * repeat, ask for the status or give up.\n *\n * Rule that never changes: an INDETERMINATE result (`transient`, `in_progress`) is never charged again with another\n * idempotency key; it is repeated with the SAME key or its status is read.\n */\n\nexport type PaymentErrorClassKind =\n /** OPS or the provider did not answer (5xx, timeout, network). The charge may or may not have happened. */\n | 'transient'\n /** A payment is already in progress for this order (409): read the status, do not charge again. */\n | 'in_progress'\n /** Too many attempts (429). */\n | 'rate_limited'\n /** Credentials or configuration of the merchant with the provider: not the buyer's fault. */\n | 'merchant_config'\n /** The provider refused the charge at API level (`payment_provider_rejected`): definitive, nothing was charged. */\n | 'provider_declined'\n /** The cart already became an order and OPS will not open a new attempt (`422 invalid_state`). */\n | 'stale_checkout'\n | 'expired'\n | 'price_mismatch'\n | 'store_closed'\n | 'validation'\n | 'other'\n\nexport type PaymentErrorClass = { kind: PaymentErrorClassKind; retryable: boolean }\n\nexport type PaymentErrorLike = {\n status?: number | null\n code?: string | null\n field?: string | null\n /** `error.retryable` as OPS declared it (`StorefrontError.retryable`). */\n retryable?: boolean | null\n /** `error.checkout_id` (`StorefrontError.checkoutId`). */\n checkoutId?: string | null\n /** Raw `error.details`; a `retryable` inside is honoured too (older bodies). */\n details?: unknown\n}\n\n/** Did OPS expressly say the failure must NOT be repeated (`retryable: false`, on the error or inside `details`)? */\nexport function opsSaysNotRetryable(err: PaymentErrorLike): boolean {\n if (err.retryable === false) return true\n const d = err.details\n return typeof d === 'object' && d !== null && (d as { retryable?: unknown }).retryable === false\n}\n\n/** Field the shop's server sets when IT refuses a payment row that is not offered (so it is not read as a stale checkout). */\nexport const PAYMENT_CHOICE_REFUSED_FIELD = 'payment_choice'\n\nconst MERCHANT_CONFIG_CODE = /credential|not_configured|unconfigured|invalid_access|access_token|provider_config|merchant|invalid_public_key|unauthorized/i\n\n/**\n * What a payment failure means and whether repeating it can help. What OPS declares (`retryable`, stable codes) wins\n * over the HTTP status: a 502 with a stable code is an answer, not \"no response\".\n */\nexport function classifyPaymentError(err: PaymentErrorLike): PaymentErrorClass {\n const status = typeof err.status === 'number' ? err.status : 0\n const code = typeof err.code === 'string' ? err.code : ''\n if (code === 'store_not_ready') return { kind: 'store_closed', retryable: false }\n if (code === 'price_mismatch' || (status === 422 && err.field === 'expected_total')) return { kind: 'price_mismatch', retryable: false }\n if (status === 409 && (code === 'payment_in_progress' || err.field === 'payment_in_progress')) return { kind: 'in_progress', retryable: true }\n if (status === 409 && code === 'expired') return { kind: 'expired', retryable: false }\n if (status === 429 || code === 'too_many_attempts' || code === 'rate_limited') return { kind: 'rate_limited', retryable: true }\n if (status === 422 && code === 'invalid_state') {\n if (err.field === PAYMENT_CHOICE_REFUSED_FIELD) return { kind: 'other', retryable: false }\n return { kind: 'stale_checkout', retryable: false }\n }\n if (code === 'payment_provider_misconfigured') return { kind: 'merchant_config', retryable: false }\n if (code === 'payment_provider_rejected') return { kind: 'provider_declined', retryable: false }\n if (MERCHANT_CONFIG_CODE.test(code) || status === 401 || status === 403) return { kind: 'merchant_config', retryable: false }\n // OPS answered and said \"do not repeat\": definitive, not indeterminate (there is no lost answer to verify).\n if (status >= 500 && opsSaysNotRetryable(err)) return { kind: 'other', retryable: false }\n if (status === 0 || status >= 500 || code === 'network' || code === 'timeout' || code === 'unavailable') return { kind: 'transient', retryable: true }\n if (status === 400 || code === 'validation') return { kind: 'validation', retryable: false }\n return { kind: 'other', retryable: false }\n}\n","import type { StorefrontClient } from './client.js'\nimport { isStorefrontError } from './errors.js'\nimport type { TokenIntrospection } from './types.js'\n\n/** `sk_…a91f`: the prefix and the last four characters, never enough to use the token. */\nexport function maskToken(token: string | null | undefined): string {\n if (!token) return '(sin token)'\n const prefix = /^[a-z]{2}_/.exec(token)?.[0] ?? ''\n return token.length <= prefix.length + 8 ? `${prefix}…` : `${prefix}…${token.slice(-4)}`\n}\n\nexport type DiagnoseOptions = {\n /** Where the warning goes (default `console.warn`). Receives ONE line per problem. */\n log?: (message: string) => void\n /** Name of the connection, shown in the repair path. */\n connectionName?: string\n /** Give up after this long (default 3000 ms). */\n timeoutMs?: number\n}\n\n/** Where the operator repairs a connection in OPS (es-MX, as the screen names it). */\nexport function repairPath(connectionName?: string): string {\n return `OPS → Conexiones y API → ${connectionName ?? '<conexión>'} → Reparar permisos`\n}\n\n/**\n * Startup check of the store's credential: asks `token.introspect()` and, when scopes are missing, logs ONE clear\n * warning with the repair path (never the token, only `sk_…a91f`). It NEVER throws and is meant to be fired and\n * forgotten, so it cannot delay or break the boot:\n *\n * ```ts\n * void diagnose(storefront)\n * ```\n *\n * Resolves with the introspection, or `null` when it could not be obtained (older OPS, outage, bad token).\n */\nexport async function diagnose(client: StorefrontClient, options: DiagnoseOptions = {}): Promise<TokenIntrospection | null> {\n const log = options.log ?? ((m: string) => console.warn(m))\n const timeoutMs = options.timeoutMs ?? 3000\n const raw = client.config.token\n let mask: string\n try {\n mask = maskToken(typeof raw === 'function' ? raw() : raw)\n } catch {\n mask = maskToken(null)\n }\n try {\n const info = await client.token.introspect({ signal: AbortSignal.timeout(timeoutMs) })\n const missing = Array.isArray(info?.missing_scopes) ? info.missing_scopes : []\n if (missing.length > 0) {\n log(\n `[@asteby/storefront] La credencial ${mask} no tiene permisos que la tienda necesita: ${missing.join(', ')}. ` +\n `Repáralo en ${repairPath(options.connectionName)} (no hace falta cambiar la clave ni reiniciar).`,\n )\n }\n return info ?? null\n } catch (err) {\n if (isStorefrontError(err) && err.status === 401) {\n try {\n log(`[@asteby/storefront] OPS rechazó la credencial ${mask} (401): está revocada o vencida. Vuelve a conectar la tienda en OPS → Conexiones y API.`)\n } catch {\n /* a broken logger must not break boot */\n }\n }\n return null\n }\n}\n","/**\n * Availability presentation: the single source of the texts and states a\n * storefront shows for stock. Pure functions, no DOM: safe in loaders, SSR and\n * edge runtimes.\n *\n * The server decides the state (`Availability.status`, already filtered by the\n * shop's `show_stock`); this module only turns it into labels. Shops may\n * override texts by key (`messages`) but never the logic. Numbers shown here\n * (\"Quedan 3\") come from `availability.quantity`, which the server sends only\n * when the shop allows it and past its own threshold: there is no threshold in\n * this code.\n */\nimport type { Availability, AvailabilityStatus, CartLine, CartLineProblem, InsufficientStockLine, Product, ProductVariant } from './types.js'\n\nexport type AvailabilityTone = 'success' | 'warning' | 'danger' | 'info'\n\nexport type AvailabilityLocale = 'es' | 'en'\n\n/** Text keys, overridable per shop. `{n}` and `{date}` are replaced. */\nexport type AvailabilityMessageKey =\n | 'status.in_stock'\n | 'status.low_stock'\n | 'status.low_stock_n'\n | 'status.out_of_stock'\n | 'status.backorder'\n | 'status.preorder'\n | 'sub.backorder_eta'\n | 'sub.preorder_date'\n | 'line.ships_on'\n | 'cta.add'\n | 'cta.out_of_stock'\n | 'cta.backorder'\n | 'cta.preorder'\n | 'sr.in_stock'\n | 'sr.low_stock'\n | 'sr.low_stock_n'\n | 'sr.out_of_stock'\n | 'sr.backorder'\n | 'sr.preorder'\n | 'option.sold_out'\n | 'option.backorder'\n | 'option.preorder'\n | 'max_per_order'\n | 'notify.title'\n | 'notify.email'\n | 'notify.phone'\n | 'notify.consent'\n | 'notify.submit'\n | 'notify.done'\n | 'notify.error'\n | 'problem.out_of_stock'\n | 'problem.insufficient_stock'\n | 'problem.insufficient_stock_n'\n | 'problem.adjust'\n | 'problem.remove'\n | 'conflict.title'\n | 'conflict.body'\n | 'conflict.dismiss'\n\nexport type AvailabilityMessages = Record<AvailabilityMessageKey, string>\n\nconst ES: AvailabilityMessages = {\n 'status.in_stock': 'Disponible',\n 'status.low_stock': 'Pocas piezas',\n 'status.low_stock_n': 'Quedan {n}',\n 'status.out_of_stock': 'Agotado',\n 'status.backorder': 'Bajo pedido',\n 'status.preorder': 'Preventa',\n 'sub.backorder_eta': 'Se envía a partir del {date}',\n 'sub.preorder_date': 'Sale a la venta el {date}',\n 'line.ships_on': 'Se enviará el: {date}',\n 'cta.add': 'Agregar al carrito',\n 'cta.out_of_stock': 'Agotado',\n 'cta.backorder': 'Pedir bajo pedido',\n 'cta.preorder': 'Apartar en preventa',\n 'sr.in_stock': 'Disponible',\n 'sr.low_stock': 'Quedan pocas piezas',\n 'sr.low_stock_n': 'Quedan solo {n} piezas',\n 'sr.out_of_stock': 'Producto agotado',\n 'sr.backorder': 'Disponible bajo pedido',\n 'sr.preorder': 'Disponible en preventa',\n 'option.sold_out': 'agotado',\n 'option.backorder': 'bajo pedido',\n 'option.preorder': 'preventa',\n max_per_order: 'Máximo {n} por pedido',\n 'notify.title': 'Avísame cuando vuelva',\n 'notify.email': 'Correo electrónico',\n 'notify.phone': 'WhatsApp o teléfono',\n 'notify.consent': 'Acepto recibir un aviso cuando vuelva a estar disponible',\n 'notify.submit': 'Avísame',\n 'notify.done': 'Listo. Te avisaremos cuando vuelva a estar disponible.',\n 'notify.error': 'No pudimos guardar tu aviso. Revisa tus datos e inténtalo de nuevo.',\n 'problem.out_of_stock': 'Ya no hay existencias',\n 'problem.insufficient_stock': 'No hay suficientes piezas para esta cantidad',\n 'problem.insufficient_stock_n': 'Solo puedes llevar {n}',\n 'problem.adjust': 'Ajustar a {n}',\n 'problem.remove': 'Quitar',\n 'conflict.title': 'Algunos productos cambiaron de existencias',\n 'conflict.body': 'Revisa las líneas marcadas. Tu carrito y tus datos se conservaron; ajusta o quita lo que ya no está disponible y continúa.',\n 'conflict.dismiss': 'Entendido',\n}\n\nconst EN: AvailabilityMessages = {\n 'status.in_stock': 'In stock',\n 'status.low_stock': 'Low stock',\n 'status.low_stock_n': 'Only {n} left',\n 'status.out_of_stock': 'Sold out',\n 'status.backorder': 'Made to order',\n 'status.preorder': 'Pre-order',\n 'sub.backorder_eta': 'Ships from {date}',\n 'sub.preorder_date': 'Available on {date}',\n 'line.ships_on': 'Ships on: {date}',\n 'cta.add': 'Add to cart',\n 'cta.out_of_stock': 'Sold out',\n 'cta.backorder': 'Order now, ships later',\n 'cta.preorder': 'Pre-order',\n 'sr.in_stock': 'In stock',\n 'sr.low_stock': 'Low stock',\n 'sr.low_stock_n': 'Only {n} left in stock',\n 'sr.out_of_stock': 'Sold out',\n 'sr.backorder': 'Available to order, ships later',\n 'sr.preorder': 'Available for pre-order',\n 'option.sold_out': 'sold out',\n 'option.backorder': 'made to order',\n 'option.preorder': 'pre-order',\n max_per_order: 'Maximum {n} per order',\n 'notify.title': 'Notify me when it is back',\n 'notify.email': 'Email',\n 'notify.phone': 'WhatsApp or phone',\n 'notify.consent': 'I agree to receive a notice when it is back in stock',\n 'notify.submit': 'Notify me',\n 'notify.done': 'Done. We will let you know when it is back in stock.',\n 'notify.error': 'We could not save your request. Check your details and try again.',\n 'problem.out_of_stock': 'No longer in stock',\n 'problem.insufficient_stock': 'Not enough stock for this quantity',\n 'problem.insufficient_stock_n': 'You can take up to {n}',\n 'problem.adjust': 'Adjust to {n}',\n 'problem.remove': 'Remove',\n 'conflict.title': 'Some items changed stock',\n 'conflict.body': 'Review the marked lines. Your cart and your details were kept; adjust or remove what is no longer available and continue.',\n 'conflict.dismiss': 'Got it',\n}\n\nconst CATALOG: Record<AvailabilityLocale, AvailabilityMessages> = { es: ES, en: EN }\n\n/** `es-MX` -> `es`, `en-US` -> `en`; anything else falls back to Spanish. */\nexport function availabilityLocale(locale: string | null | undefined): AvailabilityLocale {\n return (locale ?? '').toLowerCase().startsWith('en') ? 'en' : 'es'\n}\n\n/** Catalog for a locale with the shop's per-key overrides applied. */\nexport function availabilityMessages(locale: string | null | undefined, overrides?: Partial<AvailabilityMessages> | null): AvailabilityMessages {\n const base = CATALOG[availabilityLocale(locale)]\n if (!overrides) return base\n const out = { ...base }\n for (const [k, v] of Object.entries(overrides)) if (typeof v === 'string' && k in base) out[k as AvailabilityMessageKey] = v\n return out\n}\n\n/** Replaces `{name}` placeholders. */\nexport function formatAvailabilityMessage(template: string, values: Record<string, string | number> = {}): string {\n return template.replace(/\\{(\\w+)\\}/g, (m, k: string) => (k in values ? String(values[k]) : m))\n}\n\nfunction formatDate(value: string | null | undefined, locale: string | null | undefined): string | null {\n if (!value) return null\n const d = /^\\d{4}-\\d{2}-\\d{2}$/.test(value) ? new Date(`${value}T00:00:00Z`) : new Date(value)\n if (Number.isNaN(d.getTime())) return null\n try {\n // UTC keeps server and client renders identical (no hydration mismatch).\n return new Intl.DateTimeFormat(locale || 'es', { dateStyle: 'long', timeZone: 'UTC' }).format(d)\n } catch {\n return value.slice(0, 10)\n }\n}\n\n/**\n * Ship date of a cart line, `YYYY-MM-DD`, or `null`. Pure: it only picks what the server\n * sent (`ships_on`, else `availability.restock_eta`, else the date part of `preorder_release_at`).\n */\nexport function lineShipDate(line: Pick<CartLine, 'ships_on' | 'availability'>): string | null {\n const day = (v: string | null | undefined) => {\n const d = typeof v === 'string' ? v.slice(0, 10) : ''\n return /^\\d{4}-\\d{2}-\\d{2}$/.test(d) ? d : null\n }\n return day(line.ships_on) ?? day(line.availability?.restock_eta) ?? day(line.availability?.preorder_release_at)\n}\n\n/** Localized \"Ships on: {date}\" for a cart line, or `null` without a date. */\nexport function lineShipLabel(\n line: Pick<CartLine, 'ships_on' | 'availability'>,\n locale: string | null | undefined,\n overrides?: Partial<AvailabilityMessages> | null,\n): string | null {\n const date = formatDate(lineShipDate(line), locale)\n if (!date) return null\n return formatAvailabilityMessage(availabilityMessages(locale, overrides)['line.ships_on'], { date })\n}\n\nexport type ResolveAvailabilityOptions = {\n /**\n * Polyfill only: shop-level \"low stock\" threshold to derive `low_stock` from\n * `quantity_available` on servers older than contract 1.1. Without it the\n * polyfill never reports `low_stock`. Ignored when the server sends `availability`.\n */\n lowStockThreshold?: number | null\n}\n\ntype AvailabilitySource = Pick<Product | ProductVariant, 'available_for_sale'> & {\n availability?: Availability | null\n quantity_available?: number | null\n}\n\n/**\n * The `Availability` of a variant or product. Uses the server's `availability`\n * when present; otherwise derives `in_stock | low_stock | out_of_stock` from\n * `available_for_sale` / `quantity_available` so storefronts can migrate before\n * the backend does. A malformed `availability` falls back to the polyfill.\n */\nexport function resolveAvailability(source: AvailabilitySource, options: ResolveAvailabilityOptions = {}): Availability {\n const a = source.availability\n if (a && typeof a === 'object' && typeof a.status === 'string') return a\n const qty = typeof source.quantity_available === 'number' ? source.quantity_available : null\n const sellable = source.available_for_sale && (qty === null || qty > 0)\n const threshold = options.lowStockThreshold\n const low = sellable && qty !== null && typeof threshold === 'number' && threshold > 0 && qty <= threshold\n const status: AvailabilityStatus = !sellable ? 'out_of_stock' : low ? 'low_stock' : 'in_stock'\n return {\n status,\n quantity: sellable ? qty : null,\n max_per_order: sellable ? qty : null,\n restock_eta: null,\n preorder_release_at: null,\n // Old servers have no subscription route: never offer a form that cannot work.\n notify_available: false,\n }\n}\n\nexport type AvailabilityView = {\n status: AvailabilityStatus\n tone: AvailabilityTone\n /** Short badge text: \"Agotado\", \"Quedan 3\", \"Bajo pedido\"... Never empty. */\n label: string\n /** ETA / release date text, or `null`. */\n sublabel: string | null\n /** Primary button text. */\n ctaLabel: string\n /** The primary button may be pressed (backorder/preorder are purchasable). */\n ctaEnabled: boolean\n /** Offer the \"Notify me when it is back\" form. */\n showNotify: boolean\n /** Full sentence for screen readers. */\n srText: string\n /** Units to cap the quantity picker at, or `null`. */\n maxPerOrder: number | null\n /** Show a badge on listing cards (everything but plain `in_stock`: do not clutter). */\n showOnCard: boolean\n}\n\nexport type AvailabilityViewOptions = {\n messages?: Partial<AvailabilityMessages> | null\n}\n\nconst TONES: Record<AvailabilityStatus, AvailabilityTone> = {\n in_stock: 'success',\n low_stock: 'warning',\n out_of_stock: 'danger',\n backorder: 'info',\n preorder: 'info',\n}\n\n/**\n * Texts and flags for one availability. `availability` accepts anything with an\n * unknown `status` (a future server): it is treated as `out_of_stock`.\n */\nexport function availabilityView(availability: Availability, locale: string | null | undefined, options: AvailabilityViewOptions = {}): AvailabilityView {\n const m = availabilityMessages(locale, options.messages)\n const known = (['in_stock', 'low_stock', 'out_of_stock', 'backorder', 'preorder'] as const).includes(availability.status)\n const status: AvailabilityStatus = known ? availability.status : 'out_of_stock'\n const qty = typeof availability.quantity === 'number' && availability.quantity > 0 ? availability.quantity : null\n const f = formatAvailabilityMessage\n\n let label: string\n let sr: string\n let cta: string\n let sublabel: string | null = null\n let enabled = true\n switch (status) {\n case 'in_stock':\n label = m['status.in_stock']\n sr = m['sr.in_stock']\n cta = m['cta.add']\n break\n case 'low_stock':\n // Without a visible quantity the server still says \"low\": no number is invented.\n label = qty !== null ? f(m['status.low_stock_n'], { n: qty }) : m['status.low_stock']\n sr = qty !== null ? f(m['sr.low_stock_n'], { n: qty }) : m['sr.low_stock']\n cta = m['cta.add']\n break\n case 'backorder': {\n label = m['status.backorder']\n sr = m['sr.backorder']\n cta = m['cta.backorder']\n const date = formatDate(availability.restock_eta, locale)\n if (date) sublabel = f(m['sub.backorder_eta'], { date })\n break\n }\n case 'preorder': {\n label = m['status.preorder']\n sr = m['sr.preorder']\n cta = m['cta.preorder']\n const date = formatDate(availability.preorder_release_at ?? availability.restock_eta, locale)\n if (date) sublabel = f(m['sub.preorder_date'], { date })\n break\n }\n default:\n label = m['status.out_of_stock']\n sr = m['sr.out_of_stock']\n cta = m['cta.out_of_stock']\n enabled = false\n }\n return {\n status,\n tone: TONES[status],\n label,\n sublabel,\n ctaLabel: cta,\n ctaEnabled: enabled,\n showNotify: status === 'out_of_stock' && availability.notify_available === true,\n srText: sublabel ? `${sr}. ${sublabel}` : sr,\n maxPerOrder: typeof availability.max_per_order === 'number' && availability.max_per_order > 0 ? availability.max_per_order : null,\n showOnCard: status !== 'in_stock',\n }\n}\n\nexport type CartLineProblemView = {\n code: CartLineProblem['code']\n /** \"Ya no hay existencias\" / \"Solo puedes llevar 2\". */\n message: string\n /** Quantity to adjust the line to, or `null` (remove only). */\n adjustTo: number | null\n adjustLabel: string | null\n removeLabel: string\n}\n\n/** Texts and actions for a cart line problem. Offers \"Adjust to N\" only when `max_quantity` is a positive number different from the line quantity (a refused change leaves the cart at its old quantity). */\nexport function cartLineProblemView(\n problem: CartLineProblem | InsufficientStockLine,\n locale: string | null | undefined,\n options: AvailabilityViewOptions & { lineQuantity?: number } = {},\n): CartLineProblemView {\n const m = availabilityMessages(locale, options.messages)\n const code: CartLineProblem['code'] = 'code' in problem ? problem.code : problem.status === 'out_of_stock' ? 'out_of_stock' : 'insufficient_stock'\n const max = typeof problem.max_quantity === 'number' && problem.max_quantity >= 0 ? problem.max_quantity : null\n const canAdjust = max !== null && max > 0 && (options.lineQuantity === undefined || max !== options.lineQuantity)\n const message =\n code === 'out_of_stock' || max === 0\n ? m['problem.out_of_stock']\n : max !== null\n ? formatAvailabilityMessage(m['problem.insufficient_stock_n'], { n: max })\n : m['problem.insufficient_stock']\n return {\n code,\n message,\n adjustTo: canAdjust ? max : null,\n adjustLabel: canAdjust ? formatAvailabilityMessage(m['problem.adjust'], { n: max }) : null,\n removeLabel: m['problem.remove'],\n }\n}\n\nconst SCHEMA_AVAILABILITY: Record<AvailabilityStatus, string> = {\n in_stock: 'https://schema.org/InStock',\n low_stock: 'https://schema.org/LimitedAvailability',\n out_of_stock: 'https://schema.org/OutOfStock',\n backorder: 'https://schema.org/BackOrder',\n preorder: 'https://schema.org/PreOrder',\n}\n\n/** schema.org `ItemAvailability` URL for a status (unknown -> `OutOfStock`). */\nexport function schemaAvailability(status: AvailabilityStatus | string): string {\n return SCHEMA_AVAILABILITY[status as AvailabilityStatus] ?? SCHEMA_AVAILABILITY.out_of_stock\n}\n\n/** Best state among variants for a product summary (when the server sends none). */\nexport function productAvailability(product: Pick<Product, 'variants' | 'available_for_sale' | 'availability'>, options: ResolveAvailabilityOptions = {}): Availability {\n if (product.availability) return product.availability\n const all = product.variants.map((v) => resolveAvailability(v, options))\n const rank: AvailabilityStatus[] = ['in_stock', 'low_stock', 'backorder', 'preorder', 'out_of_stock']\n const best = all.slice().sort((a, b) => rank.indexOf(a.status) - rank.indexOf(b.status))[0]\n return best ?? resolveAvailability(product, options)\n}\n","/**\n * Embedded payment presentation: the single source of the texts and states a\n * storefront shows around an in-page payment. Pure functions, no DOM: safe in\n * loaders, SSR and edge runtimes.\n *\n * Rules this module encodes (DISENO-PAGO-INTEGRADO-BRICKS):\n * - The server decides the outcome and the amount. Nothing here computes or\n * compares money; `expected_total` is the server's own number echoed back.\n * - A rejection is explained with an actionable text built from the neutral\n * `decline_code`. A raw provider code is never shown.\n * - Vouchers and redirects only trust https URLs.\n */\nimport { availabilityLocale, formatAvailabilityMessage, type AvailabilityLocale } from './availability.js'\nimport { StorefrontError } from './errors.js'\nimport type { DeclineCode, Money, PaymentAction, PaymentAttemptResult, PaymentNextStep, PaymentVoucher } from './types.js'\n\nexport type PaymentLocale = AvailabilityLocale\n\nexport type PaymentMessageKey =\n | `decline.${DeclineCode}`\n | 'state.loading'\n | 'state.processing'\n | 'state.approved'\n | 'state.in_review'\n | 'state.voucher'\n | 'state.challenge'\n | 'state.expired'\n | 'state.cancelled'\n | 'state.redirect'\n | 'state.fallback'\n | 'error.network'\n | 'error.card_data'\n | 'error.price_mismatch'\n | 'error.payment_in_progress'\n | 'error.expired'\n | 'error.too_many_attempts'\n | 'error.generic'\n | 'action.retry'\n | 'action.try_again'\n | 'action.pay'\n | 'action.cancel'\n | 'voucher.title'\n | 'voucher.point'\n | 'voucher.reference'\n | 'voucher.amount'\n | 'voucher.expires'\n | 'voucher.clabe'\n | 'voucher.barcode'\n | 'voucher.open'\n | 'voucher.email'\n | 'form.label'\n | 'challenge.title'\n | 'challenge.escape'\n | 'challenge.escape_hint'\n | 'challenge.left'\n\nexport type PaymentMessages = Record<PaymentMessageKey, string>\n\nconst ES: PaymentMessages = {\n 'decline.insufficient_funds': 'Tu tarjeta no tiene saldo suficiente. Prueba con otra tarjeta o paga en efectivo.',\n 'decline.invalid_cvc': 'El código de seguridad no es correcto. Revísalo e intenta de nuevo.',\n 'decline.invalid_expiry': 'La fecha de vencimiento no es correcta.',\n 'decline.invalid_card_data': 'Revisa los datos de tu tarjeta.',\n 'decline.call_issuer': 'Tu banco necesita que autorices este pago. Llama al número al reverso de tu tarjeta y vuelve a intentarlo.',\n 'decline.card_disabled': 'Tu tarjeta no está activa. Actívala con tu banco o usa otra.',\n 'decline.duplicate': 'Ya hiciste un pago igual hace un momento. Revisa tu correo antes de volver a pagar.',\n 'decline.max_attempts': 'Llegaste al límite de intentos con esta tarjeta. Usa otra o paga en efectivo.',\n 'decline.authentication_failed': 'Tu banco no pudo verificar el pago. Intenta de nuevo o usa otra tarjeta.',\n 'decline.declined': 'Tu banco rechazó el pago. Usa otra tarjeta o paga en efectivo.',\n 'state.loading': 'Cargando pago seguro…',\n 'state.processing': 'Procesando pago…',\n 'state.approved': '¡Pago aprobado!',\n 'state.in_review': 'Tu pago está en revisión. Te avisamos por correo en máximo 2 días hábiles. No vuelvas a pagar.',\n 'state.voucher': 'Tu ficha de pago está lista. El pedido se confirma cuando pagues.',\n 'state.challenge': 'Tu banco necesita verificar el pago. Termina la verificación para continuar.',\n 'state.expired': 'La ficha venció. Vuelve a armar tu carrito para pagar.',\n 'state.cancelled': 'El pago se canceló. Puedes intentarlo de nuevo.',\n 'state.redirect': 'Te llevamos a la página de pago…',\n 'state.fallback': 'No pudimos cargar el formulario seguro de tarjeta. Puedes pagar con tarjeta en el sitio del proveedor y regresar aquí.',\n 'error.network': 'No pudimos conectar. Revisa tu conexión e intenta de nuevo; no se te cobrará dos veces.',\n 'error.card_data': 'Revisa los datos de tu tarjeta.',\n 'error.price_mismatch': 'El total cambió. Revisa el nuevo total y vuelve a pagar.',\n 'error.payment_in_progress': 'Ya hay un pago en proceso para este pedido. No vuelvas a pagar; revisa tu correo.',\n 'error.expired': 'Tu apartado venció. Vuelve a armar tu carrito.',\n 'error.too_many_attempts': 'Por seguridad no podemos intentar con más tarjetas. Paga en efectivo o escríbenos.',\n 'error.generic': 'No pudimos procesar tu pago. Intenta de nuevo.',\n 'action.retry': 'Reintentar',\n 'action.try_again': 'Intentar de nuevo',\n 'action.pay': 'Pagar',\n 'action.cancel': 'Cancelar',\n 'voucher.title': 'Ficha de pago',\n 'voucher.point': 'Punto de pago',\n 'voucher.reference': 'Referencia',\n 'voucher.amount': 'Monto exacto',\n 'voucher.expires': 'Vence el {date}',\n 'voucher.clabe': 'CLABE',\n 'voucher.barcode': 'Código de barras',\n 'voucher.open': 'Ver o imprimir ficha',\n 'voucher.email': 'También te la enviamos a tu correo.',\n 'form.label': 'Datos de tu tarjeta',\n 'challenge.title': 'Verificación de tu banco',\n 'challenge.escape': 'Cancelar y volver al pago',\n 'challenge.escape_hint': '¿Tarda demasiado? Puedes cerrar la verificación. Si ya la aprobaste en tu banco, el pago aún puede completarse: te confirmamos aquí antes de dejarte pagar de nuevo.',\n 'challenge.left': 'Cerraste la verificación. Estamos confirmando con tu banco si el pago se completó; no vuelvas a pagar todavía.',\n}\n\nconst EN: PaymentMessages = {\n 'decline.insufficient_funds': 'Your card has insufficient funds. Try another card or pay in cash.',\n 'decline.invalid_cvc': 'The security code is not correct. Check it and try again.',\n 'decline.invalid_expiry': 'The expiry date is not correct.',\n 'decline.invalid_card_data': 'Check your card details.',\n 'decline.call_issuer': 'Your bank needs you to authorize this payment. Call the number on the back of your card and try again.',\n 'decline.card_disabled': 'Your card is not active. Activate it with your bank or use another one.',\n 'decline.duplicate': 'You already made the same payment a moment ago. Check your email before paying again.',\n 'decline.max_attempts': 'You reached the attempt limit for this card. Use another card or pay in cash.',\n 'decline.authentication_failed': 'Your bank could not verify the payment. Try again or use another card.',\n 'decline.declined': 'Your bank declined the payment. Use another card or pay in cash.',\n 'state.loading': 'Loading secure payment…',\n 'state.processing': 'Processing payment…',\n 'state.approved': 'Payment approved!',\n 'state.in_review': 'Your payment is under review. We will email you within 2 business days. Do not pay again.',\n 'state.voucher': 'Your payment voucher is ready. The order is confirmed once you pay.',\n 'state.challenge': 'Your bank needs to verify the payment. Finish the verification to continue.',\n 'state.expired': 'The voucher expired. Rebuild your cart to pay.',\n 'state.cancelled': 'The payment was cancelled. You can try again.',\n 'state.redirect': 'Taking you to the payment page…',\n 'state.fallback': 'We could not load the secure card form. You can pay by card on the provider site and come back here.',\n 'error.network': 'We could not connect. Check your connection and try again; you will not be charged twice.',\n 'error.card_data': 'Check your card details.',\n 'error.price_mismatch': 'The total changed. Review the new total and pay again.',\n 'error.payment_in_progress': 'A payment is already in progress for this order. Do not pay again; check your email.',\n 'error.expired': 'Your reservation expired. Rebuild your cart.',\n 'error.too_many_attempts': 'For security we cannot try more cards. Pay in cash or contact us.',\n 'error.generic': 'We could not process your payment. Please try again.',\n 'action.retry': 'Retry',\n 'action.try_again': 'Try again',\n 'action.pay': 'Pay',\n 'action.cancel': 'Cancel',\n 'voucher.title': 'Payment voucher',\n 'voucher.point': 'Payment point',\n 'voucher.reference': 'Reference',\n 'voucher.amount': 'Exact amount',\n 'voucher.expires': 'Expires on {date}',\n 'voucher.clabe': 'CLABE',\n 'voucher.barcode': 'Barcode',\n 'voucher.open': 'View or print voucher',\n 'voucher.email': 'We also emailed it to you.',\n 'form.label': 'Your card details',\n 'challenge.title': 'Your bank verification',\n 'challenge.escape': 'Cancel and go back to payment',\n 'challenge.escape_hint': 'Taking too long? You can close the verification. If you already approved it with your bank the payment may still go through: we confirm here before letting you pay again.',\n 'challenge.left': 'You closed the verification. We are checking with your bank whether the payment went through; do not pay again yet.',\n}\n\nconst CATALOG: Record<PaymentLocale, PaymentMessages> = { es: ES, en: EN }\n\n/** Catalog for a locale (`es-MX` -> es, `en-US` -> en) with the shop's per-key overrides applied. */\nexport function paymentMessages(locale: string | null | undefined, overrides?: Partial<PaymentMessages> | null): PaymentMessages {\n const base = CATALOG[availabilityLocale(locale)]\n if (!overrides) return base\n const out = { ...base }\n for (const [k, v] of Object.entries(overrides)) if (typeof v === 'string' && k in base) out[k as PaymentMessageKey] = v\n return out\n}\n\nconst DECLINE_CODES: ReadonlySet<string> = new Set<DeclineCode>([\n 'insufficient_funds',\n 'invalid_cvc',\n 'invalid_expiry',\n 'invalid_card_data',\n 'call_issuer',\n 'card_disabled',\n 'duplicate',\n 'max_attempts',\n 'authentication_failed',\n 'declined',\n])\n\n/** i18n key of a decline code; unknown or missing codes map to `declined` (never a raw provider code). */\nexport function declineMessageKey(code: string | null | undefined): `decline.${DeclineCode}` {\n return `decline.${code && DECLINE_CODES.has(code) ? (code as DeclineCode) : 'declined'}`\n}\n\n/** Actionable text for a decline code. */\nexport function declineMessage(code: string | null | undefined, locale?: string | null, overrides?: Partial<PaymentMessages> | null): string {\n return paymentMessages(locale, overrides)[declineMessageKey(code)]\n}\n\n/** The value only if it is an absolute `https:` URL without credentials; `null` otherwise. */\nexport function safeHttpsUrl(value: unknown): string | null {\n if (typeof value !== 'string' || value.length > 2048) return null\n try {\n const u = new URL(value)\n if (u.protocol !== 'https:' || u.username || u.password) return null\n return u.toString()\n } catch {\n return null\n }\n}\n\n/** What the UI should do with an attempt result. */\nexport type PaymentOutcomeKind =\n | 'approved' // paid: go to the thanks page\n | 'in_review' // pending without action: do not charge again\n | 'voucher' // cash/SPEI voucher with reference and expiry\n | 'challenge' // 3DS inside the page\n | 'redirect' // leave to the provider\n | 'rejected' // failed: show the reason and let the buyer retry\n | 'expired'\n | 'cancelled'\n\n/** A voucher ready to render: https-only link and the amount as `Money` (or `null` when the server sent none). */\nexport type PaymentOutcomeVoucher = Omit<PaymentVoucher, 'amount' | 'voucher_url' | 'currency'> & {\n voucher_url: string | null\n amount: Money | null\n}\n\nconst NEXT_STEP: Record<DeclineCode, PaymentNextStep> = {\n insufficient_funds: 'use_other_card',\n invalid_cvc: 'fix_card_data',\n invalid_expiry: 'fix_card_data',\n invalid_card_data: 'fix_card_data',\n call_issuer: 'contact_issuer',\n card_disabled: 'use_other_card',\n duplicate: 'check_email',\n max_attempts: 'use_other_card',\n authentication_failed: 'retry',\n declined: 'use_other_card',\n}\n\nfunction voucherMoney(v: PaymentVoucher): Money | null {\n const a = v.amount\n if (a && typeof a === 'object' && typeof a.amount === 'string') return a\n const text = typeof a === 'number' ? String(a) : typeof a === 'string' ? a : ''\n if (!text || !/^\\d+(\\.\\d+)?$/.test(text) || !v.currency) return null\n return { amount: text.includes('.') ? text : `${text}.00`, currency_code: v.currency }\n}\n\nexport type PaymentOutcome = {\n kind: PaymentOutcomeKind\n /** Text for the buyer (no codes). */\n message: string\n decline_code: DeclineCode | null\n /** `true` when the buyer can try again with the checkout still open. */\n retryable: boolean\n /** https-only. */\n redirect_url: string | null\n challenge: { url: string | null; creq: string | null } | null\n voucher: PaymentOutcomeVoucher | null\n attempts_left: number | null\n /** What to do next (server value, or derived from the decline code): fix the card, use another, rebuild the cart... */\n next_step: PaymentNextStep | null\n}\n\n/**\n * Classifies an attempt result. Unknown statuses are treated as `in_review`\n * (never as approved, never as a reason to charge again).\n */\nexport function paymentOutcome(result: PaymentAttemptResult, locale?: string | null, overrides?: Partial<PaymentMessages> | null): PaymentOutcome {\n const m = paymentMessages(locale, overrides)\n const p = result.payment\n const action: PaymentAction | null = p.action ?? null\n const base = {\n decline_code: null as DeclineCode | null,\n retryable: false,\n redirect_url: null as string | null,\n challenge: null as PaymentOutcome['challenge'],\n voucher: null as PaymentOutcome['voucher'],\n attempts_left: typeof result.attempts_left === 'number' ? result.attempts_left : null,\n next_step: (p.next_step ?? null) as PaymentNextStep | null,\n }\n const out = (kind: PaymentOutcomeKind, message: string, extra: Partial<PaymentOutcome> = {}): PaymentOutcome => ({ ...base, kind, message, ...extra })\n\n if (p.status === 'paid') return out('approved', m['state.approved'])\n if (p.status === 'failed') {\n const code = p.decline_code ?? 'declined'\n const known: DeclineCode = DECLINE_CODES.has(code) ? code : 'declined'\n return out('rejected', m[declineMessageKey(code)], {\n decline_code: known,\n next_step: p.next_step ?? NEXT_STEP[known],\n retryable: p.retryable !== false && base.attempts_left !== 0,\n })\n }\n if (p.status === 'expired') return out('expired', m['state.expired'], { next_step: 'rebuild_cart' })\n if (p.status === 'cancelled') return out('cancelled', m['state.cancelled'], { retryable: true, next_step: 'rebuild_cart' })\n\n if (action?.type === 'redirect') {\n const url = safeHttpsUrl(action.redirect_url)\n if (url) return out('redirect', m['state.redirect'], { redirect_url: url })\n }\n if (p.status === 'requires_action' || p.status === 'pending') {\n if (action?.type === 'voucher' && action.voucher) {\n const { amount: _a, currency: _c, voucher_url, ...rest } = action.voucher\n return out('voucher', m['state.voucher'], {\n next_step: 'pay_cash',\n voucher: { ...rest, voucher_url: safeHttpsUrl(voucher_url), amount: voucherMoney(action.voucher) },\n })\n }\n if (action?.type === 'challenge' && action.challenge) {\n return out('challenge', m['state.challenge'], {\n challenge: { url: safeHttpsUrl(action.challenge.url), creq: typeof action.challenge.creq === 'string' ? action.challenge.creq : null },\n })\n }\n }\n return out('in_review', m['state.in_review'])\n}\n\n/** Failures of `POST /payment` the form maps to a specific text and next step. */\nexport type PaymentErrorKind =\n | 'network' // no answer: retry with the SAME attempt (idempotent)\n | 'price_mismatch' // total changed: show it, remount, pay again with a NEW attempt\n | 'payment_in_progress' // 409 payment_in_progress: another attempt is paid/pending: do not retry\n | 'expired' // 409: reservation expired\n | 'too_many_attempts' // 429\n | 'generic'\n\nexport type PaymentErrorView = { kind: PaymentErrorKind; message: string; retrySameAttempt: boolean; canRetry: boolean }\n\n/**\n * Maps a transport error (a `StorefrontError` or anything with `status`/`code`)\n * to a view. Network failures and 502/503/504 are safe to retry with the same\n * idempotency key; 409/422/429 are answers, not outages.\n */\nexport function paymentErrorView(err: unknown, locale?: string | null, overrides?: Partial<PaymentMessages> | null): PaymentErrorView {\n const m = paymentMessages(locale, overrides)\n const e = (err ?? {}) as Partial<StorefrontError> & { status?: number; code?: string }\n const status = typeof e.status === 'number' ? e.status : 0\n const code = typeof e.code === 'string' ? e.code : ''\n if (code === 'price_mismatch') {\n return { kind: 'price_mismatch', message: m['error.price_mismatch'], retrySameAttempt: false, canRetry: true }\n }\n if (status === 409 && code === 'expired') return { kind: 'expired', message: m['error.expired'], retrySameAttempt: false, canRetry: false }\n if (status === 409 && code === 'payment_in_progress') {\n return { kind: 'payment_in_progress', message: m['error.payment_in_progress'], retrySameAttempt: false, canRetry: false }\n }\n // 409 conflict: that Idempotency-Key was already used with a DIFFERENT payment (e.g. a new card after a reload).\n // Not an outage and not \"in progress\": start a new attempt.\n if (status === 409) return { kind: 'generic', message: m['error.generic'], retrySameAttempt: false, canRetry: true }\n if (status === 429 || code === 'too_many_attempts') {\n return { kind: 'too_many_attempts', message: m['error.too_many_attempts'], retrySameAttempt: false, canRetry: false }\n }\n // What OPS declared wins over the status: `retryable:false` is an answer (generic), any other 5xx (also a 500 with no readable body) is an outage whose charge may have happened: same key.\n const declared = (e as { retryable?: unknown }).retryable\n if (status >= 500 && declared === false) return { kind: 'generic', message: m['error.generic'], retrySameAttempt: false, canRetry: true }\n if (status === 0 || status === 502 || status === 503 || status === 504 || code === 'network' || code === 'timeout' || status >= 500) {\n return { kind: 'network', message: m['error.network'], retrySameAttempt: true, canRetry: true }\n }\n return { kind: 'generic', message: m['error.generic'], retrySameAttempt: false, canRetry: true }\n}\n\n/** `Vence el 5 de noviembre de 2026, 18:00` style text for a voucher deadline; `null` when absent or invalid. */\nexport function formatVoucherExpiry(expiresAt: string | null | undefined, locale?: string | null, overrides?: Partial<PaymentMessages> | null): string | null {\n if (!expiresAt) return null\n const d = new Date(expiresAt)\n if (Number.isNaN(d.getTime())) return null\n let date: string\n try {\n date = new Intl.DateTimeFormat(locale ?? undefined, { dateStyle: 'long', timeStyle: 'short' }).format(d)\n } catch {\n date = d.toISOString()\n }\n return formatAvailabilityMessage(paymentMessages(locale, overrides)['voucher.expires'], { date })\n}\n\n/** Builds an idempotency key for a payment attempt: the same attempt always yields the same key. */\nexport function paymentIdempotencyKey(checkoutId: string, attempt: string): string {\n return `pay-${checkoutId}-${attempt}`\n}\n","/**\n * Promotion presentation: turns `Cart.promotions` (computed by OPS) into the\n * labels and bar states a storefront shows. Pure functions, no DOM.\n *\n * The shop never computes a discount here: `remaining`, `percent`, `reached`\n * and `percent_of_max` are the server's. The only arithmetic is clamping a\n * server percentage into 0-100 for `aria-valuenow`.\n */\nimport { availabilityLocale, formatAvailabilityMessage, type AvailabilityLocale } from './availability.js'\nimport { formatMoney } from './money.js'\nimport type { CartPromotions, Money, PromotionReward } from './types.js'\n\nexport type PromotionLocale = AvailabilityLocale\n\nexport type PromotionMessageKey =\n | 'discount.next'\n | 'discount.next_upgrade'\n | 'discount.applied'\n | 'discount.max'\n | 'discount.suppressed'\n | 'discount.unlocks'\n | 'discount.remaining'\n | 'shipping.progress'\n | 'shipping.reached'\n | 'shipping.always'\n | 'reward.free_shipping'\n | 'bar.discount'\n | 'bar.shipping'\n | 'popup.close'\n | 'popup.valid_until'\n | 'popup.limited_time'\n | 'popup.discount_tier'\n | 'popup.free_shipping_min'\n | 'popup.free_shipping_always'\n | 'upsell.title'\n | 'upsell.subtitle'\n | 'upsell.next_level'\n | 'upsell.you_miss'\n | 'upsell.unlocks_reward'\n | 'upsell.total_saved'\n | 'upsell.current_benefit'\n | 'upsell.status'\n | 'upsell.status_pending'\n | 'upsell.status_active'\n | 'upsell.next_reward'\n | 'upsell.suggestions'\n | 'upsell.add'\n | 'upsell.adding'\n | 'upsell.flavor'\n | 'upsell.unlocks_badge'\n | 'upsell.unlocked'\n | 'upsell.best'\n | 'upsell.skip'\n | 'upsell.continue'\n | 'upsell.footer'\n | 'upsell.sold_out'\n | 'upsell.error'\n | 'note.label'\n | 'note.placeholder'\n | 'note.save'\n | 'note.saving'\n | 'note.saved'\n | 'note.error'\n | 'note.counter'\n\nexport type PromotionMessages = Record<PromotionMessageKey, string>\n\nconst ES: PromotionMessages = {\n 'discount.next': 'Añade {remaining} para activar tu descuento automático',\n 'discount.next_upgrade': 'Añade {remaining} para subir a {reward}',\n 'discount.applied': '¡Tienes {reward} de descuento!',\n 'discount.max': '¡Tienes {reward} de descuento, el máximo!',\n 'discount.suppressed': 'Tu código de descuento ya te da un mejor precio.',\n 'discount.unlocks': 'Desbloqueas {reward} de descuento',\n 'discount.remaining': 'Te faltan {remaining}',\n 'shipping.progress': 'Añade {remaining} para envío gratis',\n 'shipping.reached': '¡Felicidades! Tienes envío gratis',\n 'shipping.always': 'Envío gratis en todo tu pedido',\n 'reward.free_shipping': 'Envío gratis',\n 'bar.discount': 'Progreso del descuento automático',\n 'bar.shipping': 'Progreso del envío gratis',\n 'popup.close': 'Cerrar',\n 'popup.valid_until': 'Válido hasta el {date}',\n 'popup.limited_time': 'Por tiempo limitado',\n 'popup.discount_tier': '{reward} comprando {threshold}',\n 'popup.free_shipping_min': 'Envío gratis desde {threshold}',\n 'popup.free_shipping_always': 'Envíos gratis sin mínimo de compra',\n 'upsell.title': 'Completa tu compra y desbloquea más',\n 'upsell.subtitle': 'Descuento automático',\n 'upsell.next_level': 'Siguiente nivel',\n 'upsell.you_miss': 'Te faltan {remaining}',\n 'upsell.unlocks_reward': 'Desbloqueas {reward} de descuento',\n 'upsell.total_saved': 'Total ahorrado',\n 'upsell.current_benefit': 'Beneficio actual',\n 'upsell.status': 'Estado',\n 'upsell.status_pending': 'Pendiente',\n 'upsell.status_active': 'Activo',\n 'upsell.next_reward': 'Siguiente recompensa {reward} · {threshold}',\n 'upsell.suggestions': 'Suma y desbloquea · Productos que pueden interesarte',\n 'upsell.add': 'Agregar y avanzar +',\n 'upsell.adding': 'Agregando…',\n 'upsell.flavor': 'Sabor',\n 'upsell.unlocks_badge': 'Desbloquea tu {reward}',\n 'upsell.unlocked': '¡Desbloqueaste {reward}!',\n 'upsell.best': 'Tienes el mejor descuento: {reward}',\n 'upsell.skip': 'Continuar sin agregar',\n 'upsell.continue': 'Continuar al pago',\n 'upsell.footer': 'Tu mejor descuento se aplica automáticamente',\n 'upsell.sold_out': 'Se agotó este sabor, elige otro.',\n 'upsell.error': 'No pudimos agregarlo. Intenta de nuevo.',\n 'note.label': 'Añadir nota',\n 'note.placeholder': 'Instrucciones para tu pedido',\n 'note.save': 'Guardar nota',\n 'note.saving': 'Guardando…',\n 'note.saved': 'Guardada',\n 'note.error': 'No se pudo guardar la nota. Intenta de nuevo.',\n 'note.counter': '{n} de {max} caracteres',\n}\n\nconst EN: PromotionMessages = {\n 'discount.next': 'Add {remaining} to unlock your automatic discount',\n 'discount.next_upgrade': 'Add {remaining} to move up to {reward}',\n 'discount.applied': 'You have {reward} off!',\n 'discount.max': 'You have {reward} off, the maximum!',\n 'discount.suppressed': 'Your discount code already gives you a better price.',\n 'discount.unlocks': 'Unlock {reward} off',\n 'discount.remaining': '{remaining} to go',\n 'shipping.progress': 'Add {remaining} for free shipping',\n 'shipping.reached': 'Congratulations! You get free shipping',\n 'shipping.always': 'Free shipping on your whole order',\n 'reward.free_shipping': 'Free shipping',\n 'bar.discount': 'Automatic discount progress',\n 'bar.shipping': 'Free shipping progress',\n 'popup.close': 'Close',\n 'popup.valid_until': 'Valid until {date}',\n 'popup.limited_time': 'Limited time',\n 'popup.discount_tier': '{reward} when you spend {threshold}',\n 'popup.free_shipping_min': 'Free shipping from {threshold}',\n 'popup.free_shipping_always': 'Free shipping, no minimum purchase',\n 'upsell.title': 'Complete your purchase and unlock more',\n 'upsell.subtitle': 'Automatic discount',\n 'upsell.next_level': 'Next level',\n 'upsell.you_miss': '{remaining} to go',\n 'upsell.unlocks_reward': 'Unlock {reward} off',\n 'upsell.total_saved': 'Total saved',\n 'upsell.current_benefit': 'Current benefit',\n 'upsell.status': 'Status',\n 'upsell.status_pending': 'Pending',\n 'upsell.status_active': 'Active',\n 'upsell.next_reward': 'Next reward {reward} · {threshold}',\n 'upsell.suggestions': 'Add and unlock · Products you may like',\n 'upsell.add': 'Add and move up +',\n 'upsell.adding': 'Adding…',\n 'upsell.flavor': 'Flavor',\n 'upsell.unlocks_badge': 'Unlocks your {reward}',\n 'upsell.unlocked': 'You unlocked {reward}!',\n 'upsell.best': 'You have the best discount: {reward}',\n 'upsell.skip': 'Continue without adding',\n 'upsell.continue': 'Continue to payment',\n 'upsell.footer': 'Your best discount is applied automatically',\n 'upsell.sold_out': 'This flavor sold out, pick another one.',\n 'upsell.error': 'We could not add it. Please try again.',\n 'note.label': 'Add a note',\n 'note.placeholder': 'Instructions for your order',\n 'note.save': 'Save note',\n 'note.saving': 'Saving…',\n 'note.saved': 'Saved',\n 'note.error': 'The note could not be saved. Please try again.',\n 'note.counter': '{n} of {max} characters',\n}\n\nconst CATALOG: Record<PromotionLocale, PromotionMessages> = { es: ES, en: EN }\n\n/** Catalog for a locale with the shop's per-key overrides applied. */\nexport function promotionMessages(locale: string | null | undefined, overrides?: Partial<PromotionMessages> | null): PromotionMessages {\n const base = CATALOG[availabilityLocale(locale)]\n if (!overrides) return base\n const out = { ...base }\n for (const [k, v] of Object.entries(overrides)) if (typeof v === 'string' && k in base) out[k as PromotionMessageKey] = v\n return out\n}\n\n/** Order-note limit enforced by the server (`validateNote`). */\nexport const NOTE_MAX_LENGTH = 1000\n\n/** Trims and caps a note; empty becomes `null` (the server clears the note). */\nexport function normalizeNote(note: string | null | undefined): string | null {\n const t = (note ?? '').trim()\n return t ? t.slice(0, NOTE_MAX_LENGTH) : null\n}\n\n/** `5 %` / `7.5 %` (es) or `5%` (en) / `$250` / `Envío gratis`. The values are the server's. */\nexport function rewardLabel(reward: PromotionReward, locale?: string | null, overrides?: Partial<PromotionMessages> | null): string {\n const m = promotionMessages(locale, overrides)\n if (reward.kind === 'free_shipping') return m['reward.free_shipping']\n if (reward.kind === 'fixed') return formatMoney(reward.amount, locale ?? undefined, { withoutTrailingZeros: true })\n const n = Number.parseFloat(reward.percent)\n let num = reward.percent\n try {\n if (Number.isFinite(n)) num = new Intl.NumberFormat(locale ?? undefined, { maximumFractionDigits: 4 }).format(n)\n } catch {\n /* keep the raw text */\n }\n return availabilityLocale(locale) === 'en' ? `${num}%` : `${num} %`\n}\n\n/** Display clamp for a server percentage (`aria-valuenow`). Not a calculation. */\nexport function clampPercent(value: unknown): number {\n const n = typeof value === 'number' ? value : Number.parseFloat(String(value))\n if (!Number.isFinite(n)) return 0\n return Math.min(100, Math.max(0, Math.round(n)))\n}\n\nexport type DiscountBarState = 'next' | 'upgrade' | 'max' | 'suppressed'\n\nexport type DiscountBarView = {\n state: DiscountBarState\n /** Server progress 0-100. */\n percent: number\n text: string\n /** `aria-valuetext`. */\n valueText: string\n remaining: Money | null\n /** Reward of the next tier (or the applied one at max). */\n rewardText: string | null\n appliedText: string | null\n nextText: string | null\n tiers: { id: string; label: string; threshold: string; reached: boolean; position: number }[]\n}\n\nexport type ShippingBarState = 'progress' | 'reached' | 'always'\n\nexport type ShippingBarView = {\n state: ShippingBarState\n percent: number\n text: string\n valueText: string\n remaining: Money | null\n /** `false` for `always`: there is nothing to fill. */\n showBar: boolean\n}\n\nexport type PromoProgressView = { discount: DiscountBarView | null; shipping: ShippingBarView | null }\n\nconst fmt = (money: Money, locale?: string | null) => formatMoney(money, locale ?? undefined, { withoutTrailingZeros: true })\n\n/**\n * Bars of the cart and the pre-payment modal. Both read the same `Cart.promotions`,\n * so they can never disagree. `null`/absent promotions give `{ discount: null, shipping: null }`.\n */\nexport function promoProgressView(\n promotions: CartPromotions | null | undefined,\n locale?: string | null,\n overrides?: Partial<PromotionMessages> | null,\n): PromoProgressView {\n if (!promotions) return { discount: null, shipping: null }\n const m = promotionMessages(locale, overrides)\n const f = (tpl: string, vars: Record<string, string>) => formatAvailabilityMessage(tpl, vars)\n\n let discount: DiscountBarView | null = null\n const hasTiers = promotions.tiers.length > 0 || promotions.next_tier !== null || promotions.applied !== null\n if (hasTiers) {\n const next = promotions.next_tier\n const applied = promotions.applied\n const appliedReward = applied ? rewardLabel(applied.reward, locale, overrides) : null\n let state: DiscountBarState\n let text: string\n if (promotions.suppressed?.reason === 'code_better' && !applied) {\n state = 'suppressed'\n text = m['discount.suppressed']\n } else if (!next) {\n state = 'max'\n text = appliedReward ? f(m['discount.max'], { reward: appliedReward }) : m['discount.suppressed']\n } else if (applied) {\n state = 'upgrade'\n text = f(m['discount.next_upgrade'], { remaining: fmt(next.remaining, locale), reward: rewardLabel(next.reward, locale, overrides) })\n } else {\n state = 'next'\n text = f(m['discount.next'], { remaining: fmt(next.remaining, locale) })\n }\n discount = {\n state,\n percent: clampPercent(promotions.percent_of_max),\n text,\n valueText: text,\n remaining: next?.remaining ?? null,\n rewardText: next ? rewardLabel(next.reward, locale, overrides) : appliedReward,\n appliedText: appliedReward ? f(m['discount.applied'], { reward: appliedReward }) : null,\n nextText: next ? f(m['discount.unlocks'], { reward: rewardLabel(next.reward, locale, overrides) }) : null,\n tiers: promotions.tiers.map((t) => ({\n id: t.id,\n label: rewardLabel(t.reward, locale, overrides),\n threshold: fmt(t.threshold, locale),\n reached: t.reached,\n position: clampPercent(t.percent_of_max),\n })),\n }\n }\n\n let shipping: ShippingBarView | null = null\n const fs = promotions.free_shipping\n if (fs) {\n const noMinimum = Number.parseFloat(fs.threshold.amount) === 0\n if (noMinimum) {\n shipping = { state: 'always', percent: 100, text: m['shipping.always'], valueText: m['shipping.always'], remaining: null, showBar: false }\n } else if (fs.reached) {\n shipping = { state: 'reached', percent: 100, text: m['shipping.reached'], valueText: m['shipping.reached'], remaining: null, showBar: true }\n } else {\n const text = f(m['shipping.progress'], { remaining: fmt(fs.remaining, locale) })\n shipping = { state: 'progress', percent: clampPercent(fs.percent), text, valueText: text, remaining: fs.remaining, showBar: true }\n }\n }\n return { discount, shipping }\n}\n","/**\n * Detección de mercado por visita (país + idioma), pura y sin DOM: sirve en el servidor de cualquier tienda.\n *\n * Reglas (mejores prácticas de i18n para comercio):\n * - El mercado canónico lo fija el DOMINIO (OPS liga cada dominio verificado a un mercado: org_domains.market_code).\n * Esto no lo decide la geolocalización: así cada URL tiene un solo idioma/moneda (SEO, hreflang, caché de CDN).\n * - La geolocalización solo SUGIERE (banner \"¿Ver la tienda de Estados Unidos?\"); nunca redirige sola, nunca a rastreadores\n * y respeta la elección guardada del comprador.\n * - Precios, impuestos y envío NO dependen de la IP: dependen del mercado del dominio y de la dirección de entrega.\n * - El país sale de las cabeceras que pone el CDN/proxy (no se puede confiar en ellas si el servidor está expuesto\n * directo a internet: solo se leen con `trustProxy`).\n */\n\nexport type MarketInfo = {\n /** Código del mercado en OPS (\"mx\", \"us\"). */\n code: string\n /** ISO 3166-1 alfa-2 a los que vende. */\n countries: string[]\n /** BCP 47 por defecto (\"es-MX\", \"en-US\"). */\n locale: string\n /** ISO 4217 (\"MXN\", \"USD\"). */\n currency: string\n /** Dominio público del mercado, si es distinto del actual (\"godsnutrition.com\"). */\n host?: string\n}\n\n/** Cabeceras de país de los CDN/proxies más comunes, en orden de preferencia. */\nexport const COUNTRY_HEADERS = ['cf-ipcountry', 'cloudfront-viewer-country', 'x-vercel-ip-country', 'x-appengine-country', 'x-country-code'] as const\n\nconst BOT = /bot|crawl|spider|slurp|bing|facebookexternalhit|embedly|preview|lighthouse|headless|curl|wget/i\n\n/** País del visitante según el CDN. `null` si no viene, es desconocido (XX), Tor (T1) o no es ISO alfa-2. */\nexport function visitorCountry(headers: Headers, { trustProxy = true }: { trustProxy?: boolean } = {}): string | null {\n if (!trustProxy) return null\n for (const name of COUNTRY_HEADERS) {\n const value = headers.get(name)?.trim().toUpperCase()\n if (value && /^[A-Z]{2}$/.test(value) && value !== 'XX' && value !== 'T1') return value\n }\n return null\n}\n\n/** Idiomas de Accept-Language ordenados por q (mayor primero), en minúsculas. */\nexport function preferredLanguages(acceptLanguage: string | null | undefined): string[] {\n if (!acceptLanguage) return []\n return acceptLanguage\n .split(',')\n .map((part, index) => {\n const [tag = '', ...params] = part.trim().split(';')\n const q = Number(params.find((p) => p.trim().startsWith('q='))?.split('=')[1] ?? 1)\n return { tag: tag.trim().toLowerCase(), q: Number.isFinite(q) ? q : 0, index }\n })\n .filter((l) => l.tag && l.tag !== '*' && l.q > 0)\n .sort((a, b) => b.q - a.q || a.index - b.index)\n .map((l) => l.tag)\n}\n\n/** Mejor idioma entre los que ofrece la tienda: coincidencia exacta, luego por idioma base; si no, el de `fallback`. */\nexport function negotiateLocale(acceptLanguage: string | null | undefined, available: string[], fallback: string): string {\n const lowered = new Map(available.map((l) => [l.toLowerCase(), l]))\n for (const wanted of preferredLanguages(acceptLanguage)) {\n const exact = lowered.get(wanted)\n if (exact) return exact\n const base = wanted.split('-')[0]\n const sameBase = available.find((l) => l.toLowerCase().split('-')[0] === base)\n if (sameBase) return sameBase\n }\n return fallback\n}\n\nexport type MarketSuggestion = {\n market: MarketInfo\n /** Qué disparó la sugerencia. El país manda; el idioma solo si el CDN no dio país. */\n reason: 'country' | 'language'\n}\n\n/**\n * ¿Conviene sugerir otro mercado a esta visita? `null` si no (ya está en el correcto, rastreador, ya eligió, o no hay otro).\n * `chosen` es el código que el comprador guardó al elegir a mano (\"market\" en cookie): si existe, no se vuelve a sugerir.\n */\nexport function suggestMarket({\n headers,\n markets,\n current,\n chosen,\n trustProxy = true,\n}: {\n headers: Headers\n markets: MarketInfo[]\n current: string\n chosen?: string | null\n trustProxy?: boolean\n}): MarketSuggestion | null {\n if (chosen || markets.length < 2) return null\n if (BOT.test(headers.get('user-agent') ?? '')) return null\n\n const country = visitorCountry(headers, { trustProxy })\n if (country) {\n const target = markets.find((m) => m.countries.includes(country))\n return target && target.code !== current ? { market: target, reason: 'country' } : null\n }\n // Sin país del CDN: la región del idioma del navegador (\"en-US\" → US), solo como pista débil.\n for (const tag of preferredLanguages(headers.get('accept-language'))) {\n const region = tag.split('-')[1]?.toUpperCase()\n if (!region) continue\n const target = markets.find((m) => m.countries.includes(region))\n if (target) return target.code !== current ? { market: target, reason: 'language' } : null\n }\n return null\n}\n\n/**\n * Enlaces `hreflang` para <head>: un alterno por mercado con dominio propio, más x-default (el mercado por defecto).\n * `path` es la ruta con query actual (\"/productos/x\"). Es lo que permite a buscadores servir cada país en su idioma.\n */\nexport function hreflangLinks(markets: MarketInfo[], path: string, defaultMarket: string, protocol = 'https'): { hrefLang: string; href: string }[] {\n const links = markets\n .filter((m) => m.host)\n .map((m) => ({ hrefLang: m.locale, href: `${protocol}://${m.host}${path}` }))\n const fallback = markets.find((m) => m.code === defaultMarket && m.host)\n if (fallback) links.push({ hrefLang: 'x-default', href: `${protocol}://${fallback.host}${path}` })\n return links\n}\n","/**\n * Pure helpers over an `Order` (contract 1.8): the unified progress, the one next action, shipment ordering and the\n * \"test\" rules. They READ what the server sent and only derive what an older server (no `progress` / `next_action`)\n * did not. Every enum is open: an unknown stage, step state or shipment status never throws, it is kept as is and the\n * UI shows its safe fallback.\n */\nimport { safeHttpsUrl } from './payments.js'\nimport type {\n InvoiceDoc,\n NextAction,\n Order,\n OrderProblem,\n OrderProgress,\n OrderProgressStep,\n OrderStage,\n OrderStepKey,\n Shipment,\n ShipmentEvent,\n ShipmentStatus,\n} from './types.js'\n\n/** Steps of an order that ships, in order. */\nexport const SHIPPING_STEPS = ['paid', 'preparing', 'shipped', 'in_transit', 'delivered'] as const\n/** Steps of an order the buyer picks up. */\nexport const PICKUP_STEPS = ['paid', 'preparing', 'ready_for_pickup', 'delivered'] as const\n\n/** Shipment statuses that mean the package is not where it should be. */\nconst SHIPMENT_PROBLEMS: Record<string, string> = { exception: 'delivery_exception', returned: 'returned', lost: 'lost' }\n\nconst RANK: Record<string, number> = { pending: 0, label_created: 1, in_transit: 2, out_for_delivery: 3, delivered: 4 }\n\nconst isRecord = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v)\n\n/** A shipment the buyer can be told about as real: not a sandbox one. */\nexport function isTestShipment(s: Pick<Shipment, 'test_mode' | 'environment'> | null | undefined): boolean {\n return !!s && (s.test_mode === true || s.environment === 'sandbox')\n}\n\n/** An invoice or credit note from a sandbox PAC. */\nexport function isTestInvoice(d: Pick<InvoiceDoc, 'test_mode' | 'environment'> | null | undefined): boolean {\n return !!d && (d.test_mode === true || d.environment === 'sandbox')\n}\n\n/** `https` URL with no credentials, or `null`. The only kind of link a tracking or voucher button may carry. */\nexport function safeTrackingUrl(value: unknown): string | null {\n return safeHttpsUrl(value)\n}\n\nfunction time(iso: string | null | undefined): number {\n const t = iso ? Date.parse(iso) : NaN\n return Number.isNaN(t) ? -Infinity : t\n}\n\n/** Newest first, invalid dates last, ties keep the server's order; at most `limit` (default 50, the contract's cap). */\nexport function sortTrackingEvents(events: readonly ShipmentEvent[] | null | undefined, limit = 50): ShipmentEvent[] {\n if (!Array.isArray(events)) return []\n return events\n .filter(isRecord as (e: unknown) => e is ShipmentEvent)\n .map((e, i) => ({ e, i }))\n .sort((a, b) => time(b.e.occurred_at) - time(a.e.occurred_at) || a.i - b.i)\n .slice(0, Math.max(0, limit))\n .map((x) => x.e)\n}\n\n/** The shipments of the order that count: outbound/pickup/local first, returns after; stable otherwise. */\nexport function orderShipments(order: Pick<Order, 'shipments'> | null | undefined): Shipment[] {\n const list = Array.isArray(order?.shipments) ? order!.shipments!.filter(isRecord as (s: unknown) => s is Shipment) : []\n return [...list.filter((s) => s.kind !== 'return'), ...list.filter((s) => s.kind === 'return')]\n}\n\nfunction validProgress(p: unknown): p is OrderProgress {\n return isRecord(p) && typeof p.stage === 'string' && Array.isArray(p.steps)\n}\n\nconst validStep = (s: unknown): s is OrderProgressStep => isRecord(s) && typeof s.key === 'string' && typeof s.state === 'string'\n\n/** The server's progress with anything malformed dropped: a bad step or problem never reaches the UI. */\nfunction cleanProgress(p: OrderProgress): OrderProgress {\n if (p.steps.every(validStep) && (p.problem === undefined || p.problem === null || (isRecord(p.problem) && typeof p.problem.code === 'string'))) return p\n const problem = isRecord(p.problem) && typeof p.problem.code === 'string' ? p.problem : null\n return { stage: p.stage, problem, steps: p.steps.filter(validStep) }\n}\n\n/** Shipments that tell the buyer something real about delivery: not returns, not sandbox. */\nconst liveShipments = (shipments: Shipment[]) => shipments.filter((s) => s.kind !== 'return' && !isTestShipment(s))\n\n/** The stage of an order from its legacy `status` / `payment_status` and its shipments (servers before contract 1.8). */\nfunction legacyStage(order: Order, shipments: Shipment[]): OrderStage {\n const status = typeof order.status === 'string' ? order.status.toLowerCase() : ''\n const pickup = order.delivery_method === 'pickup'\n if (status === 'cancelled' || status === 'canceled') return 'cancelled'\n if (status === 'refunded') return 'refunded'\n if (status === 'pending_payment' || order.payment_status === 'pending') return 'pending_payment'\n if (status === 'delivered' || status === 'fulfilled') return 'delivered'\n // The order is as far as its LEAST advanced live shipment (a partial delivery is not a delivered order); cancelled\n // legs and legs with a problem (flagged apart) do not hold it back. Same rule as the server.\n const live = liveShipments(shipments)\n const ranked = live.filter((s) => RANK[s.status] !== undefined)\n const least = ranked.reduce<string | null>((acc, s) => (acc === null || RANK[s.status]! < RANK[acc]! ? s.status : acc), null)\n if (least === 'delivered') return 'delivered'\n if (least === 'out_for_delivery') return 'out_for_delivery'\n if (least === 'in_transit') return 'in_transit'\n if (status === 'ready_for_pickup' || (status === 'ready' && pickup)) return 'ready_for_pickup'\n // A `shipped` status whose every shipment is a sandbox one: the package is not really on its way.\n const onlySandbox = shipments.some((s) => s.kind !== 'return') && live.length === 0\n if ((status === 'shipped' && !onlySandbox) || least === 'label_created') return 'shipped'\n if (status === 'fulfilling' || status === 'accepted' || status === 'ready' || status === 'shipped') return 'preparing'\n return 'paid'\n}\n\nconst STAGE_TO_STEP: Record<string, OrderStepKey> = {\n paid: 'paid',\n preparing: 'preparing',\n ready_for_pickup: 'ready_for_pickup',\n shipped: 'shipped',\n in_transit: 'in_transit',\n out_for_delivery: 'in_transit',\n delivered: 'delivered',\n}\n\n/** When the payment was confirmed (not when the order was placed: a cash voucher is paid days later), or `null`. */\nfunction paidAt(order: Order): string | null {\n const paid = Array.isArray(order.payments) ? order.payments.find((p) => isRecord(p) && typeof p.paid_at === 'string' && p.paid_at) : undefined\n return paid?.paid_at ?? null\n}\n\n/**\n * The unified progress. The server's `order.progress` wins when it is well formed; otherwise it is derived, so a store\n * on an older OPS still gets a timeline. Pending payment, cancelled and refunded orders have no steps to walk: `steps`\n * lists them as `pending` (or `[]` when cancelled/refunded) and the stage says why.\n */\nexport function orderProgress(order: Order): OrderProgress {\n if (validProgress(order.progress)) return cleanProgress(order.progress)\n const shipments = orderShipments(order)\n const stage = legacyStage(order, shipments)\n const keys: readonly string[] = order.delivery_method === 'pickup' ? PICKUP_STEPS : SHIPPING_STEPS\n const dead = stage === 'cancelled' || stage === 'refunded'\n const awaiting = stage === 'pending_payment'\n const current = STAGE_TO_STEP[stage] ?? 'paid'\n const at = keys.indexOf(current)\n const failed = liveShipments(shipments).find((s) => SHIPMENT_PROBLEMS[s.status])\n const problem: OrderProblem | null = failed\n ? { code: SHIPMENT_PROBLEMS[failed.status]!, at: sortTrackingEvents(failed.events)[0]?.occurred_at ?? null }\n : order.payment_status === 'failed'\n ? { code: 'payment_failed' }\n : null\n const steps: OrderProgressStep[] = dead\n ? []\n : keys.map((key, i) => {\n if (awaiting) return { key, state: 'pending', at: null }\n const state = i < at || stage === 'delivered' ? 'done' : i === at ? (problem && i >= keys.indexOf('shipped') ? 'problem' : 'current') : 'pending'\n return { key, state, at: key === 'paid' && state === 'done' ? paidAt(order) : null }\n })\n return { stage, problem, steps }\n}\n\n/**\n * The action to put first. The server's `next_action` wins (its `href` is re-checked: only `https`); an older server\n * gets one derived from the order and its invoice. Never `null`: `{ kind: 'none' }` means \"nothing to offer\".\n */\nexport function nextAction(order: Order): NextAction {\n // A 1.8 server that sends `next_action: null` means \"nothing to offer\"; only an older server (no key) is derived.\n if (order.next_action === null) return { kind: 'none', href: null, ref: null }\n if (isRecord(order.next_action) && typeof order.next_action.kind === 'string') {\n const href = safeTrackingUrl(order.next_action.href)\n return { kind: order.next_action.kind, href, ref: typeof order.next_action.ref === 'string' ? order.next_action.ref : null }\n }\n const progress = orderProgress(order)\n if (progress.stage === 'pending_payment') return { kind: 'pay', href: null, ref: null }\n if (progress.stage === 'cancelled' || progress.stage === 'refunded') return { kind: 'none', href: null, ref: null }\n const live = orderShipments(order).find((s) => s.kind !== 'return' && !isTestShipment(s) && s.status !== 'delivered' && s.status !== 'cancelled')\n const trackUrl = safeTrackingUrl(live?.tracking_url)\n if (live && trackUrl) return { kind: 'track', href: trackUrl, ref: live.id }\n if (progress.stage === 'ready_for_pickup') return { kind: 'pickup', href: null, ref: null }\n const inv = isRecord(order.invoice) ? order.invoice : undefined\n // The server's `action` wins over the stage: an issued invoice it does not offer (no file yet) is not a button.\n if (inv?.action === 'download' || (inv?.action === undefined && inv?.stage === 'issued')) {\n const docs = Array.isArray(order.invoices) ? order.invoices.filter((d) => isRecord(d) && d.kind === 'invoice' && d.status !== 'cancelled') : []\n const real = docs.find((d) => !isTestInvoice(d))\n // Detail with only sandbox invoices: never offer one as the buyer's invoice.\n if (docs.length === 0 || real) return { kind: 'download_invoice', href: null, ref: real?.id ?? null }\n }\n if (inv?.action === 'correct_data') return { kind: 'correct_invoice_data', href: null, ref: null }\n if (inv?.action === 'contact_store') return { kind: 'contact_store', href: null, ref: null }\n if (inv?.can_request === true && inv.stage !== 'requested') return { kind: 'request_invoice', href: null, ref: null }\n return { kind: 'none', href: null, ref: null }\n}\n\n/** Latest known status among the live (non-sandbox, non-return) shipments, or `null`. */\nexport function shipmentsStatus(order: Order): ShipmentStatus | null {\n if (order.shipments_summary && typeof order.shipments_summary.status === 'string') return order.shipments_summary.status\n const live = orderShipments(order).filter((s) => s.kind !== 'return' && !isTestShipment(s))\n return live.length ? live[0]!.status : null\n}\n","import type { StorefrontError } from './errors.js'\n\n/**\n * Account settings of the buyer (contract 1.9): active sessions, recent re-authentication, language and\n * notification preferences, data export and account deletion. Types and small pure helpers; the calls live on\n * `client.customer`.\n */\n\n/** Notification preferences: event → channel → on. Only optional events can be configured (never the order confirmation or the invoice). */\nexport type CustomerPreferences = {\n notifications?: Record<string, Record<string, boolean>>\n}\n\n/** One session of the buyer for a «Devices» list. The server never sends an address or a token. */\nexport type CustomerSessionInfo = {\n id: string\n /** `true` for the session that made the request. */\n current: boolean\n /** A summary such as «Chrome · Windows». Never a full user agent. */\n device_label: string\n login_method: 'email' | 'phone' | 'password' | (string & {})\n last_used_at?: string | null\n created_at: string\n}\n\n/** What proves the buyer is who they say: the password, or a sign-in code requested with `customer.requestOtp`. Exactly one. */\nexport type ReauthInput = { password: string; otp_code?: never } | { otp_code: string; password?: never }\n\nexport type ReauthResult = {\n reauth_at: string\n /** How long the confirmation lasts (seconds). It applies to the session that made the call, nowhere else. */\n valid_for_seconds?: number\n}\n\n/** The buyer's data as a JSON file, in memory. `content_base64` is the file; serve it as a download and do not keep it. */\nexport type DataExportFile = {\n filename: string\n content_type: string\n content_base64: string\n}\n\n/** `DELETE /customer`. `confirm` is the text your interface asked the buyer to type. */\nexport type AccountDeleteInput = { confirm: string }\n\n/**\n * `true` when a call was refused because the buyer must confirm their password or a code first\n * (`403` with code `reauth_required`): show your confirmation step, call `customer.reauth`, and repeat the call.\n */\nexport function isReauthRequired(error: unknown): error is StorefrontError {\n const e = error as { status?: unknown; code?: unknown } | null\n return !!e && typeof e === 'object' && e.status === 403 && e.code === 'reauth_required'\n}\n\n/**\n * `true` when deleting the account was refused because an order is on its way or a payment is still pending\n * (`409`; `field` says which: `orders` or `pending_payments`).\n */\nexport function isAccountDeleteBlocked(error: unknown): error is StorefrontError & { field: 'orders' | 'pending_payments' } {\n const e = error as { status?: unknown; field?: unknown } | null\n return !!e && typeof e === 'object' && e.status === 409 && (e.field === 'orders' || e.field === 'pending_payments')\n}\n\n/** Decodes `content_base64` of a data export. Throws `TypeError` when it is not valid base64. */\nexport function dataExportBytes(file: Pick<DataExportFile, 'content_base64'>): Uint8Array {\n const raw = typeof file.content_base64 === 'string' ? file.content_base64.replace(/\\s+/g, '') : ''\n if (!/^[A-Za-z0-9+/]*={0,2}$/.test(raw) || raw.length % 4 === 1) throw new TypeError('data export is not valid base64')\n const bin = atob(raw)\n const out = new Uint8Array(bin.length)\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i)\n return out\n}\n\n/** A download filename that is safe in a `Content-Disposition` header: no path, quotes, control characters or spaces. */\nexport function safeExportFilename(name: unknown, fallback = 'account-data.json'): string {\n const base = typeof name === 'string' ? (name.split(/[\\\\/]/).pop() ?? '') : ''\n const clean = base.replace(/[^A-Za-z0-9._-]+/g, '_').replace(/^\\.+/, '').slice(0, 80)\n return clean || fallback\n}\n","/** Invoices and credit notes of an order, and the bytes of a downloaded file. Pure; no URL of the PAC ever passes here. */\nimport type { InvoiceDoc, InvoiceFile } from './types.js'\n\nexport type InvoiceGroup = { invoice: InvoiceDoc; creditNotes: InvoiceDoc[] }\n\n/**\n * Groups credit notes under the invoice they correct (`related_to`), keeping the server's order. A credit note whose\n * invoice is not in the list (or has no `related_to`) is returned in `orphans`, never dropped.\n */\nexport function groupInvoiceDocs(docs: readonly InvoiceDoc[] | null | undefined): { groups: InvoiceGroup[]; orphans: InvoiceDoc[] } {\n const list = Array.isArray(docs) ? docs.filter((d): d is InvoiceDoc => !!d && typeof d === 'object') : []\n const groups: InvoiceGroup[] = list.filter((d) => d.kind !== 'credit_note').map((invoice) => ({ invoice, creditNotes: [] }))\n const orphans: InvoiceDoc[] = []\n for (const d of list) {\n if (d.kind !== 'credit_note') continue\n const group = d.related_to ? groups.find((g) => g.invoice.id === d.related_to) : undefined\n if (group) group.creditNotes.push(d)\n else orphans.push(d)\n }\n return { groups, orphans }\n}\n\n/** Decodes `content_base64` of a downloaded invoice file. Throws `TypeError` when it is not valid base64. */\nexport function invoiceFileBytes(file: Pick<InvoiceFile, 'content_base64'>): Uint8Array {\n const raw = typeof file.content_base64 === 'string' ? file.content_base64.replace(/\\s+/g, '') : ''\n if (!/^[A-Za-z0-9+/]*={0,2}$/.test(raw) || raw.length % 4 === 1) throw new TypeError('invoice file is not valid base64')\n const bin = atob(raw)\n const out = new Uint8Array(bin.length)\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i)\n return out\n}\n\n/** A download filename that is safe in a `Content-Disposition` header: no path, quotes, control characters or spaces. */\nexport function safeInvoiceFilename(name: unknown, fallback = 'factura'): string {\n const base = typeof name === 'string' ? (name.split(/[\\\\/]/).pop() ?? '') : ''\n const clean = base.replace(/[^A-Za-z0-9._-]+/g, '_').replace(/^\\.+/, '').slice(0, 80)\n return clean || fallback\n}\n","// «My items» (contract 1.9): the pure side. The cascade of options a form shows, the same validation the server runs\n// (the server is the authority; this gives the buyer the answer without a round trip), the compatibility key and the\n// product tags it filters with. No UI, no storage, no copy, and no kind is named here: a kind is data the organization\n// publishes (`content.subjectKinds()`), and what a field \"means\" (make, size, breed) is only its label.\n//\n// Privacy: a `private` field (a licence plate) is kept apart. It is never part of `label`, `fit_key` or any tag, and\n// `maskedValue` / `isMasked` are how the server's mask is recognized so it is never sent back as if it were a value.\n\nimport type { SubjectCatalogNode, SubjectField, SubjectKind } from './types.js'\n\nexport const MIN_SUBJECT_YEAR = 1900\nexport const MAX_SUBJECT_YEAR = 2100\nconst MAX_VALUE_LENGTH = 80\nconst MAX_LABEL_LENGTH = 120\nconst MAX_FIT_KEY_LENGTH = 100\n\nexport type SubjectOption = { value: string; label: string }\nexport type SubjectValues = Record<string, string | number | null | undefined>\n\n/** Why a value was refused (the server answers `422` with the field `attributes.<key>` and never the value). */\nexport type SubjectProblemCode = 'required' | 'unknown' | 'invalid' | 'not_in_catalog' | 'year_range' | 'catalog_unavailable'\nexport type SubjectProblems = Record<string, SubjectProblemCode>\n\nexport type ResolvedSubject = {\n /** Built from the labels of the catalog and the public values, in field order. */\n label: string\n /** `''` when a placeholder of the template has no value (the item then never matches a product). */\n fit_key: string\n /** Public values, as the server stores them in `attributes`. */\n attributes: Record<string, string | number>\n /** Private values: never in the label, the key or a tag. */\n private: Record<string, string>\n}\n\nconst isPresent = (v: unknown): boolean => v !== null && v !== undefined && v !== ''\n\nconst asYear = (v: unknown): number | null => {\n const n = typeof v === 'number' ? v : typeof v === 'string' && /^\\s*\\d+\\s*$/.test(v) ? Number(v) : NaN\n return Number.isInteger(n) && n >= MIN_SUBJECT_YEAR && n <= MAX_SUBJECT_YEAR ? n : null\n}\n\n/** Collapses whitespace; `null` for a non-string, a control character or a value over `max` characters. */\nconst cleanText = (v: unknown, max: number): string | null => {\n if (typeof v !== 'string') return null\n const s = v.split(/\\s+/).filter(Boolean).join(' ')\n // eslint-disable-next-line no-control-regex\n return [...s].length > max || /[\\u0000-\\u001f\\u007f-\\u009f]/.test(s) ? null : s\n}\n\nconst slug = (s: string): string => s.toLowerCase().replace(/[^a-z0-9._+-]+/g, '-').replace(/^-+|-+$/g, '')\n\n/** Does the option cover the model year? Declared `ranges` win; else `from`/`to`; an option with none covers any year. */\nexport function coversYear(node: Pick<SubjectCatalogNode, 'from' | 'to' | 'ranges'>, year: number): boolean {\n if (node.ranges && node.ranges.length > 0) return node.ranges.some(([a, b]) => year >= a && year <= b)\n if (node.from !== undefined && year < node.from) return false\n if (node.to !== undefined && year > node.to) return false\n return true\n}\n\nconst declaresYears = (n: SubjectCatalogNode): boolean => n.from !== undefined || n.to !== undefined || (n.ranges?.length ?? 0) > 0\n\n/** The catalog fields that make the tree's levels, in order: `source: catalog` and not a year. */\nexport function subjectLevels(kind: Pick<SubjectKind, 'fields'>): SubjectField[] {\n return kind.fields.filter((f) => f.source === 'catalog' && f.type !== 'year')\n}\n\n/** The visible fields of a form: everything the buyer fills in, in the order of the kind. */\nexport function subjectFields(kind: Pick<SubjectKind, 'fields'>): SubjectField[] {\n return kind.fields\n}\n\n/** Walks the chosen values down the tree; stops at the first level without a (valid) choice. */\nfunction walk(kind: SubjectKind, values: SubjectValues): { path: SubjectCatalogNode[]; ids: Record<string, string>; next: Record<string, SubjectCatalogNode> | undefined } {\n const path: SubjectCatalogNode[] = []\n const ids: Record<string, string> = {}\n let tree: Record<string, SubjectCatalogNode> | undefined = kind.catalog?.tree\n for (const f of subjectLevels(kind)) {\n const raw = values[f.key]\n const s = isPresent(raw) ? cleanText(raw, MAX_VALUE_LENGTH) : null\n const node: SubjectCatalogNode | undefined = s && tree ? (tree[s] ?? tree[s.toLowerCase()]) : undefined\n if (!s || !node) return { path, ids, next: tree }\n ids[f.key] = tree && tree[s] ? s : s.toLowerCase()\n path.push(node)\n tree = node.children\n if (!tree) return { path, ids, next: undefined }\n }\n return { path, ids, next: tree }\n}\n\nconst byLabel = (a: SubjectOption, b: SubjectOption) => a.label.localeCompare(b.label, undefined, { sensitivity: 'base', numeric: true })\n\n/**\n * The options a catalog field offers given what is already chosen (a cascade: a level shows nothing until the previous\n * one is chosen). A level narrows by the chosen year when the option declares years; a year field offers the model\n * years the chosen options cover (newest first), or nothing when no option declares years (a free number then).\n */\nexport function subjectOptions(kind: SubjectKind, fieldKey: string, values: SubjectValues): SubjectOption[] {\n const field = kind.fields.find((f) => f.key === fieldKey)\n if (!field || field.source !== 'catalog' || !kind.catalog) return []\n if (field.type === 'year') {\n // Only the options chosen BEFORE the year constrain it (a stale choice after it is reconciled against the year).\n const upto = kind.fields.slice(0, kind.fields.indexOf(field))\n const { path } = walk({ ...kind, fields: upto }, values)\n const declared = path.filter(declaresYears)\n if (declared.length === 0) return []\n let lo = Infinity\n let hi = -Infinity\n for (const n of declared) {\n for (const [a, b] of n.ranges?.length ? n.ranges : [[n.from ?? MIN_SUBJECT_YEAR, n.to ?? MAX_SUBJECT_YEAR] as [number, number]]) {\n lo = Math.min(lo, a)\n hi = Math.max(hi, b)\n }\n }\n const out: SubjectOption[] = []\n for (let y = Math.min(hi, MAX_SUBJECT_YEAR); y >= Math.max(lo, MIN_SUBJECT_YEAR); y--) if (declared.every((n) => coversYear(n, y))) out.push({ value: String(y), label: String(y) })\n return out\n }\n const levels = subjectLevels(kind)\n const at = levels.findIndex((f) => f.key === fieldKey)\n if (at < 0) return []\n // Only the levels before this one must be chosen.\n const before = Object.fromEntries(levels.slice(0, at).map((f) => [f.key, values[f.key]]))\n const { path, next } = walk({ ...kind, fields: kind.fields.filter((f) => levels.slice(0, at).includes(f) || f.type === 'year') }, before)\n if (path.length < at || !next) return []\n const year = asYear(values[kind.fields.find((f) => f.type === 'year' && f.source === 'catalog')?.key ?? ''])\n return Object.entries(next)\n .filter(([, n]) => year === null || coversYear(n, year))\n .map(([value, n]) => ({ value, label: n.label }))\n .sort(byLabel)\n}\n\n/**\n * Drops what was chosen and is no longer valid after a change (a new make clears the model; a year the model does not\n * cover is cleared), in field order. Free values are never touched.\n */\nexport function reconcileSubjectValues(kind: SubjectKind, values: SubjectValues): SubjectValues {\n const out: SubjectValues = { ...values }\n for (const f of kind.fields) {\n if (f.source !== 'catalog' || !isPresent(out[f.key])) continue\n const options = subjectOptions(kind, f.key, out)\n const v = String(out[f.key])\n const ok = f.type === 'year' ? options.length === 0 || options.some((o) => o.value === v) : options.some((o) => o.value === v || o.value === v.toLowerCase())\n if (!ok) out[f.key] = ''\n }\n return out\n}\n\n/**\n * Validates and resolves the values the way the server does: unknown field, wrong type, a value missing from the\n * catalog and a year outside the chosen options' years are refused, naming the field only.\n */\nexport function resolveSubject(kind: SubjectKind, values: SubjectValues): { ok: true; subject: ResolvedSubject } | { ok: false; problems: SubjectProblems } {\n const problems: SubjectProblems = {}\n const known = new Set(kind.fields.map((f) => f.key))\n for (const key of Object.keys(values)) if (isPresent(values[key]) && !known.has(key)) problems[key] = 'unknown'\n\n const attributes: Record<string, string | number> = {}\n const priv: Record<string, string> = {}\n const display: Record<string, string> = {}\n const ids: Record<string, string> = {}\n const path: SubjectCatalogNode[] = []\n let tree: Record<string, SubjectCatalogNode> | undefined = kind.catalog?.tree\n const years: string[] = []\n const put = (f: SubjectField, v: string | number) => {\n if (f.private) priv[f.key] = String(v)\n else attributes[f.key] = v\n }\n for (const f of kind.fields) {\n const raw = values[f.key]\n if (!isPresent(raw)) {\n if (f.required) problems[f.key] = 'required'\n if (f.source === 'catalog' && f.type !== 'year') tree = undefined // a skipped level ends the walk\n continue\n }\n const max = f.max ?? MAX_VALUE_LENGTH\n if (f.type === 'year') {\n const y = asYear(raw)\n if (y === null) {\n problems[f.key] = 'invalid'\n continue\n }\n put(f, y)\n display[f.key] = ids[f.key] = String(y)\n if (f.source === 'catalog') years.push(f.key)\n } else if (f.source === 'catalog') {\n if (!kind.catalog) {\n problems[f.key] = 'catalog_unavailable'\n continue\n }\n const s = cleanText(raw, max)\n if (s === null) {\n problems[f.key] = 'invalid'\n continue\n }\n const node: SubjectCatalogNode | undefined = tree?.[s] ?? tree?.[s.toLowerCase()]\n if (!node) {\n problems[f.key] = 'not_in_catalog'\n continue\n }\n const id = tree?.[s] ? s : s.toLowerCase()\n path.push(node)\n tree = node.children\n put(f, id)\n display[f.key] = node.label\n ids[f.key] = id\n } else {\n const s = cleanText(raw, max)\n if (s === null) {\n problems[f.key] = 'invalid'\n continue\n }\n put(f, s)\n display[f.key] = s\n ids[f.key] = slug(s)\n }\n }\n for (const key of years) {\n const y = attributes[key] as number | undefined\n if (y !== undefined && !problems[key] && !path.every((n) => coversYear(n, y))) problems[key] = 'year_range'\n }\n if (Object.keys(problems).length > 0) return { ok: false, problems }\n\n const label = [...kind.fields.filter((f) => !f.private).map((f) => display[f.key]).filter(Boolean).join(' ')].slice(0, MAX_LABEL_LENGTH).join('').trim()\n if (!label) return { ok: false, problems: { _: 'required' } }\n let complete = true\n const key = kind.fit_key_template.replace(/\\{([a-z][a-z0-9_]*)\\}/g, (_m, name: string) => {\n const id = ids[name]\n if (!id) complete = false\n return id ?? ''\n })\n return { ok: true, subject: { label, fit_key: complete && key.length <= MAX_FIT_KEY_LENGTH ? key.toLowerCase() : '', attributes, private: priv } }\n}\n\n/** The mask the server puts in place of a private value («••34»). */\nexport const PRIVATE_MASK = '••'\nexport const isMasked = (v: unknown): boolean => typeof v === 'string' && v.startsWith(PRIVATE_MASK)\n\n/** Prefix of the tag that publishes compatibility (`<prefix><fit_key>`), as in `FitmentConfig.tagPrefix`. */\nexport const DEFAULT_FIT_TAG_PREFIX = 'fit:'\n\n/** The product tag that marks a part as fitting the item with this key. */\nexport const fitTag = (fitKey: string, prefix: string = DEFAULT_FIT_TAG_PREFIX): string => `${prefix}${fitKey}`\n\n/**\n * The `tags_any` of a listing \"only what fits my item\": its own tag plus the universal one (`<prefix>universal`).\n * `[]` when the item has no key (it does not resolve completely): ask for nothing rather than for the wrong thing.\n */\nexport function fitTagsAny(fitKey: string | null | undefined, opts: { prefix?: string; universal?: boolean } = {}): string[] {\n if (!fitKey) return []\n const prefix = opts.prefix ?? DEFAULT_FIT_TAG_PREFIX\n return opts.universal === false ? [fitTag(fitKey, prefix)] : [fitTag(fitKey, prefix), `${prefix}universal`]\n}\n\n/**\n * Budget of one catalog page, in bytes of the `tree` prop as OPS stores it (text, so every quote is escaped). Publishing\n * a page is ONE write of at most 64 KiB that carries the draft and the published copy: ~28 KB of tree per page.\n */\nexport const SUBJECT_CATALOG_PAGE_BYTES = 28 * 1024\n\nconst utf8Bytes = (s: string): number => new TextEncoder().encode(s).length\n\n/**\n * Splits a catalog tree by its first level into parts that each fit one page (`subject_catalog` section, prop `tree`).\n * Publish part `i` on its own page and name them all in the kind's `catalog_ref` (`[\"page:x-1\", \"page:x-2\", …]`); the\n * server joins them back. A real parts catalog (make → model → engine) does not fit in one page. Throws `RangeError`\n * when a single first-level option is larger than the budget on its own (split that level by hand, or trim labels).\n */\nexport function splitSubjectTree(\n tree: Record<string, SubjectCatalogNode>,\n maxBytes: number = SUBJECT_CATALOG_PAGE_BYTES,\n): Record<string, SubjectCatalogNode>[] {\n const size = (part: Record<string, SubjectCatalogNode>) => utf8Bytes(JSON.stringify(JSON.stringify(part)))\n const parts: Record<string, SubjectCatalogNode>[] = []\n let current: Record<string, SubjectCatalogNode> = {}\n for (const [id, node] of Object.entries(tree)) {\n if (size({ [id]: node }) > maxBytes) throw new RangeError(`splitSubjectTree: option ${id} alone exceeds ${maxBytes} bytes`)\n const next = { ...current, [id]: node }\n if (Object.keys(current).length > 0 && size(next) > maxBytes) {\n parts.push(current)\n current = { [id]: node }\n } else current = next\n }\n if (Object.keys(current).length > 0) parts.push(current)\n return parts\n}\n","import type { DeliveryInput, DeliveryMethod, DeliveryOptions, UnavailableRateProvider } from './types.js'\n\n/** Kind of a delivery radio: `ship` (address only, quote later), `rate` (a quoted rate) or `pickup` (a branch). */\nexport type DeliveryChoiceKind = 'ship' | 'rate' | 'pickup'\n\nexport type DeliveryChoice = {\n kind: DeliveryChoiceKind\n /** Everything after the first `:` — a rate id may contain more colons (`rate:skydropx:<id>`). */\n id: string\n method: DeliveryMethod\n /** `ship:` — only the address is saved; the rate is picked on the next pass. */\n addressOnly: boolean\n}\n\n/**\n * Parses the value of the single delivery radio group: `ship:`, `rate:<id>` or `pickup:<branch>`.\n * Splits on the FIRST colon only, so ids like `skydropx:<id>` survive intact (`split(':', 2)` would\n * silently drop everything after the second colon). Anything unknown is treated as `rate`.\n */\nexport function parseDelivery(value: string | null | undefined): DeliveryChoice {\n const raw = (value ?? '').trim()\n const i = raw.indexOf(':')\n const head = i === -1 ? raw : raw.slice(0, i)\n const id = i === -1 ? '' : raw.slice(i + 1)\n const kind: DeliveryChoiceKind = head === 'pickup' ? 'pickup' : head === 'ship' ? 'ship' : 'rate'\n return { kind, id, method: kind === 'pickup' ? 'pickup' : 'shipping', addressOnly: kind === 'ship' }\n}\n\n/** The `setDelivery` payload for a choice; `null` when it only saves the address (`ship:`). */\nexport function deliveryInput(choice: DeliveryChoice): DeliveryInput | null {\n if (choice.addressOnly) return null\n if (choice.kind === 'pickup') return { method: 'pickup', branch_id: choice.id }\n return { method: 'shipping', rate_id: choice.id || undefined }\n}\n\n/** Reason code a rate provider reports when the cart has items without weight. */\nexport const MISSING_WEIGHT = 'missing_weight'\n\nexport type DeliveryNotices = {\n /** Providers that could not quote because some item has no weight. */\n missingWeight: UnavailableRateProvider[]\n /** Providers that failed for any other reason (timeouts, errors). */\n unavailable: UnavailableRateProvider[]\n /** `true` when the shopper should be told something is off with the quote. */\n hasNotices: boolean\n}\n\n/** Splits `delivery.unavailable` into the `missing_weight` notice and the generic one. */\nexport function deliveryNotices(delivery: Pick<DeliveryOptions, 'unavailable' | 'partial'> | null | undefined): DeliveryNotices {\n const all = delivery?.unavailable ?? []\n const missingWeight = all.filter((u) => u.code === MISSING_WEIGHT)\n const unavailable = all.filter((u) => u.code !== MISSING_WEIGHT)\n return {\n missingWeight,\n unavailable,\n hasNotices: missingWeight.length > 0 || unavailable.length > 0 || delivery?.partial === true,\n }\n}\n","/**\n * The URL side of the account lists (orders, invoices, shipments): what a list page reads from `?despues=…&estado=…`\n * and the links to the previous / next page. Framework-free (React Router, Next or plain links all use it), pure and\n * safe on untrusted input: everything read from a URL is validated, so a hand-edited or hostile query can never reach\n * the API as anything but a well-formed filter.\n *\n * A list URL is the whole state of the page (cursor, filters, position), so it can be shared, bookmarked and used with\n * the browser's back / forward buttons, and every link is a real `<a href>` that works without JavaScript.\n */\nimport type { PageInfo } from './types.js'\nimport type { AccountListParams, OrderListParams } from './query.js'\n\n/** What a list page reads from its URL. Every field is optional; the cursors are opaque. */\nexport type ListQuery = {\n /** `page_info.end_cursor` of the page before: this page continues after it. */\n after?: string\n /** `page_info.start_cursor` of the page after: this page is the one before it. */\n before?: string\n /** 1-based position of the first item of the page, only for the «showing 11–20» text (a cursor has no page number). */\n pos?: number\n status?: string\n delivery?: 'shipping' | 'pickup'\n invoice?: boolean\n /** `YYYY-MM-DD` */\n from?: string\n /** `YYYY-MM-DD` */\n to?: string\n q?: string\n}\n\n/** The names a URL uses for each field, and the words for the values that are not free text. */\nexport type ListUrlNames = {\n after: string\n before: string\n pos: string\n status: string\n delivery: string\n invoice: string\n from: string\n to: string\n q: string\n /** The URL word of each delivery method. */\n deliveryValues: { shipping: string; pickup: string }\n /** The URL words of `invoice` (with / without an invoice). */\n invoiceValues: { yes: string; no: string }\n}\n\n/** Spanish URLs (`?despues=…&estado=en_camino&desde=2026-01-01`), the default of a Spanish store. */\nexport const LIST_URL_ES: ListUrlNames = {\n after: 'despues',\n before: 'antes',\n pos: 'pos',\n status: 'estado',\n delivery: 'entrega',\n invoice: 'factura',\n from: 'desde',\n to: 'hasta',\n q: 'q',\n deliveryValues: { shipping: 'envio', pickup: 'recoger' },\n invoiceValues: { yes: 'si', no: 'no' },\n}\n\n/** English URLs, the same as the API's own parameter names. */\nexport const LIST_URL_EN: ListUrlNames = {\n after: 'after',\n before: 'before',\n pos: 'pos',\n status: 'status',\n delivery: 'delivery',\n invoice: 'invoice',\n from: 'from',\n to: 'to',\n q: 'q',\n deliveryValues: { shipping: 'shipping', pickup: 'pickup' },\n invoiceValues: { yes: 'yes', no: 'no' },\n}\n\nconst CURSOR = /^[A-Za-z0-9_-]{1,300}$/\nconst DAY = /^\\d{4}-\\d{2}-\\d{2}$/\nconst STATUS = /^[a-z_]{1,32}$/\nconst MAX_Q = 64\nconst MAX_POS = 1_000_000\n\nconst asParams = (search: URLSearchParams | string | undefined | null): URLSearchParams =>\n search instanceof URLSearchParams ? search : new URLSearchParams(typeof search === 'string' ? search : '')\n\nconst validDay = (v: string | null): string | undefined => {\n if (!v || !DAY.test(v)) return undefined\n const d = new Date(`${v}T00:00:00Z`)\n return Number.isNaN(d.getTime()) || d.toISOString().slice(0, 10) !== v ? undefined : v\n}\n\n/**\n * Reads and validates a list URL. Unknown or malformed values are dropped (never an error): a stale or hand-edited link\n * simply shows the unfiltered list. `after` wins over `before` when both are present.\n */\nexport function readListQuery(search: URLSearchParams | string | undefined | null, names: ListUrlNames = LIST_URL_ES): ListQuery {\n const p = asParams(search)\n const out: ListQuery = {}\n const after = p.get(names.after)\n const before = p.get(names.before)\n if (after && CURSOR.test(after)) out.after = after\n else if (before && CURSOR.test(before)) out.before = before\n const pos = Number(p.get(names.pos))\n if (Number.isInteger(pos) && pos >= 1 && pos <= MAX_POS) out.pos = pos\n const status = p.get(names.status)\n if (status && STATUS.test(status)) out.status = status\n const delivery = p.get(names.delivery)\n if (delivery === names.deliveryValues.shipping) out.delivery = 'shipping'\n else if (delivery === names.deliveryValues.pickup) out.delivery = 'pickup'\n const invoice = p.get(names.invoice)\n if (invoice === names.invoiceValues.yes) out.invoice = true\n else if (invoice === names.invoiceValues.no) out.invoice = false\n const from = validDay(p.get(names.from))\n const to = validDay(p.get(names.to))\n if (from) out.from = from\n if (to && (!from || to >= from)) out.to = to\n const q = (p.get(names.q) ?? '').trim().replace(/^#/, '').trim()\n if (q && q.length <= MAX_Q) out.q = q\n return out\n}\n\n/** Are there filters on (cursor and position are not filters)? */\nexport function isFiltered(query: ListQuery): boolean {\n return !!(query.status || query.delivery || query.invoice !== undefined || query.from || query.to || query.q)\n}\n\n/** The same query without cursor and position: the first page of the same filters. */\nexport function firstPageQuery(query: ListQuery): ListQuery {\n const { after: _a, before: _b, pos: _p, ...filters } = query\n return filters\n}\n\n/** The API parameters of a list page. */\nexport function listApiParams(query: ListQuery, first: number): OrderListParams {\n const params: OrderListParams & AccountListParams = { first }\n if (query.after) params.after = query.after\n else if (query.before) params.before = query.before\n if (query.status) params.status = query.status\n if (query.delivery) params.delivery_method = query.delivery\n if (query.invoice !== undefined) params.has_invoice = query.invoice\n if (query.from) params.from = query.from\n if (query.to) params.to = query.to\n if (query.q) params.q = query.q\n return params\n}\n\n/** `?despues=…&estado=…` (with the leading `?`), or `''` for the first page without filters. Keys in a stable order. */\nexport function listQueryString(query: ListQuery, names: ListUrlNames = LIST_URL_ES): string {\n const p = new URLSearchParams()\n if (query.after) p.set(names.after, query.after)\n else if (query.before) p.set(names.before, query.before)\n if (query.pos && query.pos > 1) p.set(names.pos, String(query.pos))\n if (query.status) p.set(names.status, query.status)\n if (query.delivery) p.set(names.delivery, names.deliveryValues[query.delivery])\n if (query.invoice !== undefined) p.set(names.invoice, query.invoice ? names.invoiceValues.yes : names.invoiceValues.no)\n if (query.from) p.set(names.from, query.from)\n if (query.to) p.set(names.to, query.to)\n if (query.q) p.set(names.q, query.q)\n const s = p.toString()\n return s ? `?${s}` : ''\n}\n\n/** `path` + the query string. */\nexport const listHref = (path: string, query: ListQuery, names: ListUrlNames = LIST_URL_ES): string => `${path}${listQueryString(query, names)}`\n\n/** What the page the buyer is on knows about itself, to build the links around it. */\nexport type ListPageState = {\n query: ListQuery\n pageInfo: PageInfo | null | undefined\n /** Nodes on this page. */\n count: number\n /** Page size asked for. */\n first: number\n}\n\n/** 1-based position of the first node of this page: known when it is the first page, else what the URL carried. */\nexport function pagePosition({ query, pageInfo, count }: Pick<ListPageState, 'query' | 'pageInfo' | 'count'>): number | undefined {\n if (count === 0) return undefined\n if (!query.after && !query.before) return 1\n if (pageInfo && pageInfo.has_previous_page === false) return 1\n return query.pos\n}\n\n/** The query of the next (older) page, or `null` at the end. */\nexport function nextPageQuery(state: ListPageState): ListQuery | null {\n const { query, pageInfo, count } = state\n if (!pageInfo?.has_next_page || !pageInfo.end_cursor) return null\n const here = pagePosition(state)\n return { ...firstPageQuery(query), after: pageInfo.end_cursor, ...(here ? { pos: here + count } : {}) }\n}\n\n/** The query of the previous (newer) page, or `null` on the first. */\nexport function previousPageQuery(state: ListPageState): ListQuery | null {\n const { query, pageInfo, first } = state\n if (!query.after && !query.before) return null\n if (pageInfo?.has_previous_page === false) return firstPageQuery(query)\n const cursor = pageInfo?.start_cursor\n if (!cursor) return query.after || query.before ? firstPageQuery(query) : null\n const here = pagePosition(state)\n // The page before starts at the very beginning: it is the plain first page (a clean, canonical URL).\n if (here !== undefined && here - first <= 1) return firstPageQuery(query)\n return { ...firstPageQuery(query), before: cursor, ...(here ? { pos: Math.max(1, here - first) } : {}) }\n}\n\n/** «from»–«to» of «total» for the «showing 11–20 of 300» text; `null` when the page is empty or the position is unknown. */\nexport function pageRange(state: Pick<ListPageState, 'query' | 'pageInfo' | 'count'> & { total?: number | null }): { from: number; to: number; total: number | null } | null {\n const from = pagePosition(state)\n if (!from || state.count === 0) return null\n return { from, to: from + state.count - 1, total: typeof state.total === 'number' && state.total >= 0 ? state.total : null }\n}\n"]}