@shoppexio/storefront 1.0.62 → 1.0.63

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../../sdk/src/core/cache.ts","../../sdk/src/core/errors.ts","../../../node_modules/.bun/openapi-fetch@0.17.0/node_modules/openapi-fetch/src/index.js","../../contracts/src/navigation.ts","../../contracts/src/email-marketing.ts","../../contracts/src/payment-gateways.ts","../../contracts/src/style-center.ts","../../contracts/src/storefront-addons.ts","../../contracts/src/manual-gateway-template.ts","../../contracts/src/external-payment-adapter.ts","../../contracts/src/redirect-link-template.ts","../../contracts/src/invoice-wire.ts","../../contracts/src/catalog-unit-price.ts","../../contracts/src/index.ts","../../sdk/src/core/typed-client.ts","../../sdk/src/core/config.ts","../../sdk/src/utils/storefront-custom-fields.ts","../../sdk/src/utils/storefront-stock.ts","../../sdk/src/utils/storefront-catalog.ts","../../sdk/src/utils/storefront-search.ts","../../sdk/src/utils/storefront-contact.ts","../../sdk/src/core/endpoint.ts","../../sdk/src/utils/storage.ts","../../sdk/src/core/telemetry.ts","../../sdk/src/core/client.ts","../../sdk/src/modules/store.ts","../../sdk/src/modules/products.ts","../../sdk/src/modules/affiliates.ts","../../sdk/src/utils/cart-line-id.ts","../../sdk/src/utils/requested-currency.ts","../../sdk/src/modules/cart.ts","../../sdk/src/modules/checkout.ts","../../sdk/src/modules/checkout-challenge.ts","../../sdk/src/modules/coupons.ts","../../sdk/src/modules/reviews.ts","../../sdk/src/modules/customer.ts","../../sdk/src/modules/search.ts","../../sdk/src/modules/invoices.ts","../../sdk/src/modules/pages.ts","../../sdk/src/modules/navigation.ts","../../sdk/src/core/attribution.ts","../../sdk/src/modules/analytics.ts","../../sdk/src/modules/presence.ts","../../sdk/src/utils/format.ts","../../sdk/src/modules/theme.ts","../../sdk/src/index.ts"],"sourcesContent":["/**\n * In-memory cache with pending request deduplication.\n */\n\nexport interface CacheEntry<T> {\n data: T;\n expiresAt: number;\n updatedAt: number;\n ttl: number;\n}\n\nexport interface CacheOptions {\n ttl: number;\n staleWhileRevalidate?: boolean;\n}\n\nexport interface CacheStats {\n hits: number;\n misses: number;\n pendingRequests: number;\n entries: number;\n}\n\nconst cache = new Map<string, CacheEntry<unknown>>();\nconst pending = new Map<string, Promise<unknown>>();\n\nconst stats = {\n hits: 0,\n misses: 0,\n};\n\nfunction isExpired(entry: CacheEntry<unknown>): boolean {\n return Date.now() > entry.expiresAt;\n}\n\nexport function getCacheStats(): CacheStats {\n return {\n hits: stats.hits,\n misses: stats.misses,\n pendingRequests: pending.size,\n entries: cache.size,\n };\n}\n\nexport function clearCache(): void {\n cache.clear();\n pending.clear();\n}\n\nexport function invalidateCache(prefixOrKey: string): void {\n for (const key of cache.keys()) {\n if (key === prefixOrKey || key.startsWith(prefixOrKey)) {\n cache.delete(key);\n }\n }\n}\n\nexport function setCacheEntry<T>(key: string, data: T, ttl: number): void {\n const now = Date.now();\n cache.set(key, {\n data,\n ttl,\n updatedAt: now,\n expiresAt: now + ttl,\n });\n}\n\nexport function getCacheEntry<T>(key: string): CacheEntry<T> | null {\n const entry = cache.get(key) as CacheEntry<T> | undefined;\n if (!entry) return null;\n return entry;\n}\n\nexport async function getOrFetch<T>(\n key: string,\n fetcher: () => Promise<T>,\n options: CacheOptions,\n shouldCache: (value: T) => boolean = () => true\n): Promise<T> {\n const entry = getCacheEntry<T>(key);\n\n if (entry && !isExpired(entry)) {\n stats.hits += 1;\n return entry.data;\n }\n\n if (entry && options.staleWhileRevalidate) {\n stats.hits += 1;\n if (!pending.has(key)) {\n const refreshPromise = (async () => {\n try {\n const data = await fetcher();\n if (shouldCache(data)) {\n setCacheEntry(key, data, options.ttl);\n }\n return data;\n } finally {\n pending.delete(key);\n }\n })();\n pending.set(key, refreshPromise as Promise<unknown>);\n }\n return entry.data;\n }\n\n if (pending.has(key)) {\n return pending.get(key) as Promise<T>;\n }\n\n stats.misses += 1;\n const promise = (async () => {\n try {\n const data = await fetcher();\n if (shouldCache(data)) {\n setCacheEntry(key, data, options.ttl);\n }\n return data;\n } finally {\n pending.delete(key);\n }\n })();\n\n pending.set(key, promise as Promise<unknown>);\n return promise;\n}\n","/**\n * SDK Error Classes\n */\n\nexport class ShoppexError extends Error {\n public readonly code: string;\n public readonly statusCode?: number;\n\n constructor(message: string, code: string, statusCode?: number) {\n super(message);\n this.name = 'ShoppexError';\n this.code = code;\n this.statusCode = statusCode;\n Object.setPrototypeOf(this, ShoppexError.prototype);\n }\n}\n\nexport class NotInitializedError extends ShoppexError {\n constructor() {\n super(\n 'SDK not initialized. Call shoppex.init() first.',\n 'NOT_INITIALIZED'\n );\n this.name = 'NotInitializedError';\n Object.setPrototypeOf(this, NotInitializedError.prototype);\n }\n}\n\nexport class NetworkError extends ShoppexError {\n constructor(message: string, statusCode?: number) {\n super(message, 'NETWORK_ERROR', statusCode);\n this.name = 'NetworkError';\n Object.setPrototypeOf(this, NetworkError.prototype);\n }\n}\n\n/**\n * A refusal the SERVER made and named. `code` is the backend's `error_code`\n * (e.g. `errors.checkout.coupon_no_longer_valid`) — the branchable identity of\n * the refusal, stable across locales, unlike the localized `message`.\n *\n * Distinct from {@link NetworkError}, whose `code` is always `NETWORK_ERROR`:\n * that one means \"the request did not produce a named answer\".\n */\nexport class ApiError extends ShoppexError {\n public readonly errorParams?: Record<string, unknown>;\n\n constructor(\n message: string,\n code: string,\n statusCode?: number,\n errorParams?: Record<string, unknown>,\n ) {\n super(message, code, statusCode);\n this.name = 'ApiError';\n this.errorParams = errorParams;\n Object.setPrototypeOf(this, ApiError.prototype);\n }\n}\n\nexport class ValidationError extends ShoppexError {\n public readonly invalidFields?: string[];\n\n constructor(message: string, invalidFields?: string[]) {\n super(message, 'VALIDATION_ERROR');\n this.name = 'ValidationError';\n this.invalidFields = invalidFields;\n Object.setPrototypeOf(this, ValidationError.prototype);\n }\n}\n\nexport class CartError extends ShoppexError {\n constructor(message: string) {\n super(message, 'BASKET_ERROR');\n this.name = 'CartError';\n Object.setPrototypeOf(this, CartError.prototype);\n }\n}\n","// settings & const\nconst PATH_PARAM_RE = /\\{[^{}]+\\}/g;\n\nconst supportsRequestInitExt = () => {\n return (\n typeof process === \"object\" &&\n Number.parseInt(process?.versions?.node?.substring(0, 2)) >= 18 &&\n process.versions.undici\n );\n};\n\n/**\n * Returns a cheap, non-cryptographically-secure random ID\n * Courtesy of @imranbarbhuiya (https://github.com/imranbarbhuiya)\n */\nexport function randomID() {\n return Math.random().toString(36).slice(2, 11);\n}\n\n/**\n * Create an openapi-fetch client.\n * @type {import(\"./index.js\").default}\n */\nexport default function createClient(clientOptions) {\n let {\n baseUrl = \"\",\n Request: CustomRequest = globalThis.Request,\n fetch: baseFetch = globalThis.fetch,\n querySerializer: globalQuerySerializer,\n bodySerializer: globalBodySerializer,\n pathSerializer: globalPathSerializer,\n headers: baseHeaders,\n requestInitExt = undefined,\n ...baseOptions\n } = { ...clientOptions };\n requestInitExt = supportsRequestInitExt() ? requestInitExt : undefined;\n baseUrl = removeTrailingSlash(baseUrl);\n const globalMiddlewares = [];\n\n /**\n * Per-request fetch (keeps settings created in createClient()\n * @param {T} url\n * @param {import('./index.js').FetchOptions<T>} fetchOptions\n */\n async function coreFetch(schemaPath, fetchOptions) {\n const {\n baseUrl: localBaseUrl,\n fetch = baseFetch,\n Request = CustomRequest,\n headers,\n params = {},\n parseAs = \"json\",\n querySerializer: requestQuerySerializer,\n bodySerializer = globalBodySerializer ?? defaultBodySerializer,\n pathSerializer: requestPathSerializer,\n body,\n middleware: requestMiddlewares = [],\n ...init\n } = fetchOptions || {};\n let finalBaseUrl = baseUrl;\n if (localBaseUrl) {\n finalBaseUrl = removeTrailingSlash(localBaseUrl) ?? baseUrl;\n }\n\n let querySerializer =\n typeof globalQuerySerializer === \"function\"\n ? globalQuerySerializer\n : createQuerySerializer(globalQuerySerializer);\n if (requestQuerySerializer) {\n querySerializer =\n typeof requestQuerySerializer === \"function\"\n ? requestQuerySerializer\n : createQuerySerializer({\n ...(typeof globalQuerySerializer === \"object\" ? globalQuerySerializer : {}),\n ...requestQuerySerializer,\n });\n }\n\n const pathSerializer = requestPathSerializer || globalPathSerializer || defaultPathSerializer;\n\n const serializedBody =\n body === undefined\n ? undefined\n : bodySerializer(\n body,\n // Note: we declare mergeHeaders() both here and below because it’s a bit of a chicken-or-egg situation:\n // bodySerializer() needs all headers so we aren’t dropping ones set by the user, however,\n // the result of this ALSO sets the lowest-priority content-type header. So we re-merge below,\n // setting the content-type at the very beginning to be overwritten.\n // Lastly, based on the way headers work, it’s not a simple “present-or-not” check becauase null intentionally un-sets headers.\n mergeHeaders(baseHeaders, headers, params.header),\n );\n const finalHeaders = mergeHeaders(\n // with no body, we should not to set Content-Type\n serializedBody === undefined ||\n // if serialized body is FormData; browser will correctly set Content-Type & boundary expression\n serializedBody instanceof FormData\n ? {}\n : {\n \"Content-Type\": \"application/json\",\n },\n baseHeaders,\n headers,\n params.header,\n );\n\n // Client level middleware take priority over request-level middleware\n const finalMiddlewares = [...globalMiddlewares, ...requestMiddlewares];\n\n const requestInit = {\n redirect: \"follow\",\n ...baseOptions,\n ...init,\n body: serializedBody,\n headers: finalHeaders,\n };\n\n let id;\n let options;\n let request = new Request(\n createFinalURL(schemaPath, { baseUrl: finalBaseUrl, params, querySerializer, pathSerializer }),\n requestInit,\n );\n let response;\n\n /** Add custom parameters to Request object */\n for (const key in init) {\n if (!(key in request)) {\n request[key] = init[key];\n }\n }\n\n if (finalMiddlewares.length) {\n id = randomID();\n\n // middleware (request)\n options = Object.freeze({\n baseUrl: finalBaseUrl,\n fetch,\n parseAs,\n querySerializer,\n bodySerializer,\n pathSerializer,\n });\n for (const m of finalMiddlewares) {\n if (m && typeof m === \"object\" && typeof m.onRequest === \"function\") {\n const result = await m.onRequest({\n request,\n schemaPath,\n params,\n options,\n id,\n });\n if (result) {\n if (result instanceof Request) {\n request = result;\n } else if (result instanceof Response) {\n response = result;\n break;\n } else {\n throw new Error(\"onRequest: must return new Request() or Response() when modifying the request\");\n }\n }\n }\n }\n }\n\n if (!response) {\n // fetch!\n try {\n response = await fetch(request, requestInitExt);\n } catch (error) {\n let errorAfterMiddleware = error;\n // middleware (error)\n // execute in reverse-array order (first priority gets last transform)\n if (finalMiddlewares.length) {\n for (let i = finalMiddlewares.length - 1; i >= 0; i--) {\n const m = finalMiddlewares[i];\n if (m && typeof m === \"object\" && typeof m.onError === \"function\") {\n const result = await m.onError({\n request,\n error: errorAfterMiddleware,\n schemaPath,\n params,\n options,\n id,\n });\n if (result) {\n // if error is handled by returning a response, skip remaining middleware\n if (result instanceof Response) {\n errorAfterMiddleware = undefined;\n response = result;\n break;\n }\n\n if (result instanceof Error) {\n errorAfterMiddleware = result;\n continue;\n }\n\n throw new Error(\"onError: must return new Response() or instance of Error\");\n }\n }\n }\n }\n\n // rethrow error if not handled by middleware\n if (errorAfterMiddleware) {\n throw errorAfterMiddleware;\n }\n }\n\n // middleware (response)\n // execute in reverse-array order (first priority gets last transform)\n if (finalMiddlewares.length) {\n for (let i = finalMiddlewares.length - 1; i >= 0; i--) {\n const m = finalMiddlewares[i];\n if (m && typeof m === \"object\" && typeof m.onResponse === \"function\") {\n const result = await m.onResponse({\n request,\n response,\n schemaPath,\n params,\n options,\n id,\n });\n if (result) {\n if (!(result instanceof Response)) {\n throw new Error(\"onResponse: must return new Response() when modifying the response\");\n }\n response = result;\n }\n }\n }\n }\n }\n\n const contentLength = response.headers.get(\"Content-Length\");\n // handle empty content\n if (\n response.status === 204 ||\n request.method === \"HEAD\" ||\n (contentLength === \"0\" && !response.headers.get(\"Transfer-Encoding\")?.includes(\"chunked\"))\n ) {\n return response.ok ? { data: undefined, response } : { error: undefined, response };\n }\n\n // parse response (falling back to .text() when necessary)\n if (response.ok) {\n const getResponseData = async () => {\n // if \"stream\", skip parsing entirely\n if (parseAs === \"stream\") {\n return response.body;\n }\n\n if (parseAs === \"json\" && !contentLength) {\n // use text() when no content-length is provided to avoid errors parsing empty bodies (200 with no content)\n const raw = await response.text();\n return raw ? JSON.parse(raw) : undefined;\n }\n\n return await response[parseAs]();\n };\n return { data: await getResponseData(), response };\n }\n\n // handle errors\n let error = await response.text();\n try {\n error = JSON.parse(error); // attempt to parse as JSON\n } catch {\n // noop\n }\n return { error, response };\n }\n\n return {\n request(method, url, init) {\n return coreFetch(url, { ...init, method: method.toUpperCase() });\n },\n /** Call a GET endpoint */\n GET(url, init) {\n return coreFetch(url, { ...init, method: \"GET\" });\n },\n /** Call a PUT endpoint */\n PUT(url, init) {\n return coreFetch(url, { ...init, method: \"PUT\" });\n },\n /** Call a POST endpoint */\n POST(url, init) {\n return coreFetch(url, { ...init, method: \"POST\" });\n },\n /** Call a DELETE endpoint */\n DELETE(url, init) {\n return coreFetch(url, { ...init, method: \"DELETE\" });\n },\n /** Call a OPTIONS endpoint */\n OPTIONS(url, init) {\n return coreFetch(url, { ...init, method: \"OPTIONS\" });\n },\n /** Call a HEAD endpoint */\n HEAD(url, init) {\n return coreFetch(url, { ...init, method: \"HEAD\" });\n },\n /** Call a PATCH endpoint */\n PATCH(url, init) {\n return coreFetch(url, { ...init, method: \"PATCH\" });\n },\n /** Call a TRACE endpoint */\n TRACE(url, init) {\n return coreFetch(url, { ...init, method: \"TRACE\" });\n },\n /** Register middleware */\n use(...middleware) {\n for (const m of middleware) {\n if (!m) {\n continue;\n }\n if (typeof m !== \"object\" || !(\"onRequest\" in m || \"onResponse\" in m || \"onError\" in m)) {\n throw new Error(\"Middleware must be an object with one of `onRequest()`, `onResponse() or `onError()`\");\n }\n globalMiddlewares.push(m);\n }\n },\n /** Unregister middleware */\n eject(...middleware) {\n for (const m of middleware) {\n const i = globalMiddlewares.indexOf(m);\n if (i !== -1) {\n globalMiddlewares.splice(i, 1);\n }\n }\n },\n };\n}\n\nclass PathCallForwarder {\n constructor(client, url) {\n this.client = client;\n this.url = url;\n }\n\n GET = (init) => {\n return this.client.GET(this.url, init);\n };\n PUT = (init) => {\n return this.client.PUT(this.url, init);\n };\n POST = (init) => {\n return this.client.POST(this.url, init);\n };\n DELETE = (init) => {\n return this.client.DELETE(this.url, init);\n };\n OPTIONS = (init) => {\n return this.client.OPTIONS(this.url, init);\n };\n HEAD = (init) => {\n return this.client.HEAD(this.url, init);\n };\n PATCH = (init) => {\n return this.client.PATCH(this.url, init);\n };\n TRACE = (init) => {\n return this.client.TRACE(this.url, init);\n };\n}\n\nclass PathClientProxyHandler {\n constructor() {\n this.client = null;\n }\n\n // Assume the property is an URL.\n get(coreClient, url) {\n const forwarder = new PathCallForwarder(coreClient, url);\n this.client[url] = forwarder;\n return forwarder;\n }\n}\n\n/**\n * Wrap openapi-fetch client to support a path based API.\n * @type {import(\"./index.js\").wrapAsPathBasedClient}\n */\nexport function wrapAsPathBasedClient(coreClient) {\n const handler = new PathClientProxyHandler();\n const proxy = new Proxy(coreClient, handler);\n\n // Put the proxy on the prototype chain of the actual client.\n // This means if we do not have a memoized PathCallForwarder,\n // we fall back to the proxy to synthesize it.\n // However, the proxy itself is not on the hot-path (if we fetch the same\n // endpoint multiple times, only the first call will hit the proxy).\n function Client() {}\n Client.prototype = proxy;\n\n const client = new Client();\n\n // Feed the client back to the proxy handler so it can store the generated\n // PathCallForwarder.\n handler.client = client;\n\n return client;\n}\n\n/**\n * Convenience method to an openapi-fetch path based client.\n * Strictly equivalent to `wrapAsPathBasedClient(createClient(...))`.\n * @type {import(\"./index.js\").createPathBasedClient}\n */\nexport function createPathBasedClient(clientOptions) {\n return wrapAsPathBasedClient(createClient(clientOptions));\n}\n\n// utils\n\n/**\n * Serialize primitive param values\n * @type {import(\"./index.js\").serializePrimitiveParam}\n */\nexport function serializePrimitiveParam(name, value, options) {\n if (value === undefined || value === null) {\n return \"\";\n }\n if (typeof value === \"object\") {\n throw new Error(\n \"Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.\",\n );\n }\n return `${name}=${options?.allowReserved === true ? value : encodeURIComponent(value)}`;\n}\n\n/**\n * Serialize object param (shallow only)\n * @type {import(\"./index.js\").serializeObjectParam}\n */\nexport function serializeObjectParam(name, value, options) {\n if (!value || typeof value !== \"object\") {\n return \"\";\n }\n const values = [];\n const joiner =\n {\n simple: \",\",\n label: \".\",\n matrix: \";\",\n }[options.style] || \"&\";\n\n // explode: false\n if (options.style !== \"deepObject\" && options.explode === false) {\n for (const k in value) {\n values.push(k, options.allowReserved === true ? value[k] : encodeURIComponent(value[k]));\n }\n const final = values.join(\",\"); // note: values are always joined by comma in explode: false (but joiner can prefix)\n switch (options.style) {\n case \"form\": {\n return `${name}=${final}`;\n }\n case \"label\": {\n return `.${final}`;\n }\n case \"matrix\": {\n return `;${name}=${final}`;\n }\n default: {\n return final;\n }\n }\n }\n\n // explode: true\n for (const k in value) {\n const finalName = options.style === \"deepObject\" ? `${name}[${k}]` : k;\n values.push(serializePrimitiveParam(finalName, value[k], options));\n }\n const final = values.join(joiner);\n return options.style === \"label\" || options.style === \"matrix\" ? `${joiner}${final}` : final;\n}\n\n/**\n * Serialize array param (shallow only)\n * @type {import(\"./index.js\").serializeArrayParam}\n */\nexport function serializeArrayParam(name, value, options) {\n if (!Array.isArray(value)) {\n return \"\";\n }\n\n // explode: false\n if (options.explode === false) {\n const joiner = { form: \",\", spaceDelimited: \"%20\", pipeDelimited: \"|\" }[options.style] || \",\"; // note: for arrays, joiners vary wildly based on style + explode behavior\n const final = (options.allowReserved === true ? value : value.map((v) => encodeURIComponent(v))).join(joiner);\n switch (options.style) {\n case \"simple\": {\n return final;\n }\n case \"label\": {\n return `.${final}`;\n }\n case \"matrix\": {\n return `;${name}=${final}`;\n }\n // case \"spaceDelimited\":\n // case \"pipeDelimited\":\n default: {\n return `${name}=${final}`;\n }\n }\n }\n\n // explode: true\n const joiner = { simple: \",\", label: \".\", matrix: \";\" }[options.style] || \"&\";\n const values = [];\n for (const v of value) {\n if (options.style === \"simple\" || options.style === \"label\") {\n values.push(options.allowReserved === true ? v : encodeURIComponent(v));\n } else {\n values.push(serializePrimitiveParam(name, v, options));\n }\n }\n return options.style === \"label\" || options.style === \"matrix\"\n ? `${joiner}${values.join(joiner)}`\n : values.join(joiner);\n}\n\n/**\n * Serialize query params to string\n * @type {import(\"./index.js\").createQuerySerializer}\n */\nexport function createQuerySerializer(options) {\n return function querySerializer(queryParams) {\n const search = [];\n if (queryParams && typeof queryParams === \"object\") {\n for (const name in queryParams) {\n const value = queryParams[name];\n if (value === undefined || value === null) {\n continue;\n }\n if (Array.isArray(value)) {\n if (value.length === 0) {\n continue;\n }\n search.push(\n serializeArrayParam(name, value, {\n style: \"form\",\n explode: true,\n ...options?.array,\n allowReserved: options?.allowReserved || false,\n }),\n );\n continue;\n }\n if (typeof value === \"object\") {\n search.push(\n serializeObjectParam(name, value, {\n style: \"deepObject\",\n explode: true,\n ...options?.object,\n allowReserved: options?.allowReserved || false,\n }),\n );\n continue;\n }\n search.push(serializePrimitiveParam(name, value, options));\n }\n }\n return search.join(\"&\");\n };\n}\n\n/**\n * Handle different OpenAPI 3.x serialization styles\n * @type {import(\"./index.js\").defaultPathSerializer}\n * @see https://swagger.io/docs/specification/serialization/#path\n */\nexport function defaultPathSerializer(pathname, pathParams) {\n let nextURL = pathname;\n for (const match of pathname.match(PATH_PARAM_RE) ?? []) {\n let name = match.substring(1, match.length - 1);\n let explode = false;\n let style = \"simple\";\n if (name.endsWith(\"*\")) {\n explode = true;\n name = name.substring(0, name.length - 1);\n }\n if (name.startsWith(\".\")) {\n style = \"label\";\n name = name.substring(1);\n } else if (name.startsWith(\";\")) {\n style = \"matrix\";\n name = name.substring(1);\n }\n if (!pathParams || pathParams[name] === undefined || pathParams[name] === null) {\n continue;\n }\n const value = pathParams[name];\n if (Array.isArray(value)) {\n nextURL = nextURL.replace(match, serializeArrayParam(name, value, { style, explode }));\n continue;\n }\n if (typeof value === \"object\") {\n nextURL = nextURL.replace(match, serializeObjectParam(name, value, { style, explode }));\n continue;\n }\n if (style === \"matrix\") {\n nextURL = nextURL.replace(match, `;${serializePrimitiveParam(name, value)}`);\n continue;\n }\n nextURL = nextURL.replace(match, style === \"label\" ? `.${encodeURIComponent(value)}` : encodeURIComponent(value));\n }\n return nextURL;\n}\n\n/**\n * Serialize body object to string\n * @type {import(\"./index.js\").defaultBodySerializer}\n */\nexport function defaultBodySerializer(body, headers) {\n if (body instanceof FormData) {\n return body;\n }\n if (headers) {\n const contentType =\n headers.get instanceof Function\n ? (headers.get(\"Content-Type\") ?? headers.get(\"content-type\"))\n : (headers[\"Content-Type\"] ?? headers[\"content-type\"]);\n if (contentType === \"application/x-www-form-urlencoded\") {\n return new URLSearchParams(body).toString();\n }\n }\n return JSON.stringify(body);\n}\n\n/**\n * Construct URL string from baseUrl and handle path and query params\n * @type {import(\"./index.js\").createFinalURL}\n */\nexport function createFinalURL(pathname, options) {\n let finalURL = `${options.baseUrl}${pathname}`;\n if (options.params?.path) {\n finalURL = options.pathSerializer(finalURL, options.params.path);\n }\n let search = options.querySerializer(options.params.query ?? {});\n if (search.startsWith(\"?\")) {\n search = search.substring(1);\n }\n if (search) {\n finalURL += `?${search}`;\n }\n return finalURL;\n}\n\n/**\n * Merge headers a and b, with b taking priority\n * @type {import(\"./index.js\").mergeHeaders}\n */\nexport function mergeHeaders(...allHeaders) {\n const finalHeaders = new Headers();\n for (const h of allHeaders) {\n if (!h || typeof h !== \"object\") {\n continue;\n }\n const iterator = h instanceof Headers ? h.entries() : Object.entries(h);\n for (const [k, v] of iterator) {\n if (v === null) {\n finalHeaders.delete(k);\n } else if (Array.isArray(v)) {\n for (const v2 of v) {\n finalHeaders.append(k, v2);\n }\n } else if (v !== undefined) {\n finalHeaders.set(k, v);\n }\n }\n }\n return finalHeaders;\n}\n\n/**\n * Remove trailing slash from url\n * @type {import(\"./index.js\").removeTrailingSlash}\n */\nexport function removeTrailingSlash(url) {\n if (url.endsWith(\"/\")) {\n return url.substring(0, url.length - 1);\n }\n return url;\n}\n","const NAVIGATION_MENU_SLOT_CONFIG = {\n header: {\n title: 'Header',\n aliases: ['Header Menu'],\n },\n footer: {\n title: 'Footer',\n aliases: ['Footer Links', 'Legal Links'],\n },\n} as const;\n\nexport type NavigationMenuSlot = keyof typeof NAVIGATION_MENU_SLOT_CONFIG;\n\nfunction normalizeNavigationToken(value: string): string {\n return value.trim().toLowerCase().replace(/\\s+/g, ' ');\n}\n\nexport function getNavigationMenuCanonicalTitle(slot: NavigationMenuSlot): string {\n return NAVIGATION_MENU_SLOT_CONFIG[slot].title;\n}\n\nexport function getNavigationMenuTitles(slot: NavigationMenuSlot): string[] {\n const config = NAVIGATION_MENU_SLOT_CONFIG[slot];\n return [config.title, ...config.aliases];\n}\n\nexport function isNavigationMenuSlot(value: string): value is NavigationMenuSlot {\n return value in NAVIGATION_MENU_SLOT_CONFIG;\n}\n\nexport function resolveNavigationMenuSlot(value: string | null | undefined): NavigationMenuSlot | null {\n if (!value) return null;\n\n const normalizedValue = normalizeNavigationToken(value);\n for (const slot of Object.keys(NAVIGATION_MENU_SLOT_CONFIG) as NavigationMenuSlot[]) {\n const candidates = [slot, ...getNavigationMenuTitles(slot)];\n if (candidates.some((candidate) => normalizeNavigationToken(candidate) === normalizedValue)) {\n return slot;\n }\n }\n\n return null;\n}\n\nexport function isSystemNavigationMenuTitle(value: string | null | undefined): boolean {\n return resolveNavigationMenuSlot(value) !== null;\n}\n\nexport const NAVIGATION_MENU_SLOTS = Object.keys(NAVIGATION_MENU_SLOT_CONFIG) as NavigationMenuSlot[];\n","import * as z from 'zod/v4';\n\nexport const EmailMarketingConsentBasisSchema = z.enum(['CONSENT', 'SOFT_OPT_IN', 'TRANSACTIONAL_ONLY', 'UNKNOWN']);\nexport const EmailMarketingSuppressionReasonSchema = z.enum(['MANUAL_UNSUB', 'ONE_CLICK_UNSUB', 'HARD_BOUNCE', 'COMPLAINT', 'ADMIN_BLOCK']);\nexport const EmailMarketingCampaignTypeSchema = z.enum(['BROADCAST', 'AUTOMATION']);\nexport const EmailMarketingAutomationTriggerSchema = z.enum([\n 'ABANDONED_CART',\n 'POST_PURCHASE',\n 'WELCOME',\n 'WIN_BACK',\n 'RE_ENGAGEMENT',\n 'TAG_ADDED',\n]);\n\nexport const EmailMarketingContactCreateSchema = z.object({\n email: z.email(),\n name: z.string().trim().min(1).nullable().optional(),\n customer_id: z.string().uuid().nullable().optional(),\n tags: z.array(z.string().trim().min(1)).default([]),\n consent_basis: EmailMarketingConsentBasisSchema.default('UNKNOWN'),\n source: z.string().trim().min(1).default('dashboard'),\n});\n\nexport const EmailMarketingTemplateCreateSchema = z.object({\n name: z.string().trim().min(1),\n subject: z.string().trim().min(1),\n preheader: z.string().nullable().optional(),\n mjml_source: z.string().trim().min(1),\n builder_project_json: z.record(z.string(), z.unknown()).nullable().optional(),\n thumbnail_url: z.url().nullable().optional(),\n});\n\nexport const EmailMarketingTemplatePreviewSchema = z.object({\n mjml_source: z.string().trim().min(1),\n sample_variables: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport const EmailMarketingTemplateTestSendSchema = z.object({\n recipient_email: z.email(),\n sample_variables: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport const EmailMarketingSettingsUpdateSchema = z.object({\n marketing_enabled: z.boolean().optional(),\n default_from_name: z.string().trim().min(1).nullable().optional(),\n default_from_email: z.email().nullable().optional(),\n default_reply_to_email: z.email().nullable().optional(),\n physical_address: z.string().trim().min(1).nullable().optional(),\n physical_address_line2: z.string().trim().min(1).nullable().optional(),\n physical_city: z.string().trim().min(1).nullable().optional(),\n physical_postal_code: z.string().trim().min(1).nullable().optional(),\n physical_country: z.string().trim().length(2).nullable().optional(),\n daily_limit: z.number().int().positive().optional(),\n monthly_soft_cap: z.number().int().positive().optional(),\n});\n\nexport const EmailMarketingCampaignCreateSchema = z.object({\n type: EmailMarketingCampaignTypeSchema.default('BROADCAST'),\n name: z.string().trim().min(1),\n subject: z.string().trim().min(1),\n template_id: z.string().uuid(),\n list_id: z.string().uuid().nullable().optional(),\n segment_id: z.string().uuid().nullable().optional(),\n from_name: z.string().trim().min(1),\n from_email: z.email(),\n reply_to_email: z.email().nullable().optional(),\n schedule_at: z.string().datetime().nullable().optional(),\n target_emails: z.array(z.email()).max(0, 'Direct recipient entry is disabled. Use lists or segments built from Shoppex customers and paid order buyers.').default([]),\n idempotency_key: z.string().trim().min(1).nullable().optional(),\n});\n\nexport const EmailMarketingAutomationCreateSchema = z.object({\n name: z.string().trim().min(1),\n subject: z.string().trim().min(1),\n template_id: z.string().uuid(),\n from_name: z.string().trim().min(1),\n from_email: z.email(),\n reply_to_email: z.email().nullable().optional(),\n trigger: EmailMarketingAutomationTriggerSchema,\n delay_seconds: z.number().int().min(0).default(0),\n conditions: z.record(z.string(), z.unknown()).default({}),\n});\n\nexport const EmailMarketingAutomationTriggerEventSchema = z.object({\n trigger: EmailMarketingAutomationTriggerSchema,\n email: z.email(),\n customer_id: z.string().uuid().nullable().optional(),\n name: z.string().trim().min(1).nullable().optional(),\n consent_basis: EmailMarketingConsentBasisSchema.default('UNKNOWN'),\n variables: z.record(z.string(), z.unknown()).default({}),\n idempotency_key: z.string().trim().min(1).nullable().optional(),\n});\n\nexport const EmailMarketingSuppressionCreateSchema = z.object({\n email: z.email(),\n reason: EmailMarketingSuppressionReasonSchema.default('ADMIN_BLOCK'),\n notes: z.string().nullable().optional(),\n});\n\nexport type EmailMarketingContactCreate = z.infer<typeof EmailMarketingContactCreateSchema>;\nexport type EmailMarketingTemplateCreate = z.infer<typeof EmailMarketingTemplateCreateSchema>;\nexport type EmailMarketingTemplatePreview = z.infer<typeof EmailMarketingTemplatePreviewSchema>;\nexport type EmailMarketingTemplateTestSend = z.infer<typeof EmailMarketingTemplateTestSendSchema>;\nexport type EmailMarketingSettingsUpdate = z.infer<typeof EmailMarketingSettingsUpdateSchema>;\nexport type EmailMarketingCampaignCreate = z.infer<typeof EmailMarketingCampaignCreateSchema>;\nexport type EmailMarketingAutomationCreate = z.infer<typeof EmailMarketingAutomationCreateSchema>;\nexport type EmailMarketingAutomationTriggerEvent = z.infer<typeof EmailMarketingAutomationTriggerEventSchema>;\nexport type EmailMarketingSuppressionCreate = z.infer<typeof EmailMarketingSuppressionCreateSchema>;\n","import * as z from 'zod/v4';\n\n/**\n * External-adapter gateway-key helpers live here rather than in\n * external-payment-adapter.ts: this module is bundled into the checkout\n * client, and a relative import between the two breaks one of NodeNext tsc,\n * the tsup DTS build, or Turbopack depending on the specifier. The server-only\n * adapter module re-exports these for its consumers.\n */\nexport const EXTERNAL_PAYMENT_ADAPTER_GATEWAY_PREFIX = 'EXTERNAL:' as const;\n\nexport type ExternalPaymentAdapterGatewayKey =\n `${typeof EXTERNAL_PAYMENT_ADAPTER_GATEWAY_PREFIX}${string}`;\n\nconst EXTERNAL_ADAPTER_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n\nexport function buildExternalPaymentAdapterGatewayKey(\n adapterId: string,\n): ExternalPaymentAdapterGatewayKey | null {\n const normalizedId = adapterId.trim().toLowerCase();\n return EXTERNAL_ADAPTER_ID_PATTERN.test(normalizedId)\n ? `${EXTERNAL_PAYMENT_ADAPTER_GATEWAY_PREFIX}${normalizedId}`\n : null;\n}\n\nexport function parseExternalPaymentAdapterGatewayKey(gateway: string): string | null {\n const trimmed = gateway.trim();\n if (!/^external:/i.test(trimmed)) {\n return null;\n }\n\n const adapterId = trimmed.slice(trimmed.indexOf(':') + 1).trim().toLowerCase();\n return EXTERNAL_ADAPTER_ID_PATTERN.test(adapterId) ? adapterId : null;\n}\n\nexport function isExternalPaymentAdapterGatewayKey(\n gateway: string,\n): gateway is ExternalPaymentAdapterGatewayKey {\n return parseExternalPaymentAdapterGatewayKey(gateway) !== null;\n}\n\nexport const COIN_GATEWAY_KEYS = [\n 'BITCOIN',\n 'LITECOIN',\n 'ETHEREUM',\n 'BITCOIN_CASH',\n 'MONERO',\n 'RIPPLE',\n 'TRON',\n 'SOLANA',\n 'POLYGON',\n 'BINANCE_COIN',\n 'CRONOS',\n 'CONCORDIUM',\n 'NANO',\n 'DOGECOIN',\n 'DASH',\n] as const;\n\nexport const CRYPTO_PROVIDER_KEYS = [\n 'NOWPAYMENTS',\n 'CRYPTOMUS',\n 'OXAPAY',\n] as const;\n\nexport const MANAGED_CRYPTO_PROVIDER_KEYS = [\n 'NOWPAYMENTS_WHITELABEL',\n] as const;\n\nexport const GENERIC_STABLECOIN_GATEWAY_FAMILIES = {\n USDT: ['USDT_TRC20', 'USDT_ERC20', 'USDT_BEP20', 'USDT_POLYGON', 'USDT_SOL'],\n USDC: ['USDC_ERC20', 'USDC_TRC20', 'USDC_BEP20', 'USDC_POLYGON', 'USDC_SOL'],\n DAI: ['DAI_ERC20'],\n} as const;\n\nexport const GENERIC_STABLECOIN_GATEWAY_KEYS = Object.keys(\n GENERIC_STABLECOIN_GATEWAY_FAMILIES,\n) as Array<keyof typeof GENERIC_STABLECOIN_GATEWAY_FAMILIES>;\n\nexport const TOKEN_GATEWAY_KEYS = [\n ...GENERIC_STABLECOIN_GATEWAY_FAMILIES.USDT,\n ...GENERIC_STABLECOIN_GATEWAY_FAMILIES.USDC,\n ...GENERIC_STABLECOIN_GATEWAY_FAMILIES.DAI,\n] as const;\n\nexport const CRYPTO_GATEWAY_KEYS = [\n ...COIN_GATEWAY_KEYS,\n ...TOKEN_GATEWAY_KEYS,\n] as const;\n\nexport const LEGACY_CRYPTO_GATEWAY_KEYS = [\n 'BITCOIN_LN',\n] as const;\n\nexport const CRYPTO_PROVIDER_GATEWAY_KEYS = [\n ...CRYPTO_PROVIDER_KEYS,\n ...MANAGED_CRYPTO_PROVIDER_KEYS,\n] as const;\n\nexport const CONCRETE_CRYPTO_GATEWAY_KEYS = [\n ...CRYPTO_GATEWAY_KEYS,\n ...LEGACY_CRYPTO_GATEWAY_KEYS,\n] as const;\n\n// Embed v1 predates Concordium support. This list is frozen by design so new\n// shared-catalog coins cannot silently enter the embed-v1 session boundary.\nexport const EMBED_CRYPTO_GATEWAY_KEYS = [\n 'BITCOIN',\n 'LITECOIN',\n 'ETHEREUM',\n 'BITCOIN_CASH',\n 'MONERO',\n 'RIPPLE',\n 'TRON',\n 'SOLANA',\n 'POLYGON',\n 'BINANCE_COIN',\n 'CRONOS',\n 'NANO',\n 'DOGECOIN',\n 'DASH',\n 'USDT_TRC20',\n 'USDT_ERC20',\n 'USDT_BEP20',\n 'USDT_POLYGON',\n 'USDT_SOL',\n 'USDC_ERC20',\n 'USDC_TRC20',\n 'USDC_BEP20',\n 'USDC_POLYGON',\n 'USDC_SOL',\n 'DAI_ERC20',\n 'BITCOIN_LN',\n] as const;\n\nexport type CoinGatewayKey = typeof COIN_GATEWAY_KEYS[number];\nexport type TokenGatewayKey = typeof TOKEN_GATEWAY_KEYS[number];\nexport type CryptoGatewayKey = typeof CRYPTO_GATEWAY_KEYS[number];\nexport type LegacyCryptoGatewayKey = typeof LEGACY_CRYPTO_GATEWAY_KEYS[number];\nexport type CryptoProviderKey = typeof CRYPTO_PROVIDER_KEYS[number];\nexport type ManagedCryptoProviderKey = typeof MANAGED_CRYPTO_PROVIDER_KEYS[number];\nexport type CryptoProviderGatewayKey = typeof CRYPTO_PROVIDER_GATEWAY_KEYS[number];\n\nexport const NOWPAYMENTS_DYNAMIC_GATEWAY_PREFIX = 'NOWPAYMENTS:' as const;\nexport type NowPaymentsDynamicGatewayKey = `${typeof NOWPAYMENTS_DYNAMIC_GATEWAY_PREFIX}${string}`;\n\nconst NOWPAYMENTS_CURRENCY_CODE_PATTERN = /^[A-Z0-9]{2,12}$/;\n\nexport function buildNowPaymentsDynamicGatewayKey(\n currencyCode: string,\n): NowPaymentsDynamicGatewayKey | null {\n const normalizedCode = currencyCode.trim().toUpperCase();\n if (!NOWPAYMENTS_CURRENCY_CODE_PATTERN.test(normalizedCode)) {\n return null;\n }\n\n return `${NOWPAYMENTS_DYNAMIC_GATEWAY_PREFIX}${normalizedCode}`;\n}\n\nexport function parseNowPaymentsDynamicGatewayKey(gateway: string): string | null {\n const normalized = gateway.trim().toUpperCase();\n if (!normalized.startsWith(NOWPAYMENTS_DYNAMIC_GATEWAY_PREFIX)) {\n return null;\n }\n\n const code = normalized.slice(NOWPAYMENTS_DYNAMIC_GATEWAY_PREFIX.length);\n return NOWPAYMENTS_CURRENCY_CODE_PATTERN.test(code) ? code.toLowerCase() : null;\n}\n\nexport function isNowPaymentsDynamicGatewayKey(\n gateway: string,\n): gateway is NowPaymentsDynamicGatewayKey {\n return parseNowPaymentsDynamicGatewayKey(gateway) !== null;\n}\n\nexport const DEFAULT_NOWPAYMENTS_CRYPTO_GATEWAY_KEYS = CRYPTO_GATEWAY_KEYS;\n\nexport const DEFAULT_CRYPTOMUS_CRYPTO_GATEWAY_KEYS = [\n 'BITCOIN',\n 'LITECOIN',\n 'ETHEREUM',\n 'TRON',\n 'SOLANA',\n 'POLYGON',\n 'BINANCE_COIN',\n 'BITCOIN_CASH',\n 'MONERO',\n 'RIPPLE',\n 'DOGECOIN',\n 'USDT_TRC20',\n 'USDT_ERC20',\n 'USDT_BEP20',\n 'USDT_POLYGON',\n 'USDT_SOL',\n 'USDC_ERC20',\n 'USDC_BEP20',\n 'USDC_POLYGON',\n 'DAI_ERC20',\n] as const;\n\nexport const DEFAULT_OXAPAY_CRYPTO_GATEWAY_KEYS = [\n 'BITCOIN',\n 'LITECOIN',\n 'ETHEREUM',\n 'TRON',\n 'SOLANA',\n 'POLYGON',\n 'BINANCE_COIN',\n 'BITCOIN_CASH',\n 'MONERO',\n 'RIPPLE',\n 'DOGECOIN',\n 'USDT_TRC20',\n 'USDT_ERC20',\n 'USDT_BEP20',\n 'USDT_POLYGON',\n 'USDC_ERC20',\n] as const;\n\nexport const DEFAULT_PROVIDER_GATEWAY_SELECTIONS = {\n NOWPAYMENTS: DEFAULT_NOWPAYMENTS_CRYPTO_GATEWAY_KEYS,\n NOWPAYMENTS_WHITELABEL: DEFAULT_NOWPAYMENTS_CRYPTO_GATEWAY_KEYS,\n CRYPTOMUS: DEFAULT_CRYPTOMUS_CRYPTO_GATEWAY_KEYS,\n OXAPAY: DEFAULT_OXAPAY_CRYPTO_GATEWAY_KEYS,\n} as const;\n\nexport const POPULAR_PLATFORM_MANAGED_CRYPTO_GATEWAY_KEYS = [\n 'BITCOIN',\n 'LITECOIN',\n 'ETHEREUM',\n 'USDT_TRC20',\n 'USDT_ERC20',\n] as const;\n\nexport const CHECKOUT_METHOD_ORDER_KEYS = [\n 'STRIPE',\n 'PAYPAL',\n 'PAYPAL_FF',\n 'MOLLIE',\n 'AUTHORIZENET',\n 'NMI',\n 'SQUARE',\n 'SUMUP',\n 'SHOPIFY',\n 'PANDABASE',\n 'DEBLOMASSI',\n 'SHOPPEXPAY',\n 'MONEYMOTION',\n 'OVGC',\n 'WHOP',\n 'DODO',\n 'MAVERICK',\n 'CASHAPP',\n 'VENMO',\n 'CRYPTO',\n 'CUSTOMER_BALANCE',\n 'EXTERNAL',\n 'MANUAL',\n] as const;\n\n/**\n * Gateway implementations that remain in the codebase for historical payment\n * reads and webhook reconciliation, but cannot be configured or used for new\n * payments.\n */\nexport const DISABLED_PAYMENT_GATEWAY_KEYS = ['PANDABASE', 'STORRIK'] as const;\n\nconst DISABLED_PAYMENT_GATEWAY_KEY_SET = new Set<string>(\n DISABLED_PAYMENT_GATEWAY_KEYS,\n);\n\nexport function isDisabledPaymentGateway(gateway: string): boolean {\n return DISABLED_PAYMENT_GATEWAY_KEY_SET.has(gateway.trim().toUpperCase());\n}\n\n/**\n * Gateway implementations that remain in the codebase but must not be\n * advertised or selectable in merchant and buyer UI.\n */\nexport const RETIRED_UI_PAYMENT_GATEWAY_KEYS = [\n 'SHOPPEXPAY',\n ...DISABLED_PAYMENT_GATEWAY_KEYS,\n] as const;\n\nconst RETIRED_UI_PAYMENT_GATEWAY_KEY_SET = new Set<string>(\n RETIRED_UI_PAYMENT_GATEWAY_KEYS,\n);\n\nexport function isRetiredUiPaymentGateway(gateway: string): boolean {\n return RETIRED_UI_PAYMENT_GATEWAY_KEY_SET.has(gateway.trim().toUpperCase());\n}\n\nexport const DEFAULT_PAYPAL_FF_MANAGED_IPN_URL = 'https://paypal-ff.myshoppex.io';\n\nexport type CheckoutMethodOrderKey = typeof CHECKOUT_METHOD_ORDER_KEYS[number];\nexport type WritableCheckoutMethodOrderKey = Exclude<\n CheckoutMethodOrderKey,\n typeof DISABLED_PAYMENT_GATEWAY_KEYS[number]\n>;\n\nexport const WRITABLE_CHECKOUT_METHOD_ORDER_KEYS = CHECKOUT_METHOD_ORDER_KEYS.filter(\n (gateway): gateway is WritableCheckoutMethodOrderKey => !isDisabledPaymentGateway(gateway),\n);\n\nexport interface StoredPaymentGatewayRow {\n provider?: string | null;\n is_active?: boolean | number | string | null;\n isActive?: boolean | number | string | null;\n external_id?: string | null;\n externalId?: string | null;\n has_credentials?: boolean | number | string | null;\n hasCredentials?: boolean | number | string | null;\n has_settings?: boolean | number | string | null;\n hasSettings?: boolean | number | string | null;\n}\n\nexport interface OxapayCheckoutGatewayInfo {\n gateway_key?: string;\n gatewayKey?: string;\n display_name?: string;\n displayName?: string;\n symbol?: string;\n network?: string;\n network_name?: string | null;\n networkName?: string | null;\n required_confirmations?: number | null;\n requiredConfirmations?: number | null;\n deposit_min?: number | null;\n depositMin?: number | null;\n withdraw_min?: number | null;\n withdrawMin?: number | null;\n withdraw_fee?: number | null;\n withdrawFee?: number | null;\n}\n\nexport interface PaymentGatewaySecretRef {\n set: boolean;\n}\n\nexport interface PaymentGatewayHealth {\n status: 'READY' | 'NEEDS_ATTENTION';\n code?: string;\n message?: string;\n checked_at?: string;\n}\n\nexport interface PaymentGatewayState {\n provider: string;\n type: string;\n enabled: boolean;\n connected: boolean;\n credentials: Record<string, PaymentGatewaySecretRef>;\n public_config: Record<string, unknown>;\n webhook?: Record<string, unknown>;\n health?: PaymentGatewayHealth;\n}\n\nexport type GatewayIntegrationType =\n | 'OAUTH'\n | 'API_KEY'\n | 'SDK'\n | 'LEGACY'\n | 'DIRECT'\n | 'FORWARDING'\n | 'AGGREGATOR';\n\nexport interface NormalizedPaymentGatewayState {\n provider: string;\n id: string;\n type: string;\n name: string;\n enabled: boolean;\n connected: boolean;\n health_status?: 'READY' | 'NEEDS_ATTENTION';\n health_code?: string;\n health_message?: string;\n health_checked_at?: string;\n created_at: string;\n updated_at: string;\n integration_type?: 'SDK' | 'LEGACY';\n config?: Record<string, unknown>;\n}\n\nconst COIN_GATEWAY_KEY_SET = new Set<string>(COIN_GATEWAY_KEYS);\nconst TOKEN_GATEWAY_KEY_SET = new Set<string>(TOKEN_GATEWAY_KEYS);\nconst CRYPTO_GATEWAY_KEY_SET = new Set<string>(CRYPTO_GATEWAY_KEYS);\nconst LEGACY_CRYPTO_GATEWAY_KEY_SET = new Set<string>(LEGACY_CRYPTO_GATEWAY_KEYS);\nconst CRYPTO_PROVIDER_KEY_SET = new Set<string>(CRYPTO_PROVIDER_KEYS);\nconst MANAGED_CRYPTO_PROVIDER_KEY_SET = new Set<string>(MANAGED_CRYPTO_PROVIDER_KEYS);\nconst CRYPTO_PROVIDER_GATEWAY_KEY_SET = new Set<string>(CRYPTO_PROVIDER_GATEWAY_KEYS);\nconst CONCRETE_CRYPTO_GATEWAY_KEY_SET = new Set<string>(CONCRETE_CRYPTO_GATEWAY_KEYS);\nconst EMBED_CRYPTO_GATEWAY_KEY_SET = new Set<string>(EMBED_CRYPTO_GATEWAY_KEYS);\nconst GENERIC_STABLECOIN_GATEWAY_KEY_SET = new Set<string>(GENERIC_STABLECOIN_GATEWAY_KEYS);\nconst CHECKOUT_METHOD_ORDER_KEY_SET = new Set<string>(CHECKOUT_METHOD_ORDER_KEYS);\nconst CHECKOUT_METHOD_GROUP_BY_GATEWAY: Record<string, CheckoutMethodOrderKey> = {\n STRIPE: 'STRIPE',\n PAYPAL: 'PAYPAL',\n PAYPAL_FF: 'PAYPAL_FF',\n MOLLIE: 'MOLLIE',\n AUTHORIZENET: 'AUTHORIZENET',\n NMI: 'NMI',\n SQUARE: 'SQUARE',\n SUMUP: 'SUMUP',\n SHOPIFY: 'SHOPIFY',\n PANDABASE: 'PANDABASE',\n DEBLOMASSI: 'DEBLOMASSI',\n SHOPPEXPAY: 'SHOPPEXPAY',\n MONEYMOTION: 'MONEYMOTION',\n OVGC: 'OVGC',\n WHOP: 'WHOP',\n DODO: 'DODO',\n MAVERICK: 'MAVERICK',\n CASH_APP: 'CASHAPP',\n VENMO: 'VENMO',\n CUSTOMER_BALANCE: 'CUSTOMER_BALANCE',\n};\n\nconst LEGACY_GATEWAY_ALIASES: Record<string, string> = {\n CASHAPP: 'CASH_APP',\n PAYPAL_CREDIT_CARD: 'PAYPAL',\n EUTHEREUM: 'ETHEREUM',\n USDT_MATIC: 'USDT_POLYGON',\n USDC_MATIC: 'USDC_POLYGON',\n};\n\nfunction assertUniqueEntries(name: string, values: readonly string[]) {\n if (new Set(values).size !== values.length) {\n throw new Error(`${name} contains duplicate entries`);\n }\n}\n\nassertUniqueEntries('COIN_GATEWAY_KEYS', COIN_GATEWAY_KEYS);\nassertUniqueEntries('TOKEN_GATEWAY_KEYS', TOKEN_GATEWAY_KEYS);\nassertUniqueEntries('CRYPTO_GATEWAY_KEYS', CRYPTO_GATEWAY_KEYS);\nassertUniqueEntries('LEGACY_CRYPTO_GATEWAY_KEYS', LEGACY_CRYPTO_GATEWAY_KEYS);\nassertUniqueEntries('CRYPTO_PROVIDER_KEYS', CRYPTO_PROVIDER_KEYS);\nassertUniqueEntries('MANAGED_CRYPTO_PROVIDER_KEYS', MANAGED_CRYPTO_PROVIDER_KEYS);\nassertUniqueEntries('CRYPTO_PROVIDER_GATEWAY_KEYS', CRYPTO_PROVIDER_GATEWAY_KEYS);\nassertUniqueEntries('DEFAULT_NOWPAYMENTS_CRYPTO_GATEWAY_KEYS', DEFAULT_NOWPAYMENTS_CRYPTO_GATEWAY_KEYS);\nassertUniqueEntries('DEFAULT_CRYPTOMUS_CRYPTO_GATEWAY_KEYS', DEFAULT_CRYPTOMUS_CRYPTO_GATEWAY_KEYS);\nassertUniqueEntries('DEFAULT_OXAPAY_CRYPTO_GATEWAY_KEYS', DEFAULT_OXAPAY_CRYPTO_GATEWAY_KEYS);\n\nfor (const key of CRYPTO_GATEWAY_KEYS) {\n if (!COIN_GATEWAY_KEY_SET.has(key) && !TOKEN_GATEWAY_KEY_SET.has(key)) {\n throw new Error(`CRYPTO_GATEWAY_KEYS contains an unclassified gateway: ${key}`);\n }\n}\n\nexport function parseGatewayList(input: unknown): string[] {\n if (Array.isArray(input)) {\n return input.filter((entry): entry is string => typeof entry === 'string');\n }\n\n if (typeof input !== 'string') {\n return [];\n }\n\n const trimmed = input.trim();\n if (!trimmed) {\n return [];\n }\n\n if (trimmed.startsWith('[') && trimmed.endsWith(']')) {\n try {\n const parsed = JSON.parse(trimmed) as unknown;\n if (Array.isArray(parsed)) {\n return parsed.filter((entry): entry is string => typeof entry === 'string');\n }\n } catch {\n // Fallback to comma-separated parsing.\n }\n }\n\n return trimmed\n .split(',')\n .map((entry) => entry.trim())\n .filter(Boolean);\n}\n\nexport function normalizeGatewayKey(input: string): string {\n const trimmed = input.trim();\n if (!trimmed) {\n return '';\n }\n\n if (/^manual:/i.test(trimmed)) {\n const manualId = trimmed.slice(trimmed.indexOf(':') + 1).trim();\n return manualId ? `MANUAL:${manualId}` : 'MANUAL';\n }\n\n if (/^external:/i.test(trimmed)) {\n const adapterId = parseExternalPaymentAdapterGatewayKey(trimmed);\n return adapterId\n ? `${EXTERNAL_PAYMENT_ADAPTER_GATEWAY_PREFIX}${adapterId}`\n : trimmed.toUpperCase();\n }\n\n let normalized = trimmed.toUpperCase();\n\n const stablecoinNetworkMatch = normalized.match(/^(USDT|USDC|DAI):([A-Z0-9_]+)$/);\n if (stablecoinNetworkMatch) {\n const [, asset, rawNetwork] = stablecoinNetworkMatch;\n const network = rawNetwork === 'MATIC' ? 'POLYGON' : rawNetwork;\n normalized = `${asset}_${network}`;\n }\n\n return LEGACY_GATEWAY_ALIASES[normalized] ?? normalized;\n}\n\nexport function normalizeGatewayRestrictionValues(values: readonly string[]): string[] {\n const normalized = new Set<string>();\n\n for (const value of values) {\n const gateway = normalizeGatewayKey(value);\n if (gateway) {\n normalized.add(gateway);\n }\n }\n\n return [...normalized];\n}\n\nexport function normalizeGatewayRestrictionInput(input: unknown): string[] | null {\n const normalized = normalizeGatewayRestrictionValues(parseGatewayList(input));\n return normalized.length > 0 ? normalized : null;\n}\n\nexport function isValidProductGatewaySelection(input: string): boolean {\n const normalized = normalizeGatewayKey(input);\n if (\n !normalized\n || normalized === 'NULL'\n || normalized === 'UNDEFINED'\n || isDisabledPaymentGateway(normalized)\n ) {\n return false;\n }\n\n return normalized === 'CUSTOMER_BALANCE'\n || normalized === 'CRYPTO'\n || normalized === 'EXTERNAL'\n || parseExternalPaymentAdapterGatewayKey(normalized) !== null\n || isFinanceGateway(normalized)\n || isCryptoProviderGatewayKey(normalized)\n || isConcreteCryptoGatewayKey(normalized)\n || isGenericStablecoinGatewayKey(normalized);\n}\n\nexport function findInvalidProductGatewaySelections(input: unknown): string[] {\n return normalizeGatewayRestrictionValues(parseGatewayList(input))\n .filter((gateway) => !isValidProductGatewaySelection(gateway));\n}\n\n/**\n * Canonical persisted product restrictions. External write paths should reject\n * `invalid`; trusted repair/import paths may deliberately keep only `gateways`.\n */\nexport function partitionProductGatewaySelections(input: unknown): {\n gateways: string[];\n invalid: string[];\n} {\n const normalized = normalizeGatewayRestrictionValues(parseGatewayList(input));\n const gateways: string[] = [];\n const invalid: string[] = [];\n\n for (const gateway of normalized) {\n (isValidProductGatewaySelection(gateway) ? gateways : invalid).push(gateway);\n }\n\n return { gateways, invalid };\n}\n\nexport const FINANCE_GATEWAY_KEYS = [\n 'STRIPE', 'PAYPAL', 'PAYPAL_FF', 'SKRILL', 'CASHAPP', 'CASH_APP', 'PERFECT_MONEY',\n 'SQUARE', 'SUMUP', 'SHOPIFY', 'PANDABASE', 'DEBLOMASSI', 'SHOPPEXPAY', 'MONEYMOTION', 'OVGC', 'WHOP',\n 'DODO', 'MAVERICK', 'VENMO', 'MOLLIE', 'AUTHORIZENET', 'NMI',\n] as const;\n\nconst FINANCE_GATEWAY_KEY_SET = new Set<string>(\n FINANCE_GATEWAY_KEYS.map((gateway) => normalizeGatewayKey(gateway)),\n);\n\nexport function isFinanceGateway(gateway: string): boolean {\n const normalized = normalizeGatewayKey(gateway);\n return normalized === 'MANUAL'\n || normalized.startsWith('MANUAL:')\n || normalized === 'EXTERNAL'\n || parseExternalPaymentAdapterGatewayKey(normalized) !== null\n || FINANCE_GATEWAY_KEY_SET.has(normalized);\n}\n\nexport const VALID_PRODUCT_PAYMENT_GATEWAY_RESTRICTION_MODES = ['USE_STORE_DEFAULT', 'CUSTOM'] as const;\n\nexport type ProductPaymentGatewayRestrictionMode =\n (typeof VALID_PRODUCT_PAYMENT_GATEWAY_RESTRICTION_MODES)[number];\n\nexport function normalizeProductPaymentGatewayRestrictionMode(\n value: unknown,\n): ProductPaymentGatewayRestrictionMode {\n return value === 'CUSTOM' ? 'CUSTOM' : 'USE_STORE_DEFAULT';\n}\n\nexport function isProductGatewayRestrictionPublishable(\n mode: unknown,\n gateways: unknown,\n): boolean {\n return normalizeProductPaymentGatewayRestrictionMode(mode) !== 'CUSTOM'\n || normalizeGatewayRestrictionInput(gateways) !== null;\n}\n\nexport function isCoinGateway(gateway: string): gateway is CoinGatewayKey {\n return COIN_GATEWAY_KEY_SET.has(normalizeGatewayKey(gateway));\n}\n\nexport function isTokenGateway(gateway: string): gateway is TokenGatewayKey {\n return TOKEN_GATEWAY_KEY_SET.has(normalizeGatewayKey(gateway));\n}\n\nexport function isCryptoGateway(gateway: string): gateway is CryptoGatewayKey {\n return CRYPTO_GATEWAY_KEY_SET.has(normalizeGatewayKey(gateway));\n}\n\nexport function isProviderKey(gateway: string): gateway is CryptoProviderKey {\n return CRYPTO_PROVIDER_KEY_SET.has(normalizeGatewayKey(gateway));\n}\n\nexport function isManagedCryptoProviderKey(gateway: string): gateway is ManagedCryptoProviderKey {\n return MANAGED_CRYPTO_PROVIDER_KEY_SET.has(normalizeGatewayKey(gateway));\n}\n\nexport function isCryptoProviderGatewayKey(gateway: string): boolean {\n return CRYPTO_PROVIDER_GATEWAY_KEY_SET.has(normalizeGatewayKey(gateway));\n}\n\nexport function isGenericStablecoinGatewayKey(gateway: string): boolean {\n return GENERIC_STABLECOIN_GATEWAY_KEY_SET.has(normalizeGatewayKey(gateway));\n}\n\nexport function isConcreteCryptoGatewayKey(gateway: string): boolean {\n const normalizedGateway = normalizeGatewayKey(gateway);\n return isCryptoGateway(normalizedGateway)\n || LEGACY_CRYPTO_GATEWAY_KEY_SET.has(normalizedGateway)\n || CONCRETE_CRYPTO_GATEWAY_KEY_SET.has(normalizedGateway)\n || isNowPaymentsDynamicGatewayKey(normalizedGateway);\n}\n\nexport function isEmbedCryptoGatewayKey(gateway: string): boolean {\n // Exact-match on the frozen embed-v1 key set, NOT normalizeGatewayKey():\n // alias/colon rewriting (USDT:ERC20, USDT_MATIC, EUTHEREUM, …) would widen\n // the embed crypto boundary and auto-start crypto sessions for stored\n // gateway values the embed flow never accepted before.\n const exactGateway = gateway.trim().toUpperCase();\n return EMBED_CRYPTO_GATEWAY_KEY_SET.has(exactGateway)\n || isNowPaymentsDynamicGatewayKey(exactGateway);\n}\n\n/**\n * True for anything that resolves to a crypto payment, in every shape a gateway\n * key can take: a concrete coin (`BITCOIN`, `USDT:ERC20`), a generic stablecoin\n * whose chain the buyer still has to choose (`USDT`), and a provider key that\n * expands into a coin list (`OXAPAY`, `NOWPAYMENTS`, `CRYPTOMUS`).\n *\n * Use this — not `isConcreteCryptoGatewayKey` on its own — wherever the question\n * is \"may this be selected without the buyer choosing it?\". Selecting crypto\n * locks an exchange rate against a deposit address, so a caller that only\n * recognises concrete coins lets a provider key through and starts that session\n * anyway. Both halves of that mistake have been shipped before.\n */\nexport function isCryptoPaymentSelection(gateway: string): boolean {\n return isConcreteCryptoGatewayKey(gateway)\n || isGenericStablecoinGatewayKey(gateway)\n || isCryptoProviderGatewayKey(gateway);\n}\n\nexport function getConcreteCryptoGatewaySelections(gateways: Iterable<string>): string[] {\n const selected = new Set<string>();\n\n for (const gateway of gateways) {\n const normalized = normalizeGatewayKey(gateway);\n if (isConcreteCryptoGatewayKey(normalized)) {\n selected.add(normalized);\n }\n }\n\n return [...selected];\n}\n\n/**\n * External labels of crypto payment rails as emitted by the invoice read model\n * (resolveExternalCryptoRailLabel): WHITE_LABEL for managed provider rails and\n * NATIVE for self-hosted BTC/LTC nodes. These are rail labels, not gateway or\n * processor keys.\n */\nexport const CRYPTO_RAIL_GATEWAY_LABELS = ['WHITE_LABEL', 'NATIVE'] as const;\nexport type CryptoRailGatewayLabel = typeof CRYPTO_RAIL_GATEWAY_LABELS[number];\nconst CRYPTO_RAIL_GATEWAY_LABEL_SET = new Set<string>(CRYPTO_RAIL_GATEWAY_LABELS);\n\n/**\n * `PaymentProvider` enum value persisted for the self-hosted crypto rail. The\n * read model emits the 'NATIVE' rail label, while invoice and attempt rows carry\n * the provider value itself — both name the same rail.\n */\nexport const NATIVE_CRYPTO_PROVIDER_KEY = 'NATIVE_CRYPTO' as const;\n\n/** Processor keys persisted on crypto payment attempts (providers plus the NATIVE rail). */\nexport const CRYPTO_PAYMENT_PROCESSOR_KEYS = [...CRYPTO_PROVIDER_GATEWAY_KEYS, 'NATIVE'] as const;\nexport type CryptoPaymentProcessorKey = typeof CRYPTO_PAYMENT_PROCESSOR_KEYS[number];\nconst CRYPTO_PAYMENT_PROCESSOR_KEY_SET = new Set<string>(CRYPTO_PAYMENT_PROCESSOR_KEYS);\n\nexport function isCryptoRailGatewayLabel(value: string): value is CryptoRailGatewayLabel {\n return CRYPTO_RAIL_GATEWAY_LABEL_SET.has(normalizeGatewayKey(value));\n}\n\nexport function isCryptoPaymentProcessorKey(value: string): value is CryptoPaymentProcessorKey {\n return CRYPTO_PAYMENT_PROCESSOR_KEY_SET.has(normalizeGatewayKey(value));\n}\n\n/**\n * Single source of truth for \"does this invoice gateway value mean crypto\":\n * concrete coin/token keys (incl. legacy), generic stablecoin families,\n * provider gateway keys, and external rail labels. Consumers classifying\n * invoice rows by their public `gateway` value must use this instead of\n * maintaining local lists.\n */\nexport function isCryptoInvoiceGatewayLabel(value: string): boolean {\n const normalized = normalizeGatewayKey(value);\n return isConcreteCryptoGatewayKey(normalized)\n || GENERIC_STABLECOIN_GATEWAY_KEY_SET.has(normalized)\n || CRYPTO_PROVIDER_GATEWAY_KEY_SET.has(normalized)\n || CRYPTO_RAIL_GATEWAY_LABEL_SET.has(normalized)\n || normalized === NATIVE_CRYPTO_PROVIDER_KEY;\n}\n\nfunction getAvailableManualGatewaySelections(gateways: Iterable<string>): string[] {\n const selected = new Set<string>();\n\n for (const gateway of gateways) {\n const normalized = normalizeGatewayKey(gateway);\n if (normalized === 'MANUAL' || normalized.startsWith('MANUAL:')) {\n selected.add(normalized);\n }\n }\n\n return [...selected];\n}\n\nfunction getAvailableExternalAdapterSelections(gateways: Iterable<string>): string[] {\n const selected = new Set<string>();\n\n for (const gateway of gateways) {\n const normalized = normalizeGatewayKey(gateway);\n if (normalized === 'EXTERNAL' || parseExternalPaymentAdapterGatewayKey(normalized) !== null) {\n selected.add(normalized);\n }\n }\n\n return [...selected];\n}\n\nfunction getProviderScopedGatewaySelections(\n providerGateway: keyof typeof DEFAULT_PROVIDER_GATEWAY_SELECTIONS,\n availableGateways: string[],\n): string[] {\n const providerDefaults = DEFAULT_PROVIDER_GATEWAY_SELECTIONS[providerGateway];\n\n if (availableGateways.length === 0) {\n return [...providerDefaults];\n }\n\n const availableConcreteGateways = new Set(getConcreteCryptoGatewaySelections(availableGateways));\n return providerDefaults.filter((gateway) => availableConcreteGateways.has(gateway));\n}\n\nexport function expandGatewaySelection(\n gateway: string,\n options?: { availableGateways?: Iterable<string> },\n): string[] {\n const normalized = normalizeGatewayKey(gateway);\n if (!normalized) {\n return [];\n }\n\n const availableGateways = options?.availableGateways\n ? [...options.availableGateways].map((entry) => normalizeGatewayKey(entry)).filter(Boolean)\n : [];\n\n if (normalized === 'MANUAL') {\n return availableGateways.length > 0\n ? getAvailableManualGatewaySelections(availableGateways)\n : ['MANUAL'];\n }\n\n if (normalized.startsWith('MANUAL:')) {\n return [normalized];\n }\n\n if (normalized === 'EXTERNAL') {\n return availableGateways.length > 0\n ? getAvailableExternalAdapterSelections(availableGateways)\n : ['EXTERNAL'];\n }\n\n if (parseExternalPaymentAdapterGatewayKey(normalized) !== null) {\n return [normalized];\n }\n\n if (normalized.startsWith(EXTERNAL_PAYMENT_ADAPTER_GATEWAY_PREFIX)) {\n return [];\n }\n\n if (normalized === 'CRYPTO') {\n return availableGateways.length > 0\n ? getConcreteCryptoGatewaySelections(availableGateways)\n : [...CRYPTO_GATEWAY_KEYS];\n }\n\n if (isCryptoProviderGatewayKey(normalized)) {\n return getProviderScopedGatewaySelections(\n normalized as keyof typeof DEFAULT_PROVIDER_GATEWAY_SELECTIONS,\n availableGateways,\n );\n }\n\n if (isGenericStablecoinGatewayKey(normalized)) {\n const concreteGateways =\n GENERIC_STABLECOIN_GATEWAY_FAMILIES[\n normalized as keyof typeof GENERIC_STABLECOIN_GATEWAY_FAMILIES\n ];\n\n if (availableGateways.length > 0) {\n const availableSet = new Set(availableGateways);\n return concreteGateways.filter((entry) => availableSet.has(entry));\n }\n\n return [...concreteGateways];\n }\n\n return [normalized];\n}\n\nexport function resolveConcreteGatewaySelections(\n input: unknown,\n options?: { availableGateways?: Iterable<string> },\n): string[] | null {\n const normalized = normalizeGatewayRestrictionInput(input);\n if (!normalized) {\n return null;\n }\n\n const resolved = new Set<string>();\n for (const gateway of normalized) {\n for (const expanded of expandGatewaySelection(gateway, options)) {\n resolved.add(expanded);\n }\n }\n\n return [...resolved];\n}\n\nexport function normalizeCheckoutMethodOrder(\n input: Iterable<string> | null | undefined,\n): CheckoutMethodOrderKey[] {\n if (!input) {\n return [];\n }\n\n const normalized = new Set<CheckoutMethodOrderKey>();\n\n for (const entry of input) {\n if (typeof entry !== 'string') {\n continue;\n }\n\n const candidate = entry.trim().toUpperCase();\n if (CHECKOUT_METHOD_ORDER_KEY_SET.has(candidate)) {\n normalized.add(candidate as CheckoutMethodOrderKey);\n }\n }\n\n return [...normalized];\n}\n\nexport function resolveCheckoutMethodOrder(\n input: Iterable<string> | null | undefined,\n): CheckoutMethodOrderKey[] {\n const normalized = normalizeCheckoutMethodOrder(input);\n const resolved = [...normalized];\n\n for (const key of CHECKOUT_METHOD_ORDER_KEYS) {\n if (!resolved.includes(key)) {\n resolved.push(key);\n }\n }\n\n return resolved;\n}\n\nexport function getCheckoutMethodOrderGroup(\n gateway: string,\n): CheckoutMethodOrderKey | null {\n const normalized = normalizeGatewayKey(gateway);\n if (!normalized) {\n return null;\n }\n\n if (normalized === 'MANUAL' || normalized.startsWith('MANUAL:')) {\n return 'MANUAL';\n }\n\n if (normalized === 'EXTERNAL' || parseExternalPaymentAdapterGatewayKey(normalized) !== null) {\n return 'EXTERNAL';\n }\n\n if (isCryptoProviderGatewayKey(normalized) || isConcreteCryptoGatewayKey(normalized)) {\n return 'CRYPTO';\n }\n\n return CHECKOUT_METHOD_GROUP_BY_GATEWAY[normalized] ?? null;\n}\n\nexport function sortGatewaysByCheckoutMethodOrder(\n gateways: Iterable<string>,\n input: Iterable<string> | null | undefined,\n): string[] {\n const explicitOrder = normalizeCheckoutMethodOrder(input);\n if (explicitOrder.length === 0) {\n return [...gateways];\n }\n\n const resolvedOrder = resolveCheckoutMethodOrder(explicitOrder);\n const orderIndex = new Map(\n resolvedOrder.map((key, index) => [key, index] as const),\n );\n\n return [...gateways].sort((left, right) => {\n const leftGroup = getCheckoutMethodOrderGroup(left);\n const rightGroup = getCheckoutMethodOrderGroup(right);\n const leftIndex = leftGroup ? (orderIndex.get(leftGroup) ?? Number.MAX_SAFE_INTEGER) : Number.MAX_SAFE_INTEGER;\n const rightIndex = rightGroup ? (orderIndex.get(rightGroup) ?? Number.MAX_SAFE_INTEGER) : Number.MAX_SAFE_INTEGER;\n\n if (leftIndex !== rightIndex) {\n return leftIndex - rightIndex;\n }\n\n return 0;\n });\n}\n\nexport function getCheckoutMethodOrderKeysForGateways(\n gateways: Iterable<string>,\n input?: Iterable<string> | null,\n): CheckoutMethodOrderKey[] {\n const orderedGroups = new Set<CheckoutMethodOrderKey>();\n\n for (const gateway of sortGatewaysByCheckoutMethodOrder(gateways, input)) {\n const group = getCheckoutMethodOrderGroup(gateway);\n if (group) {\n orderedGroups.add(group);\n }\n }\n\n return [...orderedGroups];\n}\n\nexport function getCheckoutMethodOrderLabel(key: CheckoutMethodOrderKey): string {\n switch (key) {\n case 'STRIPE':\n return 'Credit / Debit Cards';\n case 'PAYPAL':\n return 'PayPal';\n case 'PAYPAL_FF':\n return 'PayPal F&F';\n case 'MOLLIE':\n return 'Mollie';\n case 'AUTHORIZENET':\n return 'Authorize.net';\n case 'NMI':\n return 'NMI';\n case 'SQUARE':\n return 'Square';\n case 'SUMUP':\n return 'SumUp';\n case 'SHOPIFY':\n return 'Shopify';\n case 'PANDABASE':\n return 'Pandabase';\n case 'DEBLOMASSI':\n return 'DebloMassi';\n case 'SHOPPEXPAY':\n return 'Card payment';\n case 'MONEYMOTION':\n return 'MoneyMotion';\n case 'OVGC':\n return 'OVGC Payments';\n case 'WHOP':\n return 'Whop';\n case 'DODO':\n return 'Dodo Payments';\n case 'MAVERICK':\n return 'Maverick Payments';\n case 'CASHAPP':\n return 'Cash App';\n case 'VENMO':\n return 'Venmo';\n case 'CRYPTO':\n return 'Crypto';\n case 'CUSTOMER_BALANCE':\n return 'Store Credit';\n case 'EXTERNAL':\n return 'External Providers';\n case 'MANUAL':\n return 'Manual Payment Methods';\n }\n}\n\nexport const SecretRefSchema = z.object({\n set: z.boolean(),\n});\n\nexport const PaymentGatewayHealthSchema = z.object({\n status: z.enum(['READY', 'NEEDS_ATTENTION']).optional(),\n code: z.string().optional(),\n message: z.string().optional(),\n checked_at: z.string().optional(),\n});\n\nexport const PaymentGatewayStateSchema = z.object({\n provider: z.string(),\n type: z.string(),\n enabled: z.boolean(),\n connected: z.boolean(),\n credentials: z.record(z.string(), SecretRefSchema),\n public_config: z.record(z.string(), z.unknown()),\n webhook: z.record(z.string(), z.unknown()).optional(),\n health: PaymentGatewayHealthSchema.optional(),\n});\n\nexport type PaymentGatewayStateFromSchema = z.infer<typeof PaymentGatewayStateSchema>;\n","import * as z from 'zod/v4';\n\n/** Canonical Shoppex hosted-checkout brand (matches `apps/checkout/app/globals.css` `--primary`). */\nexport const CHECKOUT_PLATFORM_BRAND_COLOR = '#7c3aed';\n\n/** Curated font label for Style Center controls (runtime loads Geist via `next/font`). */\nexport const CHECKOUT_PLATFORM_FONT_FAMILY = 'Geist';\n\n/** Stripe/PayPal appearance and CSS var() fallbacks when no merchant brand override exists. */\nexport const CHECKOUT_PLATFORM_BRAND_FALLBACK = CHECKOUT_PLATFORM_BRAND_COLOR;\n\n/** Runtime font stack when no merchant typography override exists. */\nexport const CHECKOUT_PLATFORM_FONT_STACK =\n 'var(--font-geist-sans, Geist), Geist, system-ui, sans-serif';\n\n/** Stripe appearance fontFamily (no CSS var() — provider SDK string). */\nexport const CHECKOUT_PLATFORM_STRIPE_FONT_FAMILY = 'Geist, system-ui, sans-serif';\n\nconst BRAND_DERIVED_TOKEN_KEYS: Partial<Record<string, string>> = {\n 'component.primaryButton.background': 'color.brand',\n 'component.radio.checkedFill': 'color.brand',\n};\n\n/**\n * Platform baseline values for unset checkout tokens.\n * Used by Style Center UI, validation, and documentation — not emitted to live CSS unless explicit.\n *\n * Every neutral below is a value from the hosted checkout's tonal ladder\n * (`apps/checkout/app/globals.css`, dark appearance). The zinc palette these\n * replace was a SECOND palette: the Style Center baseline painted `#18181b` /\n * `#27272a` / `#222222` over a checkout whose own surfaces are `--surface-0`\n * … `--surface-4`, so a shop that had never opened the Style Center saw the\n * old design repainted on top of the new one.\n *\n * They are also PURE neutrals — R = G = B — for the same reason the ladder is:\n * a baseline that carries a hue is a hue painted over every merchant's brand,\n * and this file is what an untouched shop actually renders. The white alphas\n * below follow the same rule; they used to be a warm `255,252,248`, which is\n * what turned every uncustomised chip and product plate a shade of brown.\n */\nexport const CHECKOUT_PLATFORM_BASELINE: Partial<Record<string, string | number>> = {\n 'color.brand': CHECKOUT_PLATFORM_BRAND_COLOR,\n 'color.brandContrast': '#ffffff',\n // `--surface-1`: the ground a column sits on.\n 'color.background': '#111111',\n // `--surface-0`: the working panel the buyer pays in.\n 'color.surface': '#1b1b1b',\n // `--card`: a panel raised above that ground.\n 'color.surfaceRaised': '#222222',\n 'color.text': '#f5f5f5',\n 'color.textMuted': '#a1a1a1',\n 'color.border': '#2c2c2c',\n 'color.focus': CHECKOUT_PLATFORM_BRAND_COLOR,\n 'color.success': '#22c55e',\n 'color.warning': '#f59e0b',\n 'color.error': '#ef4444',\n 'typography.fontFamily': CHECKOUT_PLATFORM_FONT_FAMILY,\n 'typography.baseSize': 14,\n // 10 across the board, and the same 10 the token definitions below carry:\n // this map is read by `resolveCheckoutStyleTokenValue` while the emitted CSS\n // reads `definition.default`, so a disagreement between them means the\n // Style Center shows one radius and the buyer sees another. The checkout has\n // TWO radii — 8 for marks under 16px, 10 for every control and surface — and\n // a button is a control.\n //\n // Down from 12 with `--radius-lg` in apps/checkout/app/globals.css, and the\n // two have to move together: the slot layer paints\n // `var(--spx-checkout-card-radius, var(--radius-lg))` with `!important`, so\n // THIS value is the one a hosted buyer actually sees.\n 'shape.buttonRadius': 10,\n 'shape.inputRadius': 10,\n 'shape.cardRadius': 10,\n 'spacing.density': 'comfortable',\n 'spacing.controlHeight': 48,\n 'component.primaryButton.text': '#ffffff',\n 'component.input.background': '#292929',\n 'component.input.border': '#2c2c2c',\n 'component.input.focusRing': 'rgba(124,58,237,0.35)',\n 'component.productCard.background': 'rgba(255,255,255,0.03)',\n 'component.productCard.border': 'rgba(255,255,255,0.06)',\n 'component.productCard.shadow': 'none',\n 'component.productImage.background': 'rgba(255,255,255,0.06)',\n 'component.productImage.border': 'rgba(255,255,255,0.04)',\n 'component.productImage.icon': 'rgba(250,250,250,0.4)',\n 'component.brandAvatar.background': 'rgba(255,255,255,0.06)',\n 'component.brandAvatar.text': '#ffffff',\n 'component.brandAvatar.border': 'rgba(255,255,255,0.1)',\n 'component.pill.background': 'rgba(255,255,255,0.04)',\n 'component.pill.border': 'rgba(255,255,255,0.08)',\n 'component.pill.text': '#a1a1a1',\n 'component.errorBanner.background': 'rgba(239,68,68,0.1)',\n 'component.errorBanner.border': 'rgba(239,68,68,0.2)',\n 'component.errorBanner.text': '#ef4444',\n 'component.radio.idleRing': 'rgba(161,161,161,0.5)',\n 'component.radio.checkedIcon': '#ffffff',\n 'component.divider.color': 'rgba(255,255,255,0.06)',\n};\n\nexport function isExplicitCheckoutStyleTokenValue(value: unknown): value is string | number {\n if (typeof value === 'number' && Number.isFinite(value)) return true;\n if (typeof value === 'string') return value.trim().length > 0;\n return false;\n}\n\nfunction resolveCheckoutStyleBrandDerivedTokenKey(key: string): string | undefined {\n return BRAND_DERIVED_TOKEN_KEYS[key];\n}\n\nexport const checkoutStyleSurfaceValues = ['checkout', 'payment_link', 'embed'] as const;\nexport const checkoutStyleDensityValues = ['comfortable', 'compact'] as const;\n\nexport const checkoutStyleModeValues = ['light', 'dark', 'system'] as const;\nexport const checkoutStylePaymentLinkHeroPositionValues = ['top', 'side', 'background'] as const;\nexport const embedCloseButtonStyleValues = ['ghost', 'outlined', 'filled'] as const;\nexport const embedMobileLayoutValues = ['sheet', 'fullscreen', 'center'] as const;\nexport const embedContentVisibilityValues = ['visible', 'hidden'] as const;\nexport const checkoutStyleManagedAssetHostValues = ['assets.shoppex.io', 'cdn.shoppex.io', 'imagedelivery.net'] as const;\n\nexport const CheckoutStyleSurfaceSchema = z.enum(checkoutStyleSurfaceValues);\nexport const CheckoutStyleDensitySchema = z.enum(checkoutStyleDensityValues);\nexport const CheckoutStyleModeSchema = z.enum(checkoutStyleModeValues);\nexport const CheckoutStylePaymentLinkHeroPositionSchema = z.enum(checkoutStylePaymentLinkHeroPositionValues);\nexport const EmbedCloseButtonStyleSchema = z.enum(embedCloseButtonStyleValues);\nexport const EmbedMobileLayoutSchema = z.enum(embedMobileLayoutValues);\nexport const EmbedContentVisibilitySchema = z.enum(embedContentVisibilityValues);\n\nexport type CheckoutStyleSurface = z.infer<typeof CheckoutStyleSurfaceSchema>;\nexport type CheckoutStyleDensity = z.infer<typeof CheckoutStyleDensitySchema>;\nexport type CheckoutStyleMode = z.infer<typeof CheckoutStyleModeSchema>;\nexport type CheckoutStylePaymentLinkHeroPosition = z.infer<typeof CheckoutStylePaymentLinkHeroPositionSchema>;\nexport type EmbedCloseButtonStyle = z.infer<typeof EmbedCloseButtonStyleSchema>;\nexport type EmbedMobileLayout = z.infer<typeof EmbedMobileLayoutSchema>;\nexport type EmbedContentVisibility = z.infer<typeof EmbedContentVisibilitySchema>;\n\nexport const CHECKOUT_STYLE_TOKEN_SCHEMA_VERSION = 1;\nexport const SHOPPEX_STYLE_THEME_EXPORT_FORMAT_VERSION = 2;\n\nexport type CheckoutStyleTokenType = 'asset_url' | 'color' | 'font' | 'number' | 'select' | 'shadow';\nexport type CheckoutStyleTokenGroup = 'asset' | 'brand' | 'color' | 'typography' | 'shape' | 'spacing' | 'component' | 'embed';\n\nexport type CheckoutStyleCssTokenDefinition = {\n key: string;\n cssVar: `--spx-checkout-${string}` | `--spx-embed-${string}`;\n group: Exclude<CheckoutStyleTokenGroup, 'asset'>;\n type: Exclude<CheckoutStyleTokenType, 'asset_url'>;\n default: string | number;\n min?: number;\n max?: number;\n step?: number;\n unit?: 'px' | 'rem';\n allowedValues?: readonly string[];\n protected?: boolean;\n};\n\nexport type CheckoutStyleAssetTokenDefinition = {\n key: string;\n group: 'asset';\n type: 'asset_url' | 'number' | 'select';\n default: string | number | null;\n accept?: readonly string[];\n maxBytes?: number;\n min?: number;\n max?: number;\n step?: number;\n unit?: 'px';\n allowedValues?: readonly string[];\n surface?: CheckoutStyleSurface;\n};\n\nexport type CheckoutStyleTokenDefinition = CheckoutStyleCssTokenDefinition | CheckoutStyleAssetTokenDefinition;\n\nexport const checkoutStyleTokenDefinitions = [\n { key: 'color.brand', cssVar: '--spx-checkout-brand', group: 'brand', type: 'color', default: CHECKOUT_PLATFORM_BRAND_COLOR },\n { key: 'color.brandContrast', cssVar: '--spx-checkout-brand-contrast', group: 'brand', type: 'color', default: '#ffffff', protected: true },\n // Empty default → CSS variable is omitted by createCheckoutStyleCssVariables,\n // so the layout's `var(--spx-checkout-bg, fallback)` resolves to the original\n // Tailwind/ambient-gradient fallback for shops that haven't customised the\n // background. Setting an explicit hex would clobber the ambient gradient and\n // the right-panel `--surface-2` accent for every default-theme checkout.\n { key: 'color.background', cssVar: '--spx-checkout-bg', group: 'color', type: 'color', default: '' },\n // The four neutrals below are the DARK appearance of the hosted checkout's\n // tonal ladder (`apps/checkout/app/globals.css`); the light values sit in\n // CHECKOUT_PLATFORM_BASELINE_LIGHT_DEFAULTS. They are materialised into the\n // live checkout root, so they are what a shop with no Style Center theme\n // actually renders — which is why each one has to name the SAME rung the\n // component paints, not a palette of its own.\n // surface → `--surface-0`, the working panel the buyer pays in\n // surfaceRaised → `--card`, a panel raised above that panel\n // (the provider widget frame and its loading skeleton)\n // text → `--foreground`\n // textMuted → `--muted-foreground`\n // border → `--border`\n { key: 'color.surface', cssVar: '--spx-checkout-surface', group: 'color', type: 'color', default: '#1b1b1b' },\n { key: 'color.surfaceRaised', cssVar: '--spx-checkout-surface-raised', group: 'color', type: 'color', default: '#222222' },\n { key: 'color.text', cssVar: '--spx-checkout-text', group: 'color', type: 'color', default: '#f5f5f5', protected: true },\n { key: 'color.textMuted', cssVar: '--spx-checkout-text-muted', group: 'color', type: 'color', default: '#a1a1a1' },\n // Never '': the border token feeds runtime-style fallbacks for inputs,\n // provider widgets and buttons, and an unset value turns those slots'\n // `var(--spx-checkout-border, …)` chains loose. The hosted checkout draws\n // almost no hairlines any more — the slots that still do read this, the rest\n // resolve their border to `transparent` in the system CSS.\n { key: 'color.border', cssVar: '--spx-checkout-border', group: 'color', type: 'color', default: '#2c2c2c' },\n { key: 'color.focus', cssVar: '--spx-checkout-focus', group: 'color', type: 'color', default: CHECKOUT_PLATFORM_BRAND_COLOR, protected: true },\n { key: 'color.success', cssVar: '--spx-checkout-success', group: 'color', type: 'color', default: '#22c55e', protected: true },\n { key: 'color.warning', cssVar: '--spx-checkout-warning', group: 'color', type: 'color', default: '#f59e0b', protected: true },\n { key: 'color.error', cssVar: '--spx-checkout-error', group: 'color', type: 'color', default: '#ef4444', protected: true },\n { key: 'typography.fontFamily', cssVar: '--spx-checkout-font', group: 'typography', type: 'font', default: CHECKOUT_PLATFORM_FONT_FAMILY },\n // Optional Google Fonts family. Empty default → CSS variable is omitted\n // so the curated fontFamily wins. When set, the storefront also injects\n // a <link rel=\"stylesheet\"> to fonts.googleapis.com so the family is\n // actually loaded.\n { key: 'typography.googleFontFamily', cssVar: '--spx-checkout-google-font', group: 'typography', type: 'font', default: '' },\n { key: 'typography.baseSize', cssVar: '--spx-checkout-font-size', group: 'typography', type: 'number', default: 14, min: 12, max: 18, step: 1, unit: 'px' },\n // 12px, not 8, for the same reason as the input below: the hosted pay CTA is\n // `rounded-xl` and this token is materialised over every slotted button. At 8\n // the store-credit and manual actions rendered one step tighter than the\n // field directly above them and than the CTA they stand in for.\n { key: 'shape.buttonRadius', cssVar: '--spx-checkout-button-radius', group: 'shape', type: 'number', default: 10, min: 0, max: 24, step: 1, unit: 'px' },\n // 12px, not 8: the hosted `Input` primitive is `rounded-lg`, and this token is\n // materialised over it. At 8 the system CSS rounded every field one step\n // tighter than the component that drew it.\n { key: 'shape.inputRadius', cssVar: '--spx-checkout-input-radius', group: 'shape', type: 'number', default: 10, min: 0, max: 24, step: 1, unit: 'px' },\n { key: 'shape.cardRadius', cssVar: '--spx-checkout-card-radius', group: 'shape', type: 'number', default: 10, min: 0, max: 28, step: 1, unit: 'px' },\n {\n key: 'spacing.density',\n cssVar: '--spx-checkout-density',\n group: 'spacing',\n type: 'select',\n default: 'comfortable',\n allowedValues: checkoutStyleDensityValues,\n },\n { key: 'spacing.controlHeight', cssVar: '--spx-checkout-control-height', group: 'spacing', type: 'number', default: 48, min: 36, max: 56, step: 2, unit: 'px' },\n { key: 'component.primaryButton.background', cssVar: '--spx-checkout-button-bg', group: 'component', type: 'color', default: '', protected: true },\n { key: 'component.primaryButton.text', cssVar: '--spx-checkout-button-text', group: 'component', type: 'color', default: '#ffffff', protected: true },\n { key: 'component.input.background', cssVar: '--spx-checkout-input-bg', group: 'component', type: 'color', default: '#292929' },\n { key: 'component.input.border', cssVar: '--spx-checkout-input-border', group: 'component', type: 'color', default: '#2c2c2c' },\n { key: 'component.input.focusRing', cssVar: '--spx-checkout-input-focus-ring', group: 'component', type: 'color', default: '' },\n // Default '' is filtered out by the preview-iframe normaliser, so the\n // CSS fallback chain on [data-spx-slot=\"summary.panel\"] resolves to\n // --spx-checkout-bg when no merchant override is set. A merchant who\n // only edits color.background therefore sees the aside follow that\n // change without an explicit summary override.\n { key: 'component.summary.background', cssVar: '--spx-checkout-summary-bg', group: 'component', type: 'color', default: '' },\n { key: 'component.paymentMethod.background', cssVar: '--spx-checkout-payment-method-bg', group: 'component', type: 'color', default: '' },\n { key: 'component.paymentMethod.cardBackground', cssVar: '--spx-checkout-payment-method-card-bg', group: 'component', type: 'color', default: '' },\n { key: 'component.paymentMethod.border', cssVar: '--spx-checkout-payment-method-border', group: 'component', type: 'color', default: '' },\n { key: 'component.paymentMethod.selectedBackground', cssVar: '--spx-checkout-payment-method-selected-bg', group: 'component', type: 'color', default: '' },\n { key: 'component.checkoutHeader.background', cssVar: '--spx-checkout-embed-header-bg', group: 'component', type: 'color', default: '' },\n { key: 'component.checkoutHeader.text', cssVar: '--spx-checkout-embed-header-text', group: 'component', type: 'color', default: '' },\n { key: 'component.productCard.background', cssVar: '--spx-checkout-product-card-bg', group: 'component', type: 'color', default: 'rgba(255,255,255,0.03)' },\n { key: 'component.productCard.border', cssVar: '--spx-checkout-product-card-border', group: 'component', type: 'color', default: 'rgba(255,255,255,0.06)' },\n { key: 'component.productCard.shadow', cssVar: '--spx-checkout-product-card-shadow', group: 'component', type: 'shadow', default: 'none' },\n { key: 'component.productImage.background', cssVar: '--spx-checkout-product-image-bg', group: 'component', type: 'color', default: 'rgba(255,255,255,0.06)' },\n { key: 'component.productImage.border', cssVar: '--spx-checkout-product-image-border', group: 'component', type: 'color', default: 'rgba(255,255,255,0.04)' },\n { key: 'component.productImage.icon', cssVar: '--spx-checkout-product-image-icon', group: 'component', type: 'color', default: 'rgba(250,250,250,0.4)' },\n { key: 'component.brandAvatar.background', cssVar: '--spx-checkout-brand-avatar-bg', group: 'component', type: 'color', default: 'rgba(255,255,255,0.06)' },\n { key: 'component.brandAvatar.text', cssVar: '--spx-checkout-brand-avatar-text', group: 'component', type: 'color', default: '#ffffff' },\n { key: 'component.brandAvatar.border', cssVar: '--spx-checkout-brand-avatar-border', group: 'component', type: 'color', default: 'rgba(255,255,255,0.1)' },\n { key: 'component.pill.background', cssVar: '--spx-checkout-pill-bg', group: 'component', type: 'color', default: 'rgba(255,255,255,0.04)' },\n { key: 'component.pill.border', cssVar: '--spx-checkout-pill-border', group: 'component', type: 'color', default: 'rgba(255,255,255,0.08)' },\n { key: 'component.pill.text', cssVar: '--spx-checkout-pill-text', group: 'component', type: 'color', default: '#a1a1a1' },\n { key: 'component.errorBanner.background', cssVar: '--spx-checkout-error-bg', group: 'component', type: 'color', default: 'rgba(239,68,68,0.1)' },\n { key: 'component.errorBanner.border', cssVar: '--spx-checkout-error-border', group: 'component', type: 'color', default: 'rgba(239,68,68,0.2)' },\n { key: 'component.errorBanner.text', cssVar: '--spx-checkout-error-text', group: 'component', type: 'color', default: '#ef4444' },\n { key: 'component.warningBanner.background', cssVar: '--spx-checkout-warning-bg', group: 'component', type: 'color', default: '' },\n { key: 'component.warningBanner.border', cssVar: '--spx-checkout-warning-border', group: 'component', type: 'color', default: '' },\n { key: 'component.warningBanner.text', cssVar: '--spx-checkout-warning-text', group: 'component', type: 'color', default: '' },\n { key: 'component.radio.idleRing', cssVar: '--spx-checkout-radio-idle-ring', group: 'component', type: 'color', default: 'rgba(161,161,161,0.5)' },\n { key: 'component.radio.checkedFill', cssVar: '--spx-checkout-radio-checked-fill', group: 'component', type: 'color', default: '' },\n { key: 'component.radio.checkedIcon', cssVar: '--spx-checkout-radio-checked-icon', group: 'component', type: 'color', default: '#ffffff' },\n { key: 'component.divider.color', cssVar: '--spx-checkout-divider', group: 'component', type: 'color', default: 'rgba(255,255,255,0.06)' },\n] as const satisfies readonly CheckoutStyleCssTokenDefinition[];\n\nexport const checkoutStyleAssetTokenDefinitions = [\n {\n key: 'brand.logoUrl',\n group: 'asset',\n type: 'asset_url',\n default: null,\n accept: ['image/png', 'image/jpeg', 'image/svg+xml', 'image/webp'],\n maxBytes: 512_000,\n },\n {\n key: 'brand.logoDarkUrl',\n group: 'asset',\n type: 'asset_url',\n default: null,\n accept: ['image/png', 'image/jpeg', 'image/svg+xml', 'image/webp'],\n maxBytes: 512_000,\n },\n {\n key: 'brand.logoMaxHeight',\n group: 'asset',\n type: 'number',\n default: 32,\n min: 16,\n max: 80,\n step: 2,\n unit: 'px',\n },\n {\n key: 'brand.faviconUrl',\n group: 'asset',\n type: 'asset_url',\n default: null,\n accept: ['image/png', 'image/x-icon', 'image/svg+xml'],\n maxBytes: 64_000,\n },\n {\n key: 'paymentLink.heroImageUrl',\n group: 'asset',\n type: 'asset_url',\n default: null,\n accept: ['image/png', 'image/jpeg', 'image/webp'],\n maxBytes: 1_048_576,\n surface: 'payment_link',\n },\n {\n key: 'paymentLink.heroPosition',\n group: 'asset',\n type: 'select',\n default: 'top',\n allowedValues: checkoutStylePaymentLinkHeroPositionValues,\n surface: 'payment_link',\n },\n] as const satisfies readonly CheckoutStyleAssetTokenDefinition[];\n\nexport const checkoutStyleControlTokenDefinitions = [\n ...checkoutStyleTokenDefinitions,\n ...checkoutStyleAssetTokenDefinitions,\n] as const satisfies readonly CheckoutStyleTokenDefinition[];\n\nexport type CheckoutStyleTokenKey = typeof checkoutStyleTokenDefinitions[number]['key'];\nexport type CheckoutStyleControlTokenKey = typeof checkoutStyleControlTokenDefinitions[number]['key'];\nexport type CheckoutStyleCssVariable = typeof checkoutStyleTokenDefinitions[number]['cssVar'];\n\nexport const embedStyleTokenDefinitions = [\n { key: 'embed.launcher.background', cssVar: '--spx-embed-launcher-background', group: 'embed', type: 'color', default: '#7c5cff' },\n { key: 'embed.launcher.text', cssVar: '--spx-embed-launcher-text', group: 'embed', type: 'color', default: '#ffffff', protected: true },\n { key: 'embed.launcher.radius', cssVar: '--spx-embed-launcher-radius', group: 'embed', type: 'number', default: 10, min: 0, max: 28, step: 1, unit: 'px' },\n { key: 'embed.launcher.paddingX', cssVar: '--spx-embed-launcher-padding-x', group: 'embed', type: 'number', default: 18, min: 8, max: 32, step: 1, unit: 'px' },\n { key: 'embed.launcher.paddingY', cssVar: '--spx-embed-launcher-padding-y', group: 'embed', type: 'number', default: 12, min: 6, max: 24, step: 1, unit: 'px' },\n { key: 'embed.launcher.shadow', cssVar: '--spx-embed-launcher-shadow', group: 'embed', type: 'shadow', default: '0 12px 32px rgba(0,0,0,0.18)' },\n { key: 'embed.productCard.background', cssVar: '--spx-embed-product-card-background', group: 'embed', type: 'color', default: '#ffffff' },\n { key: 'embed.productCard.border', cssVar: '--spx-embed-product-card-border', group: 'embed', type: 'color', default: 'rgba(24,24,27,0.12)' },\n { key: 'embed.productCard.imageRadius', cssVar: '--spx-embed-product-card-image-radius', group: 'embed', type: 'number', default: 8, min: 0, max: 24, step: 1, unit: 'px' },\n { key: 'embed.productCard.padding', cssVar: '--spx-embed-product-card-padding', group: 'embed', type: 'number', default: 16, min: 8, max: 32, step: 1, unit: 'px' },\n { key: 'embed.cart.background', cssVar: '--spx-embed-cart-background', group: 'embed', type: 'color', default: '#ffffff' },\n { key: 'embed.cart.rowBorder', cssVar: '--spx-embed-cart-row-border', group: 'embed', type: 'color', default: 'rgba(24,24,27,0.1)' },\n { key: 'embed.cart.itemSpacing', cssVar: '--spx-embed-cart-item-spacing', group: 'embed', type: 'number', default: 12, min: 4, max: 28, step: 1, unit: 'px' },\n { key: 'embed.modal.background', cssVar: '--spx-embed-modal-background', group: 'embed', type: 'color', default: '#ffffff' },\n { key: 'embed.modal.radius', cssVar: '--spx-embed-modal-radius', group: 'embed', type: 'number', default: 16, min: 0, max: 32, step: 1, unit: 'px' },\n { key: 'embed.modal.maxWidth', cssVar: '--spx-embed-modal-max-width', group: 'embed', type: 'number', default: 560, min: 360, max: 960, step: 20, unit: 'px' },\n { key: 'embed.modal.shadow', cssVar: '--spx-embed-modal-shadow', group: 'embed', type: 'shadow', default: '0 20px 60px rgba(0,0,0,0.2)' },\n { key: 'embed.backdrop.color', cssVar: '--spx-embed-backdrop-color', group: 'embed', type: 'color', default: 'rgba(0,0,0,0.6)' },\n { key: 'embed.backdrop.blur', cssVar: '--spx-embed-backdrop-blur', group: 'embed', type: 'number', default: 4, min: 0, max: 24, step: 1, unit: 'px' },\n { key: 'embed.backdrop.opacity', cssVar: '--spx-embed-backdrop-opacity', group: 'embed', type: 'number', default: 1, min: 0, max: 1, step: 0.05 },\n { key: 'embed.skeleton.background', cssVar: '--spx-embed-skeleton-background', group: 'embed', type: 'color', default: '#f4f4f5' },\n { key: 'embed.skeleton.shimmer', cssVar: '--spx-embed-skeleton-shimmer', group: 'embed', type: 'color', default: '#e8e8ec' },\n { key: 'embed.spinner.color', cssVar: '--spx-embed-spinner-color', group: 'embed', type: 'color', default: '#7c5cff' },\n {\n key: 'embed.closeButton.style',\n cssVar: '--spx-embed-close-button-style',\n group: 'embed',\n type: 'select',\n default: 'ghost',\n allowedValues: embedCloseButtonStyleValues,\n },\n {\n key: 'embed.mobile.layout',\n cssVar: '--spx-embed-mobile-layout',\n group: 'embed',\n type: 'select',\n default: 'sheet',\n allowedValues: embedMobileLayoutValues,\n },\n {\n key: 'embed.content.productDescription',\n cssVar: '--spx-embed-product-description-visibility',\n group: 'embed',\n type: 'select',\n default: 'visible',\n allowedValues: embedContentVisibilityValues,\n },\n {\n key: 'embed.content.termsShortcut',\n cssVar: '--spx-embed-terms-shortcut-visibility',\n group: 'embed',\n type: 'select',\n default: 'visible',\n allowedValues: embedContentVisibilityValues,\n },\n] as const satisfies readonly CheckoutStyleCssTokenDefinition[];\n\nexport type EmbedStyleTokenKey = typeof embedStyleTokenDefinitions[number]['key'];\nexport type EmbedStyleCssVariable = typeof embedStyleTokenDefinitions[number]['cssVar'];\n\nexport type EmbedStyleCssVariableOptions = {\n mode?: CheckoutStyleMode;\n};\n\nexport const checkoutStyleSlotValues = [\n 'checkout.shell',\n 'checkout.panel',\n 'checkout.header',\n 'brand.logo',\n 'product.card',\n 'product.image',\n 'product.title',\n 'product.description',\n 'product.price',\n 'product.quantity',\n 'product.addon',\n 'paymentLink.hero',\n 'summary.panel',\n 'summary.line',\n 'summary.total',\n 'form.field',\n 'form.label',\n 'form.help',\n 'coupon.input',\n 'input.base',\n 'input.error',\n 'button.primary',\n 'button.secondary',\n 'payment.methods',\n 'payment.method',\n 'payment.method.icon',\n 'payment.method.label',\n 'payment.method.meta',\n 'payment.method.fee',\n 'payment.method.indicator',\n 'payment.provider_widget',\n 'payment.loading',\n 'payment.error',\n 'payment.warning',\n 'legal.terms',\n 'status.success',\n 'status.processing',\n 'embed.launcher',\n 'embed.launcher.icon',\n 'embed.productCard',\n 'embed.productCard.image',\n 'embed.productCard.title',\n 'embed.productCard.price',\n 'embed.cart',\n 'embed.cart.row',\n 'embed.cart.summary',\n 'embed.modal',\n 'embed.modal.header',\n 'embed.modal.close',\n 'embed.skeleton',\n 'embed.loader',\n 'embed.branding',\n] as const;\n\nexport const checkoutStyleProtectedSlotValues = [\n 'product.title',\n 'product.price',\n 'summary.total',\n 'payment.method.label',\n 'payment.provider_widget',\n 'payment.loading',\n 'payment.error',\n 'payment.warning',\n 'legal.terms',\n 'status.success',\n 'status.processing',\n 'embed.modal.close',\n 'embed.branding',\n] as const;\n\nexport const CheckoutStyleSlotSchema = z.enum(checkoutStyleSlotValues);\nexport const CheckoutStyleProtectedSlotSchema = z.enum(checkoutStyleProtectedSlotValues);\n\nexport type CheckoutStyleSlot = z.infer<typeof CheckoutStyleSlotSchema>;\nexport type CheckoutStyleProtectedSlot = z.infer<typeof CheckoutStyleProtectedSlotSchema>;\n\nconst HexColorSchema = z.string().regex(/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/, 'Use a valid hex color');\n// Permissive color schema for composite values (rgba, gradients, color-mix)\n// used by token slots that aren't simple solid color picks. The CSS pipeline\n// is the consumer; we just guard against unbounded length and obviously\n// suspicious payloads (no semicolons, no curly braces, no @-rules).\nconst ExtendedColorSchema = z.string().trim().min(1).max(200).refine(\n (value) => !/[;{}]|@import|expression\\s*\\(/i.test(value),\n 'Use a valid CSS color or gradient',\n);\nconst ShadowSchema = z.string().trim().min(1).max(400).refine(\n (value) => !/[;{}]|@import|expression\\s*\\(/i.test(value),\n 'Use a valid CSS box-shadow value',\n);\n// Curated font list — the families the Style Center dropdown offers. Every\n// value here is served without a third-party request: the nine web families are\n// bundled by `next/font/google` in `apps/checkout/app/layout.tsx`, and \"Arial\" /\n// \"System UI\" come from the OS. A payment page must not hand the buyer's IP to\n// fonts.googleapis.com, so a family added here MUST also be added to\n// `app/layout.tsx` and to both maps in `apps/checkout/lib/checkout-style.tsx`\n// (LOCALLY_LOADED_FONTS + LOCAL_FONT_FAMILY_TOKENS); the checkout font-stack\n// test fails otherwise. Order matters: it drives both the dropdown in the\n// editor and the type-checked union here.\nexport const curatedFontValues = [\n 'Inter',\n 'Geist',\n 'Manrope',\n 'Plus Jakarta Sans',\n 'DM Sans',\n 'Space Grotesk',\n 'Sora',\n 'IBM Plex Sans',\n 'JetBrains Mono',\n 'Arial',\n 'System UI',\n] as const;\nconst CuratedFontSchema = z.enum(curatedFontValues);\n\n// Google Fonts family schema — accepts a single Google-hosted family name\n// like \"Source Serif 4\" or \"Crimson Pro\". Restricted to the character set\n// Google Fonts permits in family names (alphanumerics, spaces, +, -, _,\n// digits) and capped at 60 chars to avoid abuse via giant CSS imports.\nconst GoogleFontFamilySchema = z\n .string()\n .trim()\n .min(1)\n .max(60)\n .regex(/^[A-Za-z0-9 +\\-_]+$/, 'Use a Google Fonts family name');\nconst AssetUrlSchema = z.string().url();\n\nexport function isCheckoutStyleManagedAssetUrl(value: string): boolean {\n try {\n const url = new URL(value);\n return url.protocol === 'https:' && checkoutStyleManagedAssetHostValues.includes(\n url.hostname as typeof checkoutStyleManagedAssetHostValues[number],\n );\n } catch {\n return false;\n }\n}\n\nexport const CheckoutStyleTokensSchema = z.object({\n brand: z.object({\n logoUrl: AssetUrlSchema.optional().nullable(),\n logoDarkUrl: AssetUrlSchema.optional().nullable(),\n logoMaxHeight: z.number().int().min(16).max(80).optional(),\n faviconUrl: AssetUrlSchema.optional().nullable(),\n }).strict().optional(),\n color: z.object({\n brand: HexColorSchema.optional(),\n brandContrast: HexColorSchema.optional(),\n background: HexColorSchema.optional(),\n surface: HexColorSchema.optional(),\n surfaceRaised: HexColorSchema.optional(),\n text: HexColorSchema.optional(),\n textMuted: HexColorSchema.optional(),\n border: HexColorSchema.optional(),\n focus: HexColorSchema.optional(),\n success: HexColorSchema.optional(),\n warning: HexColorSchema.optional(),\n error: HexColorSchema.optional(),\n }).strict().optional(),\n typography: z.object({\n fontFamily: CuratedFontSchema.optional(),\n // Optional Google Fonts override. When set, the storefront injects the\n // fonts.googleapis.com stylesheet and uses this family in addition to\n // (or instead of) the curated fontFamily as the leftmost name in the\n // CSS font stack.\n googleFontFamily: GoogleFontFamilySchema.optional(),\n baseSize: z.number().int().min(12).max(18).optional(),\n }).strict().optional(),\n shape: z.object({\n buttonRadius: z.number().int().min(0).max(24).optional(),\n inputRadius: z.number().int().min(0).max(24).optional(),\n cardRadius: z.number().int().min(0).max(28).optional(),\n }).strict().optional(),\n spacing: z.object({\n density: CheckoutStyleDensitySchema.optional(),\n controlHeight: z.number().int().min(36).max(56).optional(),\n }).strict().optional(),\n component: z.object({\n primaryButton: z.object({\n background: HexColorSchema.optional(),\n text: HexColorSchema.optional(),\n }).strict().optional(),\n input: z.object({\n background: HexColorSchema.optional(),\n border: HexColorSchema.optional(),\n focusRing: ExtendedColorSchema.optional(),\n }).strict().optional(),\n summary: z.object({\n background: HexColorSchema.optional(),\n }).strict().optional(),\n paymentMethod: z.object({\n background: ExtendedColorSchema.optional(),\n cardBackground: ExtendedColorSchema.optional(),\n border: ExtendedColorSchema.optional(),\n selectedBackground: ExtendedColorSchema.optional(),\n }).strict().optional(),\n productCard: z.object({\n background: ExtendedColorSchema.optional(),\n border: ExtendedColorSchema.optional(),\n shadow: ShadowSchema.optional(),\n }).strict().optional(),\n productImage: z.object({\n background: ExtendedColorSchema.optional(),\n border: ExtendedColorSchema.optional(),\n icon: ExtendedColorSchema.optional(),\n }).strict().optional(),\n brandAvatar: z.object({\n background: ExtendedColorSchema.optional(),\n text: HexColorSchema.optional(),\n border: ExtendedColorSchema.optional(),\n }).strict().optional(),\n pill: z.object({\n background: ExtendedColorSchema.optional(),\n border: ExtendedColorSchema.optional(),\n text: HexColorSchema.optional(),\n }).strict().optional(),\n errorBanner: z.object({\n background: ExtendedColorSchema.optional(),\n border: ExtendedColorSchema.optional(),\n text: HexColorSchema.optional(),\n }).strict().optional(),\n warningBanner: z.object({\n background: ExtendedColorSchema.optional(),\n border: ExtendedColorSchema.optional(),\n text: HexColorSchema.optional(),\n }).strict().optional(),\n radio: z.object({\n idleRing: ExtendedColorSchema.optional(),\n checkedFill: HexColorSchema.optional(),\n checkedIcon: HexColorSchema.optional(),\n }).strict().optional(),\n divider: z.object({\n color: ExtendedColorSchema.optional(),\n }).strict().optional(),\n }).strict().optional(),\n paymentLink: z.object({\n heroImageUrl: AssetUrlSchema.optional().nullable(),\n heroPosition: CheckoutStylePaymentLinkHeroPositionSchema.optional(),\n }).strict().optional(),\n embed: z.object({\n launcher: z.object({\n background: ExtendedColorSchema.optional(),\n text: HexColorSchema.optional(),\n radius: z.number().int().min(0).max(28).optional(),\n paddingX: z.number().int().min(8).max(32).optional(),\n paddingY: z.number().int().min(6).max(24).optional(),\n shadow: ShadowSchema.optional(),\n }).strict().optional(),\n productCard: z.object({\n background: ExtendedColorSchema.optional(),\n border: ExtendedColorSchema.optional(),\n imageRadius: z.number().int().min(0).max(24).optional(),\n padding: z.number().int().min(8).max(32).optional(),\n }).strict().optional(),\n cart: z.object({\n background: ExtendedColorSchema.optional(),\n rowBorder: ExtendedColorSchema.optional(),\n itemSpacing: z.number().int().min(4).max(28).optional(),\n }).strict().optional(),\n modal: z.object({\n background: ExtendedColorSchema.optional(),\n radius: z.number().int().min(0).max(32).optional(),\n maxWidth: z.number().int().min(360).max(960).optional(),\n shadow: ShadowSchema.optional(),\n }).strict().optional(),\n backdrop: z.object({\n color: ExtendedColorSchema.optional(),\n blur: z.number().int().min(0).max(24).optional(),\n opacity: z.number().min(0).max(1).optional(),\n }).strict().optional(),\n skeleton: z.object({\n background: ExtendedColorSchema.optional(),\n shimmer: ExtendedColorSchema.optional(),\n }).strict().optional(),\n spinner: z.object({\n color: ExtendedColorSchema.optional(),\n }).strict().optional(),\n closeButton: z.object({\n style: EmbedCloseButtonStyleSchema.optional(),\n }).strict().optional(),\n mobile: z.object({\n layout: EmbedMobileLayoutSchema.optional(),\n }).strict().optional(),\n content: z.object({\n productDescription: EmbedContentVisibilitySchema.optional(),\n termsShortcut: EmbedContentVisibilitySchema.optional(),\n }).strict().optional(),\n }).strict().optional(),\n}).strict();\n\nexport type CheckoutStyleTokens = z.infer<typeof CheckoutStyleTokensSchema>;\n\nexport const CheckoutStyleSettingsSchema = z.object({\n mode: CheckoutStyleModeSchema.default('system'),\n fontSource: z.enum(['curated']).default('curated'),\n}).strict();\n\nexport type CheckoutStyleSettings = z.infer<typeof CheckoutStyleSettingsSchema>;\n\nexport const StyleThemeShareModeSchema = z.enum(['standalone', 'bundle', 'pointer']);\nexport type StyleThemeShareMode = z.infer<typeof StyleThemeShareModeSchema>;\n\nexport const StyleThemeParentHintSchema = z.object({\n name: z.string().trim().min(1).max(80),\n fingerprint: z.string().trim().min(1).max(128),\n}).strict();\n\n/**\n * Historic-data tolerance. Theme export codes are copy-pasted strings that live\n * outside this system — in merchant notes, Discord messages, and the\n * `style_theme_shares` table — so codes minted before the embed surface\n * collapsed to a single design still carry a top-level `embed_design` key (and\n * one inside `bundled_parent`). The export schemas are `.strict()`, so without\n * this strip every one of those codes would fail to import.\n *\n * Accept and ignore: the key is dropped before validation and never re-emitted.\n * Remove this once codes minted before the single-design release are no longer\n * expected to import (they carry no other retired field, so the strip can go\n * away wholesale).\n *\n * OBSERVABILITY LIVES ELSEWHERE, ON PURPOSE. This module is isomorphic — the\n * dashboard's import dialog parses the same code in the browser before the\n * backend ever sees it — so there is no logger to reach for here, and adding\n * one would put a server sink in a bundle that ships to merchants. The signal\n * that says whether the retirement has completed is the backend's\n * `retired_embed_design_key` warn line in\n * `apps/backend/src/services/style-center/embed-runtime.ts`, which watches the\n * same key on the transports and Redis sessions minted by the same release.\n * Those age out no earlier than a copy-pasted export code does, so a quiet\n * runtime is the precondition for dropping THIS strip too — never the proof on\n * its own. The removal plan for all three is one list:\n * `docs/architecture/domains/style-center.md` — Release 2.\n */\nconst RETIRED_EXPORT_FIELDS = ['embed_design'] as const;\n\nfunction stripRetiredExportFields(value: unknown): unknown {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n return value;\n }\n\n const record = value as Record<string, unknown>;\n if (!RETIRED_EXPORT_FIELDS.some((field) => field in record)) {\n return value;\n }\n\n const cleaned = { ...record };\n for (const field of RETIRED_EXPORT_FIELDS) {\n delete cleaned[field];\n }\n return cleaned;\n}\n\nexport const CheckoutStyleBundledParentThemeExportSchema = z.preprocess(\n stripRetiredExportFields,\n z.object({\n type: z.literal('shoppex.style_theme'),\n surface: z.literal('checkout'),\n format_version: z.union([\n z.literal(1),\n z.literal(SHOPPEX_STYLE_THEME_EXPORT_FORMAT_VERSION),\n ]),\n name: z.string().trim().min(1).max(80),\n description: z.string().trim().max(240).optional(),\n token_schema_version: z.literal(CHECKOUT_STYLE_TOKEN_SCHEMA_VERSION),\n tokens: CheckoutStyleTokensSchema.default({}),\n custom_css: z.string().max(20_000).default(''),\n settings: CheckoutStyleSettingsSchema.default({ mode: 'system', fontSource: 'curated' }),\n _meta: z.record(z.string(), z.unknown()).optional(),\n }).strict(),\n);\n\nexport const CheckoutStyleThemeExportSchema = z.preprocess(\n stripRetiredExportFields,\n z.object({\n type: z.literal('shoppex.style_theme'),\n surface: CheckoutStyleSurfaceSchema,\n format_version: z.union([\n z.literal(1),\n z.literal(SHOPPEX_STYLE_THEME_EXPORT_FORMAT_VERSION),\n ]),\n name: z.string().trim().min(1).max(80),\n description: z.string().trim().max(240).optional(),\n token_schema_version: z.literal(CHECKOUT_STYLE_TOKEN_SCHEMA_VERSION),\n tokens: CheckoutStyleTokensSchema.default({}),\n custom_css: z.string().max(20_000).default(''),\n settings: CheckoutStyleSettingsSchema.default({ mode: 'system', fontSource: 'curated' }),\n share_mode: StyleThemeShareModeSchema.default('standalone'),\n parent_hint: StyleThemeParentHintSchema.optional(),\n bundled_parent: CheckoutStyleBundledParentThemeExportSchema.optional(),\n _meta: z.record(z.string(), z.unknown()).optional(),\n }).strict(),\n);\n\nexport type CheckoutStyleThemeExport = z.infer<typeof CheckoutStyleThemeExportSchema>;\n\nexport const ResolvedCheckoutStyleSchema = z.object({\n theme_id: z.string().uuid().nullable(),\n surface: CheckoutStyleSurfaceSchema,\n token_schema_version: z.literal(CHECKOUT_STYLE_TOKEN_SCHEMA_VERSION),\n revision: z.number().int().min(1),\n tokens: CheckoutStyleTokensSchema,\n custom_css: z.string(),\n css_variables: z.record(z.string(), z.string()),\n}).strict();\n\nexport type ResolvedCheckoutStyle = z.infer<typeof ResolvedCheckoutStyleSchema>;\n\nexport const ResolvedEmbedStyleSchema = z.object({\n theme_id: z.string().uuid().nullable(),\n parent_theme_id: z.string().uuid().nullable(),\n surface: z.literal('embed'),\n token_schema_version: z.literal(CHECKOUT_STYLE_TOKEN_SCHEMA_VERSION),\n revision: z.number().int().min(1),\n parent_revision: z.number().int().min(1).nullable(),\n tokens: CheckoutStyleTokensSchema,\n custom_css: z.string(),\n css_variables: z.record(z.string(), z.string()),\n}).strict();\n\nexport type ResolvedEmbedStyle = z.infer<typeof ResolvedEmbedStyleSchema>;\n\n/** Canonical embed runtime contract shared by SDK shell and checkout iframe. */\nexport const EmbedRuntimeStyleSchema = ResolvedEmbedStyleSchema;\nexport type EmbedRuntimeStyle = ResolvedEmbedStyle;\n\nexport const EmbedRuntimeSessionContextSchema = z.object({\n shop_id: z.string().uuid(),\n product_id: z.string().uuid().nullable(),\n product_group_id: z.string().uuid().nullable(),\n payment_link_id: z.string().uuid().nullable(),\n invoice_id: z.string().nullable(),\n}).strict();\n\nexport type EmbedRuntimeSessionContext = z.infer<typeof EmbedRuntimeSessionContextSchema>;\n\nexport const EmbedRuntimeThemeResponseSchema = z.object({\n embed_runtime: z.string().min(16).max(128),\n revision: z.number().int().min(1),\n parent_revision: z.number().int().min(1).nullable(),\n theme_id: z.string().uuid().nullable(),\n css_variables: z.record(z.string(), z.string()),\n custom_css: z.string(),\n}).strict();\n\nexport type EmbedRuntimeThemeResponse = z.infer<typeof EmbedRuntimeThemeResponseSchema>;\n\nexport const EmbedRuntimeTransportSchema = z.object({\n embed_style_revision: z.coerce.number().int().min(1).optional(),\n embed_runtime: z.string().min(16).max(128).optional(),\n preview: z.boolean().optional(),\n}).strict();\n\nexport type EmbedRuntimeTransport = z.infer<typeof EmbedRuntimeTransportSchema>;\n\nfunction readPath(input: unknown, path: string): unknown {\n return path.split('.').reduce<unknown>((current, segment) => {\n if (!current || typeof current !== 'object' || Array.isArray(current)) return undefined;\n return (current as Record<string, unknown>)[segment];\n }, input);\n}\n\nfunction formatCssValue(definition: CheckoutStyleTokenDefinition, value: string | number): string {\n if (definition.type === 'number' && definition.unit) {\n return `${value}${definition.unit}`;\n }\n\n // Multi-word font family names must be quoted so they survive var()\n // substitution into a font-family list. Single-word names like \"Inter\"\n // or generic keywords are left bare so they keep their generic-family\n // semantics.\n if (definition.type === 'font' && typeof value === 'string') {\n const trimmed = value.trim();\n if (trimmed.length === 0) return '';\n if (/\\s/.test(trimmed) && !/^['\"]/.test(trimmed)) {\n return `\"${trimmed.replace(/\"/g, '\\\\\"')}\"`;\n }\n return trimmed;\n }\n\n return String(value);\n}\n\nexport function resolveCheckoutStyleTokenValue(\n tokens: CheckoutStyleTokens,\n key: CheckoutStyleTokenKey,\n options: { parentTokens?: CheckoutStyleTokens } = {},\n): string | number | undefined {\n const own = readPath(tokens, key);\n if (isExplicitCheckoutStyleTokenValue(own)) {\n return own as string | number;\n }\n\n const parent = options.parentTokens ? readPath(options.parentTokens, key) : undefined;\n if (isExplicitCheckoutStyleTokenValue(parent)) {\n return parent as string | number;\n }\n\n const brandDerivedKey = resolveCheckoutStyleBrandDerivedTokenKey(key);\n if (brandDerivedKey) {\n const brand = resolveCheckoutStyleTokenValue(tokens, brandDerivedKey as CheckoutStyleTokenKey, options);\n if (isExplicitCheckoutStyleTokenValue(brand)) {\n return brand;\n }\n }\n\n const definition = checkoutStyleTokenDefinitions.find((entry) => entry.key === key);\n if (definition && isExplicitCheckoutStyleTokenValue(definition.default)) {\n return definition.default;\n }\n\n const baseline = CHECKOUT_PLATFORM_BASELINE[key];\n return baseline !== undefined ? baseline : undefined;\n}\n\nexport function createCheckoutStyleCssVariables(tokens: CheckoutStyleTokens): Record<CheckoutStyleCssVariable, string> {\n const variables = {} as Record<CheckoutStyleCssVariable, string>;\n\n for (const definition of checkoutStyleTokenDefinitions) {\n const value = readPath(tokens, definition.key);\n if (!isExplicitCheckoutStyleTokenValue(value)) {\n continue;\n }\n variables[definition.cssVar] = formatCssValue(definition, value);\n }\n\n return variables;\n}\n\n/**\n * Token groups whose defaults are safe to materialise into the live checkout\n * root. These are the \"foundation\" tokens (brand, base colors, shape, spacing)\n * that sit at the INNER end of the system-CSS `var()` fallback chains —\n * e.g. `var(--spx-checkout-product-card-border, var(--spx-checkout-border, …))`.\n * Materialising them kills the white-`currentColor` fallback bug without\n * touching the cascade.\n *\n * The `component` group is deliberately excluded: those tokens are the OUTER\n * end of the chains, so emitting their defaults (e.g. `--spx-checkout-product-card-bg`)\n * would shadow base-token edits — a merchant who only customises `color.surfaceRaised`\n * would no longer see it cascade into product cards. Their defaults stay inline\n * in the system CSS as the final hex fallback instead.\n *\n * The `typography` group is also excluded: `typography.fontFamily` resolves to a\n * bare family name (\"Geist\") that no `@font-face` declares — the checkout loads\n * Geist via `next/font` as `--font-geist-sans`. Materialising `--spx-checkout-font`\n * as \"Geist\" would make the font-family rule bypass the Next webfont and fall\n * back to system sans. The system CSS keeps CHECKOUT_PLATFORM_FONT_STACK (which\n * references `--font-geist-sans`) as its inline default instead.\n */\nconst CHECKOUT_BASELINE_TOKEN_GROUPS = new Set(['brand', 'color', 'shape', 'spacing']);\n\n/**\n * Like {@link createCheckoutStyleCssVariables}, but materialises each foundation\n * token's SSOT default when the merchant hasn't set an explicit value. The live\n * hosted checkout renders this so the base `--spx-checkout-*` variables are\n * always present in the DOM, which means the system CSS never falls back to\n * `currentColor` (that fallback resolved to the white text colour → white\n * borders/buttons for any merchant who never opened the Style Center).\n *\n * Rules:\n * - Explicit merchant values are always emitted (any group, including component\n * overrides), so partial Style Center themes keep working.\n * - Unset tokens only get their default emitted when they belong to a foundation\n * group (see {@link CHECKOUT_BASELINE_TOKEN_GROUPS}); component defaults are\n * left to the inline system-CSS fallbacks so base-token edits cascade.\n * - Empty defaults (`''`) are skipped so the value stays unset — most importantly\n * `color.background` (`--spx-checkout-bg`), which must remain absent so the\n * two hosted columns keep their own rungs of the ladder (`--surface-0` for the\n * working panel, `--surface-1` for the summary ground). A materialised\n * background paints BOTH and the column split disappears. This resolves only\n * to `definition.default`, NOT through `resolveCheckoutStyleTokenValue`,\n * because that resolver would fall through to the opaque\n * `CHECKOUT_PLATFORM_BASELINE` background.\n */\n/**\n * Light-appearance defaults for the baseline foundation tokens. Keys not listed\n * here keep their (appearance-neutral) definition default. `color.background`\n * stays absent in both appearances so the column split and the summary column's\n * own ground survive.\n *\n * Same rule as the dark defaults above: every value is the LIGHT rung of the\n * ladder in `apps/checkout/app/globals.css` — `--surface-0`, `--card`,\n * `--foreground`, `--muted-foreground`, `--border` — so that a shop with no\n * theme renders exactly what the components paint.\n */\nexport const CHECKOUT_PLATFORM_BASELINE_LIGHT_DEFAULTS: Partial<Record<string, string>> = {\n // `--surface-0`: the working panel, PURE WHITE. It is the form half of the\n // page, and a form's structure comes from the edge of each field and tile,\n // not from the tone of the sheet they sit on. Two tinted panels shipped here\n // before this one (#f7f7f7, then a #f0f0f0 \"well\") and both made the middle\n // of the page read as a tonal step rather than as a join.\n 'color.surface': '#ffffff',\n // `--surface-2`: a card resting on that panel — the SAME white, on purpose.\n // Light separates a card from its panel by `--card-hairline` (#e8e8e8) and a\n // whisper of `--card-shadow`, never by a step of fill. That these two are\n // equal is the model, not a missing value: the summary column (#fafafa) is\n // the only tonal step the light theme spends anywhere.\n 'color.surfaceRaised': '#ffffff',\n 'color.text': '#101010',\n 'color.textMuted': '#636363',\n // `--border`. It is the pair that matters, not either value: a shop on the\n // platform baseline has to get the same relation between a field edge and a\n // card edge that the checkout paints for everyone else. Both halves moved up\n // together to Stripe Checkout's measured pair (card edge #e8e8e8, input ring\n // #e0e0e0) when the working panel's white-on-white cards turned out to have\n // nothing but this line holding them off the sheet.\n 'color.border': '#e0e0e0',\n 'color.success': '#16a34a',\n 'color.warning': '#ca8a04',\n 'color.error': '#dc2626',\n};\n\nexport type CheckoutStyleAppearance = 'dark' | 'light';\n\nexport function createCheckoutStyleBaselineCssVariables(\n tokens: CheckoutStyleTokens,\n appearance: CheckoutStyleAppearance = 'dark',\n): Record<CheckoutStyleCssVariable, string> {\n const variables = {} as Record<CheckoutStyleCssVariable, string>;\n\n for (const definition of checkoutStyleTokenDefinitions) {\n const own = readPath(tokens, definition.key);\n if (isExplicitCheckoutStyleTokenValue(own)) {\n variables[definition.cssVar] = formatCssValue(definition, own);\n continue;\n }\n if (!CHECKOUT_BASELINE_TOKEN_GROUPS.has(definition.group)) {\n continue;\n }\n const baselineDefault = appearance === 'light'\n ? CHECKOUT_PLATFORM_BASELINE_LIGHT_DEFAULTS[definition.key] ?? definition.default\n : definition.default;\n if (!isExplicitCheckoutStyleTokenValue(baselineDefault)) {\n continue;\n }\n variables[definition.cssVar] = formatCssValue(definition, baselineDefault);\n }\n\n return variables;\n}\n\n/**\n * Dark-appearance defaults for the embed chrome tokens. The `definition.default`\n * of every embed token is the LIGHT value, so only the keys that actually differ\n * in dark are listed here. Emitted only when the theme's mode is explicitly\n * 'dark' — never inferred from anything else.\n */\nconst EMBED_STYLE_DARK_DEFAULTS: Partial<Record<EmbedStyleTokenKey, string>> = {\n 'embed.productCard.background': '#09090b',\n 'embed.productCard.border': 'rgba(255,255,255,0.08)',\n 'embed.cart.background': '#09090b',\n 'embed.cart.rowBorder': '#27272a',\n 'embed.modal.background': '#0a0a0c',\n 'embed.modal.shadow': '0 20px 60px rgba(0,0,0,0.45)',\n 'embed.skeleton.background': '#1a1a1e',\n 'embed.skeleton.shimmer': '#2a2a2f',\n};\n\n/**\n * Emits the `--spx-embed-*` variables for a resolved embed style.\n *\n * Rules:\n * - An explicit merchant token always wins and is always emitted.\n * - An unset token gets a baked default ONLY when the theme picked an\n * appearance explicitly (`settings.mode` of 'dark' or 'light').\n * - Mode 'system' (and an unset mode) bakes nothing. The embed SDK stylesheet\n * reads every one of these through `var(--spx-embed-*, <fallback>)` and pairs\n * that with its own `prefers-color-scheme` handling (see\n * `shouldUseDarkShell` in apps/checkout/src/embed/modal.ts, which reads\n * `--spx-checkout-color-mode` first and falls back to the media query).\n * Baking an appearance here would pin a merchant who asked for \"follow the\n * visitor's system setting\" to one of the two.\n */\nexport function createEmbedStyleCssVariables(\n tokens: CheckoutStyleTokens,\n options: EmbedStyleCssVariableOptions = {},\n): Record<EmbedStyleCssVariable, string> {\n const variables = {} as Record<EmbedStyleCssVariable, string>;\n const bakeDefaults = options.mode === 'dark' || options.mode === 'light';\n\n for (const definition of embedStyleTokenDefinitions) {\n const value = readPath(tokens, definition.key);\n\n if (typeof value === 'string' || typeof value === 'number') {\n if (typeof value === 'string' && value.length === 0) {\n continue;\n }\n variables[definition.cssVar] = formatCssValue(definition, value);\n continue;\n }\n\n if (!bakeDefaults) {\n continue;\n }\n\n const resolvedDefault = options.mode === 'dark'\n ? EMBED_STYLE_DARK_DEFAULTS[definition.key] ?? definition.default\n : definition.default;\n if (typeof resolvedDefault === 'string' && resolvedDefault.length === 0) {\n continue;\n }\n variables[definition.cssVar] = formatCssValue(definition, resolvedDefault);\n }\n\n return variables;\n}\n","import * as z from 'zod/v4';\n\nexport const storefrontAddonTypeValues = [\n 'announcement_bar',\n 'countdown_bar',\n 'promo_info_card',\n 'recent_purchase_popup',\n 'coupon_popup_modal',\n 'live_chat',\n] as const;\n\nexport const storefrontAddonSlotValues = [\n 'layout.header.before',\n 'layout.header.after',\n 'layout.overlay',\n 'home.hero.after',\n 'home.grid.before',\n 'product.buybox.after',\n 'layout.footer.before',\n 'floating.bottom_right',\n] as const;\n\nexport const storefrontAddonComponentValues = [\n 'announcement_bar',\n 'countdown_bar',\n 'promo_info_card',\n 'recent_purchase_popup',\n 'coupon_popup_modal',\n 'live_chat',\n] as const;\n\nexport const StorefrontAddonTypeSchema = z.enum(storefrontAddonTypeValues);\nexport const StorefrontAddonSlotSchema = z.enum(storefrontAddonSlotValues);\nexport const StorefrontAddonComponentSchema = z.enum(storefrontAddonComponentValues);\n\nexport type StorefrontAddonType = z.infer<typeof StorefrontAddonTypeSchema>;\nexport type StorefrontAddonSlot = z.infer<typeof StorefrontAddonSlotSchema>;\nexport type StorefrontAddonComponent = z.infer<typeof StorefrontAddonComponentSchema>;\n\nconst HexColorSchema = z.string().regex(/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/, 'Use a valid hex color');\n\nexport const announcementBarDisplayModeValues = [\n 'static',\n 'marquee',\n] as const;\n\nexport const announcementBarThemePresetValues = [\n 'brand_blue',\n 'emerald',\n 'sunset',\n 'rose',\n 'charcoal',\n 'custom',\n] as const;\n\nexport const DEFAULT_ANNOUNCEMENT_BAR_ANIMATION_SPEED_SECONDS = 30;\n\nexport const AnnouncementBarDisplayModeSchema = z.enum(announcementBarDisplayModeValues);\nexport const AnnouncementBarThemePresetSchema = z.enum(announcementBarThemePresetValues);\n\nexport const countdownBarExpiryBehaviorValues = [\n 'hide',\n 'message',\n] as const;\n\nexport const countdownBarDensityValues = [\n 'compact',\n 'comfortable',\n] as const;\n\nexport const countdownBarCtaStyleValues = [\n 'subtle',\n 'outline',\n 'solid',\n] as const;\n\nexport const countdownBarTimerStyleValues = [\n 'minimal',\n 'boxed',\n] as const;\n\nexport const promoInfoCardThemePresetValues = [\n 'indigo',\n 'emerald',\n 'amber',\n 'rose',\n 'slate',\n 'custom',\n] as const;\n\nexport const promoInfoCardLayoutStyleValues = [\n 'compact',\n 'feature',\n 'alert',\n] as const;\n\nexport const promoInfoCardDensityValues = [\n 'compact',\n 'comfortable',\n] as const;\n\nexport const promoInfoCardCtaStyleValues = [\n 'subtle',\n 'outline',\n 'solid',\n] as const;\n\nexport const promoInfoCardIconVisibilityValues = [\n 'show',\n 'hide',\n] as const;\n\nexport const promoInfoCardIconValues = [\n 'sparkles',\n 'megaphone',\n 'gift',\n 'truck',\n 'shield',\n 'support',\n 'none',\n] as const;\n\nexport const CountdownBarExpiryBehaviorSchema = z.enum(countdownBarExpiryBehaviorValues);\nexport const CountdownBarDensitySchema = z.enum(countdownBarDensityValues);\nexport const CountdownBarCtaStyleSchema = z.enum(countdownBarCtaStyleValues);\nexport const CountdownBarTimerStyleSchema = z.enum(countdownBarTimerStyleValues);\nexport const PromoInfoCardThemePresetSchema = z.enum(promoInfoCardThemePresetValues);\nexport const PromoInfoCardLayoutStyleSchema = z.enum(promoInfoCardLayoutStyleValues);\nexport const PromoInfoCardDensitySchema = z.enum(promoInfoCardDensityValues);\nexport const PromoInfoCardCtaStyleSchema = z.enum(promoInfoCardCtaStyleValues);\nexport const PromoInfoCardIconSchema = z.enum(promoInfoCardIconValues);\nexport const PromoInfoCardIconVisibilitySchema = z.enum(promoInfoCardIconVisibilityValues);\n\nexport const couponPopupModalThemePresetValues = [\n 'midnight',\n 'ocean',\n 'ember',\n 'forest',\n 'custom',\n] as const;\n\nexport const couponPopupModalTriggerValues = [\n 'delay',\n 'exit_intent',\n] as const;\n\nexport const CouponPopupModalThemePresetSchema = z.enum(couponPopupModalThemePresetValues);\nexport const CouponPopupModalTriggerSchema = z.enum(couponPopupModalTriggerValues);\n\nconst RelativeOrAbsoluteUrlSchema = z.string().trim().refine((value) => {\n if (value.startsWith('/')) {\n return true;\n }\n\n try {\n const parsed = new URL(value);\n return parsed.protocol === 'http:' || parsed.protocol === 'https:';\n } catch {\n return false;\n }\n}, 'Use a valid absolute URL or a path starting with \"/\"');\n\nconst DatetimeStringSchema = z.string().trim().refine((value) => {\n const parsed = new Date(value);\n return !Number.isNaN(parsed.getTime());\n}, 'Use a valid date and time');\n\nexport const AnnouncementBarConfigSchema = z.object({\n text: z.string().trim().min(1, 'Text is required').max(160, 'Text must be 160 characters or fewer'),\n linkLabel: z.string().trim().max(32, 'Link label must be 32 characters or fewer').optional().nullable(),\n linkUrl: RelativeOrAbsoluteUrlSchema.optional().nullable(),\n dismissible: z.boolean().default(false),\n displayMode: AnnouncementBarDisplayModeSchema.default('marquee'),\n themePreset: AnnouncementBarThemePresetSchema.default('custom'),\n animationSpeedSeconds: z.number().int().min(8).max(40).default(DEFAULT_ANNOUNCEMENT_BAR_ANIMATION_SPEED_SECONDS),\n backgroundColor: HexColorSchema.default('#111827'),\n textColor: HexColorSchema.default('#f9fafb'),\n});\n\nexport const CountdownBarConfigSchema = z.object({\n text: z.string().trim().min(1, 'Text is required').max(120, 'Text must be 120 characters or fewer'),\n endAt: DatetimeStringSchema,\n linkLabel: z.string().trim().max(32, 'Link label must be 32 characters or fewer').optional().nullable(),\n linkUrl: RelativeOrAbsoluteUrlSchema.optional().nullable(),\n dismissible: z.boolean().default(false),\n themePreset: AnnouncementBarThemePresetSchema.default('brand_blue'),\n expiredBehavior: CountdownBarExpiryBehaviorSchema.default('hide'),\n expiredMessage: z.string().trim().max(120, 'Expired message must be 120 characters or fewer').optional().nullable(),\n density: CountdownBarDensitySchema.default('compact'),\n ctaStyle: CountdownBarCtaStyleSchema.default('subtle'),\n timerStyle: CountdownBarTimerStyleSchema.default('boxed'),\n backgroundColor: HexColorSchema.default('#111827'),\n textColor: HexColorSchema.default('#f9fafb'),\n});\n\nexport const PromoInfoCardConfigSchema = z.object({\n eyebrow: z.string().trim().max(32, 'Eyebrow must be 32 characters or fewer').optional().nullable(),\n title: z.string().trim().min(1, 'Title is required').max(80, 'Title must be 80 characters or fewer'),\n body: z.string().trim().min(1, 'Body is required').max(240, 'Body must be 240 characters or fewer'),\n linkLabel: z.string().trim().max(32, 'Link label must be 32 characters or fewer').optional().nullable(),\n linkUrl: RelativeOrAbsoluteUrlSchema.optional().nullable(),\n themePreset: PromoInfoCardThemePresetSchema.default('indigo'),\n layoutStyle: PromoInfoCardLayoutStyleSchema.default('feature'),\n density: PromoInfoCardDensitySchema.default('comfortable'),\n ctaStyle: PromoInfoCardCtaStyleSchema.default('outline'),\n icon: PromoInfoCardIconSchema.default('sparkles'),\n iconVisibility: PromoInfoCardIconVisibilitySchema.default('show'),\n backgroundColor: HexColorSchema.default('#111827'),\n textColor: HexColorSchema.default('#f9fafb'),\n accentColor: HexColorSchema.default('#818cf8'),\n});\n\nexport const RecentPurchasePopupConfigSchema = z.object({\n title: z.string().trim().min(1, 'Title is required').max(80, 'Title must be 80 characters or fewer').default('Recent purchases'),\n lookbackHours: z.number().int().min(1).max(168).default(24),\n cooldownSeconds: z.number().int().min(5).max(300).default(20),\n maxItems: z.number().int().min(1).max(20).default(8),\n anonymizeMode: z.enum([\n 'first_name_city',\n 'first_name_country',\n 'initial_country',\n 'anonymous',\n ]).default('first_name_city'),\n includedProductIds: z.array(z.string().min(1)).max(50).default([]),\n});\n\nexport const CouponPopupModalConfigSchema = z.object({\n eyebrow: z.string().trim().max(32, 'Eyebrow must be 32 characters or fewer').optional().nullable(),\n title: z.string().trim().min(1, 'Title is required').max(80, 'Title must be 80 characters or fewer'),\n body: z.string().trim().min(1, 'Body is required').max(240, 'Body must be 240 characters or fewer'),\n couponCode: z.string().trim().min(2, 'Coupon code is required').max(40, 'Coupon code must be 40 characters or fewer'),\n primaryButtonLabel: z.string().trim().min(1, 'Primary button label is required').max(24, 'Primary button label must be 24 characters or fewer').default('Copy code'),\n secondaryButtonLabel: z.string().trim().min(1, 'Secondary button label is required').max(24, 'Secondary button label must be 24 characters or fewer').default('Maybe later'),\n disclaimer: z.string().trim().max(100, 'Disclaimer must be 100 characters or fewer').optional().nullable(),\n themePreset: CouponPopupModalThemePresetSchema.default('midnight'),\n trigger: CouponPopupModalTriggerSchema.default('delay'),\n delaySeconds: z.number().int().min(0).max(60).default(6),\n showOncePerSession: z.boolean().default(true),\n reminderHours: z.number().int().min(1).max(720).default(24),\n backgroundColor: HexColorSchema.default('#111827'),\n textColor: HexColorSchema.default('#f8fafc'),\n accentColor: HexColorSchema.default('#7c9cff'),\n heroImageUrl: RelativeOrAbsoluteUrlSchema.optional().nullable(),\n discountDisplay: z.string().trim().max(24, 'Discount display must be 24 characters or fewer').optional().nullable(),\n expiresAt: DatetimeStringSchema.optional().nullable(),\n});\n\nexport const liveChatContactFieldsValues = [\n 'hidden',\n 'optional',\n] as const;\n\nexport const LiveChatContactFieldsSchema = z.enum(liveChatContactFieldsValues);\n\nexport const LiveChatConfigSchema = z.object({\n headline: z.string().trim().min(1, 'Headline is required').max(60, 'Headline must be 60 characters or fewer').default('Chat with us'),\n greeting: z.string().trim().min(1, 'Greeting is required').max(240, 'Greeting must be 240 characters or fewer').default('Hi! Send us a message and we will reply as soon as possible.'),\n inputPlaceholder: z.string().trim().min(1, 'Placeholder is required').max(80, 'Placeholder must be 80 characters or fewer').default('Type your message…'),\n contactFields: LiveChatContactFieldsSchema.default('optional'),\n accentColor: HexColorSchema.default('#111827'),\n launcherIconColor: HexColorSchema.default('#f9fafb'),\n});\n\nexport type LiveChatConfig = z.infer<typeof LiveChatConfigSchema>;\n\nexport type AnnouncementBarConfig = z.infer<typeof AnnouncementBarConfigSchema>;\nexport type CountdownBarConfig = z.infer<typeof CountdownBarConfigSchema>;\nexport type PromoInfoCardConfig = z.infer<typeof PromoInfoCardConfigSchema>;\nexport type RecentPurchasePopupConfig = z.infer<typeof RecentPurchasePopupConfigSchema>;\nexport type CouponPopupModalConfig = z.infer<typeof CouponPopupModalConfigSchema>;\n\nexport type StorefrontAddonConfigByType = {\n announcement_bar: AnnouncementBarConfig;\n countdown_bar: CountdownBarConfig;\n promo_info_card: PromoInfoCardConfig;\n recent_purchase_popup: RecentPurchasePopupConfig;\n coupon_popup_modal: CouponPopupModalConfig;\n live_chat: LiveChatConfig;\n};\n\nexport const StorefrontAddonConfigSchemaByType = {\n announcement_bar: AnnouncementBarConfigSchema,\n countdown_bar: CountdownBarConfigSchema,\n promo_info_card: PromoInfoCardConfigSchema,\n recent_purchase_popup: RecentPurchasePopupConfigSchema,\n coupon_popup_modal: CouponPopupModalConfigSchema,\n live_chat: LiveChatConfigSchema,\n} as const satisfies Record<StorefrontAddonType, z.ZodTypeAny>;\n\nconst AnnouncementBarDraftSchema = z.object({\n type: z.literal('announcement_bar'),\n slot: StorefrontAddonSlotSchema,\n enabled: z.boolean().default(true),\n sortOrder: z.number().int().min(0).max(999).default(0),\n config: AnnouncementBarConfigSchema,\n});\n\nconst RecentPurchasePopupDraftSchema = z.object({\n type: z.literal('recent_purchase_popup'),\n slot: StorefrontAddonSlotSchema,\n enabled: z.boolean().default(true),\n sortOrder: z.number().int().min(0).max(999).default(0),\n config: RecentPurchasePopupConfigSchema,\n});\n\nconst CountdownBarDraftSchema = z.object({\n type: z.literal('countdown_bar'),\n slot: StorefrontAddonSlotSchema,\n enabled: z.boolean().default(true),\n sortOrder: z.number().int().min(0).max(999).default(0),\n config: CountdownBarConfigSchema,\n});\n\nconst PromoInfoCardDraftSchema = z.object({\n type: z.literal('promo_info_card'),\n slot: StorefrontAddonSlotSchema,\n enabled: z.boolean().default(true),\n sortOrder: z.number().int().min(0).max(999).default(0),\n config: PromoInfoCardConfigSchema,\n});\n\nconst CouponPopupModalDraftSchema = z.object({\n type: z.literal('coupon_popup_modal'),\n slot: StorefrontAddonSlotSchema,\n enabled: z.boolean().default(true),\n sortOrder: z.number().int().min(0).max(999).default(0),\n config: CouponPopupModalConfigSchema,\n});\n\nconst LiveChatDraftSchema = z.object({\n type: z.literal('live_chat'),\n slot: StorefrontAddonSlotSchema,\n enabled: z.boolean().default(true),\n sortOrder: z.number().int().min(0).max(999).default(0),\n config: LiveChatConfigSchema,\n});\n\nexport const StorefrontAddonCreateSchema = z.discriminatedUnion('type', [\n AnnouncementBarDraftSchema,\n CountdownBarDraftSchema,\n PromoInfoCardDraftSchema,\n RecentPurchasePopupDraftSchema,\n CouponPopupModalDraftSchema,\n LiveChatDraftSchema,\n]);\n\nexport const StorefrontAddonUpdateSchema = z.discriminatedUnion('type', [\n AnnouncementBarDraftSchema.extend({\n id: z.string().min(1),\n }),\n CountdownBarDraftSchema.extend({\n id: z.string().min(1),\n }),\n PromoInfoCardDraftSchema.extend({\n id: z.string().min(1),\n }),\n RecentPurchasePopupDraftSchema.extend({\n id: z.string().min(1),\n }),\n CouponPopupModalDraftSchema.extend({\n id: z.string().min(1),\n }),\n LiveChatDraftSchema.extend({\n id: z.string().min(1),\n }),\n]);\n\nexport type StorefrontAddonCreateInput = z.infer<typeof StorefrontAddonCreateSchema>;\nexport type StorefrontAddonUpdateInput = z.infer<typeof StorefrontAddonUpdateSchema>;\n\nexport interface StorefrontAddonInstanceBase {\n id: string;\n shopId: string;\n type: StorefrontAddonType;\n slot: StorefrontAddonSlot;\n enabled: boolean;\n sortOrder: number;\n createdAt: string;\n updatedAt: string;\n}\n\nexport type StorefrontAddonInstance =\n | (StorefrontAddonInstanceBase & {\n type: 'announcement_bar';\n config: AnnouncementBarConfig;\n })\n | (StorefrontAddonInstanceBase & {\n type: 'countdown_bar';\n config: CountdownBarConfig;\n })\n | (StorefrontAddonInstanceBase & {\n type: 'promo_info_card';\n config: PromoInfoCardConfig;\n })\n | (StorefrontAddonInstanceBase & {\n type: 'recent_purchase_popup';\n config: RecentPurchasePopupConfig;\n })\n | (StorefrontAddonInstanceBase & {\n type: 'coupon_popup_modal';\n config: CouponPopupModalConfig;\n })\n | (StorefrontAddonInstanceBase & {\n type: 'live_chat';\n config: LiveChatConfig;\n });\n\nexport interface StorefrontAddonCatalogItem {\n type: StorefrontAddonType;\n title: string;\n description: string;\n slots: StorefrontAddonSlot[];\n supportsMultiple: boolean;\n features: string[];\n defaults: StorefrontAddonCreateInput;\n}\n\nexport interface AnnouncementBarResolvedProps extends AnnouncementBarConfig {\n addonId: string;\n}\n\nexport interface CountdownBarResolvedProps extends CountdownBarConfig {\n addonId: string;\n}\n\nexport interface PromoInfoCardResolvedProps extends PromoInfoCardConfig {\n addonId: string;\n}\n\nexport interface RecentPurchasePopupItem {\n customerLabel: string;\n productTitle: string;\n createdAt: string;\n}\n\nexport interface RecentPurchasePopupResolvedProps {\n addonId: string;\n title: string;\n cooldownSeconds: number;\n items: RecentPurchasePopupItem[];\n}\n\nexport interface CouponPopupModalResolvedProps extends CouponPopupModalConfig {\n addonId: string;\n}\n\nexport interface LiveChatResolvedProps extends LiveChatConfig {\n addonId: string;\n}\n\nexport type ResolvedStorefrontAddon =\n | {\n id: string;\n type: 'announcement_bar';\n slot: StorefrontAddonSlot;\n component: 'announcement_bar';\n sortOrder: number;\n props: AnnouncementBarResolvedProps;\n }\n | {\n id: string;\n type: 'countdown_bar';\n slot: StorefrontAddonSlot;\n component: 'countdown_bar';\n sortOrder: number;\n props: CountdownBarResolvedProps;\n }\n | {\n id: string;\n type: 'promo_info_card';\n slot: StorefrontAddonSlot;\n component: 'promo_info_card';\n sortOrder: number;\n props: PromoInfoCardResolvedProps;\n }\n | {\n id: string;\n type: 'recent_purchase_popup';\n slot: StorefrontAddonSlot;\n component: 'recent_purchase_popup';\n sortOrder: number;\n props: RecentPurchasePopupResolvedProps;\n }\n | {\n id: string;\n type: 'coupon_popup_modal';\n slot: StorefrontAddonSlot;\n component: 'coupon_popup_modal';\n sortOrder: number;\n props: CouponPopupModalResolvedProps;\n }\n | {\n id: string;\n type: 'live_chat';\n slot: StorefrontAddonSlot;\n component: 'live_chat';\n sortOrder: number;\n props: LiveChatResolvedProps;\n };\n\nexport interface StorefrontAddonBootstrap {\n items: ResolvedStorefrontAddon[];\n}\n","export const MANUAL_GATEWAY_TEMPLATE_VARIABLES = [\n 'amount',\n 'currency',\n 'invoice_id',\n 'customer_email',\n 'id',\n 'email',\n 'price',\n 'price_usd',\n 'product_name',\n 'quantity',\n] as const;\n\nexport type ManualGatewayTemplateVariable = typeof MANUAL_GATEWAY_TEMPLATE_VARIABLES[number];\nexport type ManualGatewayTemplateVars = Record<string, string>;\n\nexport const MANUAL_GATEWAY_TEMPLATE_VARIABLE_EXAMPLES = [\n '{{amount}}',\n '{{currency}}',\n '{{invoice_id}}',\n '{{customer_email}}',\n '{id}',\n '{email}',\n '{price}',\n '{currency}',\n '{price_usd}',\n '{product_name}',\n '{quantity}',\n] as const;\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nfunction buildVariablePattern(key: string, style: 'double' | 'single'): RegExp {\n const escapedKey = escapeRegExp(key);\n if (style === 'double') {\n return new RegExp(`\\\\{\\\\{\\\\s*${escapedKey}\\\\s*\\\\}\\\\}`, 'gi');\n }\n\n return new RegExp(`(?<!\\\\{)\\\\{\\\\s*${escapedKey}\\\\s*\\\\}(?!\\\\})`, 'gi');\n}\n\nexport function renderManualGatewayTemplate(\n template: string,\n vars: ManualGatewayTemplateVars,\n options: { encodeValues?: boolean } = {},\n): string {\n let rendered = template;\n for (const [key, value] of Object.entries(vars)) {\n const replacement = options.encodeValues ? encodeURIComponent(value) : value;\n rendered = rendered.replace(buildVariablePattern(key, 'double'), replacement);\n rendered = rendered.replace(buildVariablePattern(key, 'single'), replacement);\n }\n return rendered;\n}\n\nconst PLACEHOLDER_SCAN_PATTERNS = [\n /\\{\\{\\s*([a-zA-Z][a-zA-Z0-9_]*)\\s*\\}\\}/g,\n /(?<!\\{)\\{\\s*([a-zA-Z][a-zA-Z0-9_]*)\\s*\\}(?!\\})/g,\n] as const;\n\nconst REMAINING_PLACEHOLDER_PATTERNS = [\n /\\{\\{[\\s\\S]*?\\}\\}/g,\n /(?<!\\{)\\{[^{}]+\\}(?!\\})/g,\n] as const;\n\nexport const MANUAL_GATEWAY_CUSTOM_FIELD_NAME_PATTERN = /^[a-zA-Z][a-zA-Z0-9_]*$/;\n\nexport function isValidManualGatewayCustomFieldName(name: string): boolean {\n return MANUAL_GATEWAY_CUSTOM_FIELD_NAME_PATTERN.test(name.trim());\n}\n\nexport function findUnsupportedManualGatewayPlaceholders(\n template: string,\n additionalVariables: Iterable<string> = [],\n): string[] {\n if (!template.trim()) {\n return [];\n }\n\n const allowedVariables = new Set<string>(MANUAL_GATEWAY_TEMPLATE_VARIABLES);\n for (const variable of additionalVariables) {\n const normalized = variable.trim().toLowerCase();\n if (normalized) {\n allowedVariables.add(normalized);\n }\n }\n\n const unsupported = new Set<string>();\n // Track the raw spans of syntactically-valid placeholders that ARE allowed, so\n // we don't double-flag them when sweeping for malformed syntax below.\n const allowedRawSpans = new Set<string>();\n for (const pattern of PLACEHOLDER_SCAN_PATTERNS) {\n for (const match of template.matchAll(pattern)) {\n const raw = match[0];\n const name = match[1]?.toLowerCase();\n if (name && !allowedVariables.has(name)) {\n unsupported.add(raw);\n } else if (name) {\n allowedRawSpans.add(raw);\n }\n }\n }\n\n // Also reject ANY remaining {{...}}/{...} placeholder syntax that is not an\n // allowed variable — a mistyped or filtered token such as `{{order-id}}` or\n // `{{ amount | money }}` is not caught by the strict name patterns above, so\n // it would survive save and only fail at checkout (session 400 / raw token in\n // instructions). Flag it at save time instead.\n for (const pattern of REMAINING_PLACEHOLDER_PATTERNS) {\n for (const match of template.matchAll(pattern)) {\n const raw = match[0];\n if (!allowedRawSpans.has(raw)) {\n unsupported.add(raw);\n }\n }\n }\n\n return [...unsupported];\n}\n\nexport function collectUnsupportedManualGatewayPlaceholders(\n ...templates: Array<string | null | undefined>\n): string[] {\n const unsupported = new Set<string>();\n for (const template of templates) {\n for (const placeholder of findUnsupportedManualGatewayPlaceholders(template ?? '')) {\n unsupported.add(placeholder);\n }\n }\n return [...unsupported];\n}\n\nexport function collectUnsupportedManualGatewayPlaceholdersWithExtras(\n additionalVariables: Iterable<string>,\n ...templates: Array<string | null | undefined>\n): string[] {\n const unsupported = new Set<string>();\n for (const template of templates) {\n for (const placeholder of findUnsupportedManualGatewayPlaceholders(template ?? '', additionalVariables)) {\n unsupported.add(placeholder);\n }\n }\n return [...unsupported];\n}\n\nconst RESERVED_MANUAL_GATEWAY_FIELD_NAMES = new Set<string>(\n MANUAL_GATEWAY_TEMPLATE_VARIABLES.map((name) => name.toLowerCase()),\n);\n\nexport function isReservedManualGatewayFieldName(name: string): boolean {\n const normalized = name.trim().toLowerCase();\n return normalized.length > 0 && RESERVED_MANUAL_GATEWAY_FIELD_NAMES.has(normalized);\n}\n\nexport function findRemainingManualGatewayPlaceholders(template: string): string[] {\n if (!template.trim()) {\n return [];\n }\n\n const remaining = new Set<string>();\n for (const pattern of REMAINING_PLACEHOLDER_PATTERNS) {\n for (const match of template.matchAll(pattern)) {\n remaining.add(match[0]);\n }\n }\n\n return [...remaining];\n}\n\nexport function stableGatewayFieldValuesKey(fields: Record<string, string> | null | undefined): string {\n if (!fields) {\n return '{}';\n }\n\n const sortedEntries = Object.keys(fields)\n .sort((left, right) => left.localeCompare(right))\n .map((key) => [key, fields[key]] as const);\n\n return JSON.stringify(sortedEntries);\n}\n\nexport function isSafeManualGatewayRedirectUrl(url: string): boolean {\n const trimmed = url.trim();\n if (!trimmed) {\n return false;\n }\n\n try {\n const parsed = new URL(trimmed);\n return parsed.protocol === 'http:' || parsed.protocol === 'https:';\n } catch {\n return false;\n }\n}\n\nexport function mergeManualGatewayTemplateVars(\n trustedVars: ManualGatewayTemplateVars,\n gatewayFieldVars: Record<string, string> = {},\n): ManualGatewayTemplateVars {\n return {\n ...gatewayFieldVars,\n ...trustedVars,\n };\n}\n","import { z } from 'zod';\n\n/**\n * Versioned wire contract between Shoppex and a merchant-owned payment adapter.\n * A literal version makes breaking changes fail closed instead of being guessed.\n */\nexport const EXTERNAL_PAYMENT_ADAPTER_CONTRACT_VERSION = '2026-08-14' as const;\nexport { EXTERNAL_PAYMENT_ADAPTER_GATEWAY_PREFIX } from './payment-gateways.js';\nexport const EXTERNAL_PAYMENT_ADAPTER_TRUST_LEVEL = 'MERCHANT_ATTESTED' as const;\nexport const EXTERNAL_PAYMENT_ADAPTER_CONFORMANCE_PATH = '/.well-known/shoppex-payment-adapter' as const;\n\n/**\n * Maximum non-archived adapters per shop, matching the manual-gateway cap.\n * Enforced in ExternalPaymentAdapterService.create; the dashboard reads the\n * same constant for its usage badge so the two cannot drift.\n */\nexport const MAX_EXTERNAL_PAYMENT_ADAPTERS = 10;\n\nconst currencySchema = z.string().regex(/^[A-Z]{3}$/, 'Currency must be a three-letter uppercase code.');\nconst absoluteHttpsUrlSchema = z.string().url().refine(\n (value) => new URL(value).protocol === 'https:',\n 'URL must use HTTPS.',\n);\n\nconst externalPaymentAdapterBaseSchema = z.object({\n version: z.literal(EXTERNAL_PAYMENT_ADAPTER_CONTRACT_VERSION),\n});\n\nexport const externalPaymentAdapterSessionRequestSchema = externalPaymentAdapterBaseSchema.extend({\n type: z.literal('payment.session.create'),\n data: z.object({\n attempt_id: z.string().uuid(),\n invoice_id: z.string().uuid(),\n amount_minor: z.number().int().safe().positive(),\n currency: currencySchema,\n customer_email: z.string().email().nullable(),\n description: z.string().min(1).max(500),\n success_url: absoluteHttpsUrlSchema,\n cancel_url: absoluteHttpsUrlSchema,\n event_url: absoluteHttpsUrlSchema,\n }),\n});\n\nexport const externalPaymentAdapterSessionResponseSchema = externalPaymentAdapterBaseSchema.extend({\n provider_reference: z.string().trim().min(1).max(255),\n checkout_url: absoluteHttpsUrlSchema,\n expires_at: z.iso.datetime({ offset: true }).nullable().optional(),\n});\n\nexport const externalPaymentAdapterEventSchema = externalPaymentAdapterBaseSchema.extend({\n type: z.enum([\n 'payment.processing',\n 'payment.succeeded',\n 'payment.failed',\n ]),\n data: z.object({\n attempt_id: z.string().uuid(),\n provider_reference: z.string().trim().min(1).max(255),\n amount_minor: z.number().int().safe().positive(),\n currency: currencySchema,\n occurred_at: z.iso.datetime({ offset: true }).nullable().optional(),\n }),\n});\n\nexport const externalPaymentAdapterConformanceRequestSchema = externalPaymentAdapterBaseSchema.extend({\n type: z.literal('adapter.conformance.run'),\n data: z.object({\n challenge_id: z.string().uuid(),\n mode: z.enum(['standard', 'timeout']),\n expected_event: z.object({\n attempt_id: z.string().uuid(),\n provider_reference: z.string().trim().min(1).max(255),\n amount_minor: z.number().int().safe().positive(),\n currency: currencySchema,\n }),\n }),\n});\n\nexport const externalPaymentAdapterConformanceSampleSchema = z.object({\n scenario: z.enum([\n 'valid_event',\n 'amount_mismatch',\n 'duplicate_event_first',\n 'duplicate_event_retry',\n ]),\n webhook_id: z.string().trim().min(1).max(255),\n webhook_timestamp: z.string().trim().min(1).max(32),\n webhook_signature: z.string().trim().min(1).max(1024),\n raw_body: z.string().min(1).max(4096),\n});\n\nexport const externalPaymentAdapterConformanceResponseSchema = externalPaymentAdapterBaseSchema.extend({\n type: z.literal('adapter.conformance.result'),\n data: z.object({\n challenge_id: z.string().uuid(),\n samples: z.array(externalPaymentAdapterConformanceSampleSchema).length(4),\n }),\n});\n\nexport type ExternalPaymentAdapterSessionRequest = z.infer<\n typeof externalPaymentAdapterSessionRequestSchema\n>;\nexport type ExternalPaymentAdapterSessionResponse = z.infer<\n typeof externalPaymentAdapterSessionResponseSchema\n>;\nexport type ExternalPaymentAdapterEvent = z.infer<typeof externalPaymentAdapterEventSchema>;\nexport type ExternalPaymentAdapterConformanceRequest = z.infer<\n typeof externalPaymentAdapterConformanceRequestSchema\n>;\nexport type ExternalPaymentAdapterConformanceSample = z.infer<\n typeof externalPaymentAdapterConformanceSampleSchema\n>;\nexport type ExternalPaymentAdapterConformanceResponse = z.infer<\n typeof externalPaymentAdapterConformanceResponseSchema\n>;\n\nexport function buildExternalPaymentAdapterConformanceUrl(sessionEndpoint: string): string | null {\n try {\n const url = new URL(sessionEndpoint);\n if (url.protocol !== 'https:') return null;\n url.pathname = EXTERNAL_PAYMENT_ADAPTER_CONFORMANCE_PATH;\n url.search = '';\n url.hash = '';\n return url.toString();\n } catch {\n return null;\n }\n}\n\n// The gateway-key helpers live in payment-gateways.ts: that module is part of\n// the checkout client bundle and must not import this one (its relative\n// specifier breaks either NodeNext tsc, the tsup DTS build, or Turbopack,\n// depending on how it is written). This module is server-only, so re-exporting\n// from there is safe.\nexport {\n buildExternalPaymentAdapterGatewayKey,\n isExternalPaymentAdapterGatewayKey,\n parseExternalPaymentAdapterGatewayKey,\n type ExternalPaymentAdapterGatewayKey,\n} from './payment-gateways.js';\n","// Standalone product-redirect placeholder engine. Intentionally does NOT import from\n// manual-gateway-template.ts: that file is consumed via its own package subpath export\n// (@shoppex/contracts/manual-gateway-template), and a cross-subpath relative import here\n// breaks Next.js/Turbopack module resolution for client components that only depend on\n// this subpath. The scan/render logic is small enough to duplicate safely.\n\nexport const PRODUCT_REDIRECT_TEMPLATE_VARIABLES = ['product_id', 'order_id'] as const;\n\nexport type ProductRedirectTemplateVariable = typeof PRODUCT_REDIRECT_TEMPLATE_VARIABLES[number];\nexport type ProductRedirectTemplateVars = Record<ProductRedirectTemplateVariable, string>;\n\nexport const PRODUCT_REDIRECT_TEMPLATE_VARIABLE_EXAMPLES = [\n '{{product_id}}',\n '{{order_id}}',\n] as const;\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nfunction buildVariablePattern(key: string, style: 'double' | 'single'): RegExp {\n const escapedKey = escapeRegExp(key);\n if (style === 'double') {\n return new RegExp(`\\\\{\\\\{\\\\s*${escapedKey}\\\\s*\\\\}\\\\}`, 'gi');\n }\n\n return new RegExp(`(?<!\\\\{)\\\\{\\\\s*${escapedKey}\\\\s*\\\\}(?!\\\\})`, 'gi');\n}\n\n// Accepts a partial var map: only the keys present (and non-empty) are\n// substituted. A variable the caller cannot supply is left as a raw placeholder\n// so downstream fail-closed checks (findRemainingProductRedirectPlaceholders)\n// reject the URL instead of emitting an encoded \"\" / \"null\".\nexport function renderProductRedirectTemplate(\n template: string,\n vars: Partial<ProductRedirectTemplateVars>,\n): string {\n let rendered = template;\n for (const [key, value] of Object.entries(vars)) {\n if (typeof value !== 'string' || value.length === 0) continue;\n const replacement = encodeURIComponent(value);\n rendered = rendered.replace(buildVariablePattern(key, 'double'), replacement);\n rendered = rendered.replace(buildVariablePattern(key, 'single'), replacement);\n }\n return rendered;\n}\n\nconst PLACEHOLDER_SCAN_PATTERNS = [\n /\\{\\{\\s*([a-zA-Z][a-zA-Z0-9_]*)\\s*\\}\\}/g,\n /(?<!\\{)\\{\\s*([a-zA-Z][a-zA-Z0-9_]*)\\s*\\}(?!\\})/g,\n] as const;\n\nconst REMAINING_PLACEHOLDER_PATTERNS = [\n /\\{\\{[\\s\\S]*?\\}\\}/g,\n /(?<!\\{)\\{[^{}]+\\}(?!\\})/g,\n] as const;\n\n// A fully rendered redirect URL never contains a literal curly brace — any `{`\n// or `}` left after substitution is a malformed/unrendered placeholder fragment\n// (e.g. the unbalanced `{{product_id` or trailing `}` in `{{product_id}}}`).\n// The balanced-span patterns above miss these, so scan for any brace that\n// survives once the balanced spans are stripped out.\nfunction findDanglingBraceFragments(template: string): string[] {\n let stripped = template;\n for (const pattern of REMAINING_PLACEHOLDER_PATTERNS) {\n stripped = stripped.replace(pattern, '');\n }\n return /[{}]/.test(stripped) ? [...new Set(stripped.match(/[{}]+/g) ?? [])] : [];\n}\n\nexport function findUnsupportedProductRedirectPlaceholders(template: string): string[] {\n if (!template.trim()) {\n return [];\n }\n\n const allowedVariables = new Set<string>(PRODUCT_REDIRECT_TEMPLATE_VARIABLES);\n const unsupported = new Set<string>();\n const allowedRawSpans = new Set<string>();\n\n for (const pattern of PLACEHOLDER_SCAN_PATTERNS) {\n for (const match of template.matchAll(pattern)) {\n const raw = match[0];\n const name = match[1]?.toLowerCase();\n if (name && !allowedVariables.has(name)) {\n unsupported.add(raw);\n } else if (name) {\n allowedRawSpans.add(raw);\n }\n }\n }\n\n // Also reject malformed placeholder syntax (e.g. {{order-id}}, {{ product_id | x }}) that the\n // strict name patterns above don't match — same rationale as the manual-gateway scanner: catch\n // it at save time instead of letting a raw token survive to checkout.\n for (const pattern of REMAINING_PLACEHOLDER_PATTERNS) {\n for (const match of template.matchAll(pattern)) {\n const raw = match[0];\n if (!allowedRawSpans.has(raw)) {\n unsupported.add(raw);\n }\n }\n }\n\n // Reject unbalanced braces (e.g. `{{product_id` or `{{product_id}}}`) that the\n // balanced-span patterns never see — fail closed at save time rather than\n // letting a malformed token reach checkout.\n for (const fragment of findDanglingBraceFragments(template)) {\n unsupported.add(fragment);\n }\n\n return [...unsupported];\n}\n\nexport function findRemainingProductRedirectPlaceholders(template: string): string[] {\n if (!template.trim()) {\n return [];\n }\n\n const remaining = new Set<string>();\n for (const pattern of REMAINING_PLACEHOLDER_PATTERNS) {\n for (const match of template.matchAll(pattern)) {\n remaining.add(match[0]);\n }\n }\n\n // A rendered URL must not carry any leftover brace — including unbalanced ones\n // the balanced-span patterns miss — or checkout would redirect to a literal\n // malformed token instead of failing closed.\n for (const fragment of findDanglingBraceFragments(template)) {\n remaining.add(fragment);\n }\n\n return [...remaining];\n}\n\nexport function isSafeHttpsRedirectTemplateUrl(url: string): boolean {\n const trimmed = url.trim();\n if (!trimmed) {\n return false;\n }\n\n try {\n const parsed = new URL(trimmed);\n return parsed.protocol === 'https:';\n } catch {\n return false;\n }\n}\n","import { z } from 'zod';\n\nconst unknownRecordSchema = z.record(z.string(), z.unknown());\nconst stringOrNumberSchema = z.union([z.string(), z.number()]);\n\nexport const embedPaymentSessionWireSchema = z.object({\n kind: z.enum(['address', 'redirect', 'embed_pending']),\n gateway: z.string(),\n checkout_url: z.string().nullable().optional(),\n address: z.string().optional(),\n amount: z.string().optional(),\n qr_code: z.string().optional(),\n expires_at: z.string().optional(),\n payment_id: z.string().optional(),\n confirmations_needed: z.number().optional(),\n}).passthrough();\n\nconst publicInvoiceWireCustomFieldDefinitionSchema = z.object({\n default_value: z.string().optional(),\n min_length: z.number().optional(),\n name: z.string(),\n placeholder: z.string().optional(),\n regex: z.string().optional(),\n required: z.boolean(),\n type: z.string(),\n});\n\nconst publicInvoiceWireProductAddonSchema = z.object({\n id: z.string(),\n price: z.number(),\n quantity: z.number(),\n title: z.string(),\n});\n\nconst publicInvoiceWireAvailableAddonSchema = z.object({\n currency: z.string(),\n description: z.string(),\n id: z.string(),\n price: z.number(),\n title: z.string(),\n uniqid: z.string(),\n});\n\n/**\n * A null display price is only a legal wire state for PWYW products; a\n * fixed-price producer omitting it is a broken contract and must keep\n * failing fast (AGENTS.md forward-only rule).\n */\nfunction requirePriceDisplayUnlessPayWhatYouWant(\n product: { price_display: string | number | null; pay_what_you_want?: boolean },\n ctx: z.RefinementCtx,\n): void {\n if (product.price_display === null && product.pay_what_you_want !== true) {\n ctx.addIssue({\n code: 'custom',\n path: ['price_display'],\n message: 'price_display may only be null for pay_what_you_want products.',\n });\n }\n}\n\nconst publicInvoiceWireProductSchema = z.object({\n addons: z.array(publicInvoiceWireProductAddonSchema).optional(),\n /** Per-line cart-edit capability from the enricher; the checkout renders no\n * control without an explicit true. */\n quantity_editable: z.boolean().optional(),\n addons_editable: z.boolean().optional(),\n removable: z.boolean().optional(),\n available_addons: z.array(z.unknown()).optional(),\n cloudflare_image_id: z.string().nullable(),\n created_at: z.string().optional(),\n currency: z.string(),\n custom_fields: unknownRecordSchema.nullable().optional(),\n custom_fields_config: z.array(publicInvoiceWireCustomFieldDefinitionSchema).nullable().optional(),\n delivery_instruction: z.unknown().optional(),\n delivery_instruction_config: z.unknown().optional(),\n delivery_instruction_label: z.unknown().optional(),\n delivery_text: z.string().nullable().optional(),\n // Delivery wait as a bare COUNT. `0` and `null` both mean instant (the\n // digital-goods default); a positive value is a \"within N <unit>\" promise.\n delivery_time: z.number().nullable().optional(),\n // The unit `delivery_time` is counted in. The column is NOT NULL with a\n // `days` default — which is what every row meant before the unit existed — so\n // a live producer always sends one. It stays optional here because this\n // schema also describes payment-link and other synthesized products that\n // carry no catalog row, and those quote no wait at all.\n delivery_time_unit: z.enum(['minutes', 'hours', 'days']).nullable().optional(),\n description: z.string().nullable(),\n discount_percent: z.number().optional(),\n discount_display: z.number().optional(),\n discounted_total_display: z.number().optional(),\n gateways: z.array(z.string()).nullable().optional(),\n id: z.string().optional(),\n image_name: z.string().nullable(),\n image_storage: z.string().nullable().optional(),\n line_item_id: z.string().nullable().optional(),\n pay_what_you_want: z.boolean().optional(),\n price: z.string().optional(),\n // Nullable ONLY for PWYW products (no fixed catalog price until the buyer\n // chooses one) — enforced by requirePriceDisplayUnlessPayWhatYouWant below,\n // so a fixed-price producer dropping the field still fails fast.\n price_display: stringOrNumberSchema.nullable(),\n quantity: z.number(),\n quantity_max: z.number().optional(),\n quantity_min: z.number().optional(),\n recurring_interval: z.string().nullable().optional(),\n recurring_interval_count: z.number().nullable().optional(),\n redirect_link: z.string().nullable().optional(),\n redirect_time: z.number().nullable().optional(),\n service_text: z.string().nullable().optional(),\n setup_cost: z.string().optional(),\n slug: z.string().nullable().optional(),\n storefront_url: z.string().nullable().optional(),\n status: z.string().nullable().optional(),\n subtype: z.string().nullable().optional(),\n terms_of_service: z.string().nullable().optional(),\n title: z.string(),\n total: z.number(),\n trial_period: z.number().nullable().optional(),\n type: z.string().nullable().optional(),\n uniqid: z.string().nullable(),\n unit_price: z.number().optional(),\n unit_price_display: stringOrNumberSchema.optional(),\n unit_quantity: z.number(),\n updated_at: z.string().optional(),\n variant_title: z.string().nullable().optional(),\n video_link: z.string().nullable().optional(),\n volume_discounts: z.unknown().optional(),\n /** The SHORT replacement/refund eligibility window, in SECONDS. */\n warranty_days: z.number().nullable().optional(),\n warranty_text: z.string().nullable().optional(),\n /**\n * Long-term per-purchase coverage in DAYS, or null/absent for none.\n *\n * Deliberately a second field beside `warranty_days` rather than a rename:\n * they are different features that a similar name keeps conflating.\n * `warranty_days` is the seconds-long refund window; this is\n * Before payment this is the current `products.warranty_period_days` value.\n * After completion it is the invoice line's activated\n * `order_item_warranties.period_days` snapshot, so later product edits cannot\n * rewrite the buyer's receipt. Buyer surfaces read THIS one — reading\n * `warranty_days` would print a seconds count as a day count.\n */\n warranty_period_days: z.number().nullable().optional(),\n});\n\nconst gatewayFeePreviewSchema = z.object({\n amount: z.number(),\n gateway: z.string(),\n});\n\nconst checkoutTippingSchema = z.object({\n custom_tip_enabled: z.boolean().optional(),\n enabled: z.boolean(),\n preset_percentages: z.array(z.number()).optional(),\n});\n\nconst customerBalanceSchema = z.object({\n allow_partial_payment: z.boolean().optional(),\n auto_apply: z.boolean().optional(),\n available: z.string(),\n currency: z.string(),\n});\n\nconst pricingBreakdownSchema = z.object({\n affiliate_code: z.string().nullable().optional(),\n already_paid: stringOrNumberSchema.nullable().optional(),\n amount_due: stringOrNumberSchema.nullable().optional(),\n currency: z.string().nullable().optional(),\n discount: stringOrNumberSchema.nullable().optional(),\n volume_discount: stringOrNumberSchema.nullable().optional(),\n discount_label: z.string().nullable().optional(),\n gateway_fee: stringOrNumberSchema.nullable().optional(),\n platform_fee: stringOrNumberSchema.nullable().optional(),\n processing_fee: stringOrNumberSchema.nullable().optional(),\n subtotal: stringOrNumberSchema.nullable().optional(),\n tip: stringOrNumberSchema.nullable().optional(),\n total: stringOrNumberSchema.nullable().optional(),\n});\n\nconst pollingSchema = z.object({\n active: z.boolean(),\n expires_at: z.string(),\n});\n\nconst supportSchema = z.object({\n faq_url: z.string().nullable(),\n support_email: z.string().nullable(),\n support_url: z.string().nullable(),\n telegram_invite: z.string().nullable(),\n /** shop_social_links.discord — the checkout renders an optional join row from it. */\n discord_invite_url: z.string().nullable(),\n});\n\nconst gatewayEligibilityStateSchema = z.object({\n currency: z.string().nullable().optional(),\n enabled: z.boolean(),\n max_amount: z.number().nullable().optional(),\n min_amount: z.number().nullable().optional(),\n reason: z.enum(['BELOW_MIN_AMOUNT', 'ABOVE_MAX_AMOUNT']).nullable().optional(),\n});\n\nconst deliverySchema = z.object({\n delivered_items: z.array(z.unknown()),\n downloads: z.array(z.unknown()),\n external_urls: z.array(z.unknown()),\n license_keys: z.array(z.unknown()),\n tracking_codes: z.array(z.unknown()),\n});\n\nconst underpaymentSchema = z.object({\n active: z.boolean().optional(),\n attempt_id: z.string().optional(),\n buyer_actionable: z.boolean().nullable().optional(),\n crypto_currency: z.string().nullable().optional(),\n currency: z.string().optional(),\n expected_amount: z.string().nullable().optional(),\n expected_crypto_amount: z.string().nullable().optional(),\n last_checked_at: z.string().optional(),\n missing_amount: z.string().nullable().optional(),\n missing_crypto_amount: z.string().nullable().optional(),\n // InvoiceEnricher.applyUnderpayment serializes providerReference ?? null —\n // an active underpayment without a provider reference is a valid payload.\n provider_reference: z.string().nullable().optional(),\n provider_status: z.string().nullable().optional(),\n received_amount: z.string().nullable().optional(),\n /** Display-only fiat estimate for the crypto amount observed on-chain. */\n received_fiat_estimate: z.string().nullable().optional(),\n received_crypto_amount: z.string().nullable().optional(),\n shortfall_percent: z.string().nullable().optional(),\n buyer_action_reason: z.enum([\n 'BELOW_MINIMUM_COLLECTIBLE',\n 'PROVIDER_SESSION_CLOSED',\n 'PROVIDER_TOP_UP_UNSUPPORTED',\n 'MERCHANT_REVIEW_REQUIRED',\n ]).nullable().optional(),\n});\n\nconst statusHistoryEntrySchema = z.object({\n created_at: z.string().nullable(),\n details: z.string().nullable(),\n id: z.string(),\n invoice_id: z.string(),\n status: z.string().nullable(),\n});\n\nconst paymentMethodOverrideSchema = z.object({\n billing_address_mode: z.enum(['INHERIT', 'REQUIRED', 'DISABLED']).optional(),\n button_label: z.string().nullable().optional(),\n display_name: z.string().nullable().optional(),\n gateway: z.string(),\n hide_provider_attribution: z.boolean().optional(),\n icon_url: z.string().nullable().optional(),\n terms_mode: z.enum(['INHERIT', 'REQUIRED', 'DISABLED']).optional(),\n});\n\nconst customGatewaySchema = z.object({\n custom_fields: z.array(z.unknown()).optional(),\n description: z.string().nullable(),\n display_order: z.number(),\n icon_preset: z.string().nullable(),\n icon_url: z.string().nullable(),\n id: z.string(),\n instructions: z.string().nullable(),\n is_active: z.boolean().optional(),\n name: z.string(),\n payment_type: z.enum(['INSTRUCTIONS', 'REDIRECT']),\n redirect_url: z.string().nullable(),\n require_proof: z.boolean(),\n // Which fields the buyer has to fill in when proof is required. Optional so\n // an older cached payload stays parseable; the checkout falls back to BOTH.\n proof_type: z.enum(['TEXT', 'IMAGE', 'BOTH']).optional(),\n void_after_hours: z.number(),\n});\n\nconst externalPaymentAdapterSchema = z.object({\n description: z.string().nullable(),\n display_order: z.number(),\n icon_url: z.string().nullable(),\n id: z.string(),\n name: z.string(),\n});\n\nconst buyerIdentitySchema = z.object({\n email: z.object({\n masked: z.string().nullable(),\n persisted: z.boolean(),\n required_for_provider_session: z.boolean().optional(),\n }),\n});\n\nconst cryptoTransactionSchema = z.object({\n amount: z.string().nullable(),\n confirmations: z.number().nullable(),\n created_at: z.number().optional(),\n hash: z.string().nullable(),\n status: z.string().optional(),\n});\n\nconst voidTimeSchema = z.object({\n conf: z.object({\n partial: z.number().optional(),\n void: z.number(),\n waiting_for_confirmations: z.number().optional(),\n }),\n gateways: z.array(z.string()),\n});\n\nconst invoicePaymentSessionStateSchema = z.object({\n invoice_payable: z.boolean(),\n resumable: z.boolean(),\n resumable_gateway: z.string().nullable(),\n gateway: z.string().nullable().optional(),\n crypto_gateway: z.string().nullable().optional(),\n processor: z.string().nullable().optional(),\n flow_type: z.string().nullable().optional(),\n status: z.string().nullable().optional(),\n provider_reference: z.string().nullable().optional(),\n provider_reference_type: z.string().nullable().optional(),\n capture_id: z.string().nullable().optional(),\n manual_confirmation_pending: z.boolean().optional(),\n payment_method_switch_locked: z.boolean().optional(),\n awaiting_payment_method: z.boolean().optional(),\n started_at: z.number().nullable().optional(),\n completed_at: z.number().nullable().optional(),\n});\n\nconst embedInvoicePaymentSessionStateSchema = invoicePaymentSessionStateSchema.extend({\n gateway: z.string().nullable(),\n flow_type: z.string().nullable(),\n status: z.string().nullable(),\n manual_confirmation_pending: z.boolean(),\n payment_method_switch_locked: z.boolean(),\n});\n\n// Historic-data tolerance: invoices created before the embed surface collapsed\n// to a single design froze an `embed_design` key into\n// `invoices.checkout_style_snapshot`, and the API still serves those rows. This\n// object is non-strict, so the retired key is accepted and stripped rather than\n// rejected. Nothing reads it.\n//\n// The tolerance is deliberate but NOT self-evident — a non-strict object looks\n// like an oversight next to the `.strict()` schemas around it — so the\n// behaviour is pinned by\n// `apps/backend/tests/unit/style-center/invoice-wire-embed-design-tolerance.test.ts`\n// and listed for deletion in `docs/architecture/domains/style-center.md`,\n// Release 2. Unlike the transport and session shims this one has no runtime\n// signal to watch: the retired key is frozen into already-written invoice rows\n// rather than arriving from a client, so its removal condition is a data\n// question (are there pre-release invoices still being served?), answered\n// against `invoices.checkout_style_snapshot`, not a log line.\nconst checkoutStyleStateSchema = z.object({\n theme_id: z.string().nullable(),\n surface: z.enum(['checkout', 'payment_link', 'embed']),\n token_schema_version: z.literal(1),\n revision: z.number(),\n tokens: unknownRecordSchema,\n custom_css: z.string(),\n css_variables: z.record(z.string(), z.string()),\n});\n\nconst paymentRescueSchema = z.object({\n link_id: z.string(),\n source_gateway: z.string().nullable(),\n invoice_uniqid: z.string(),\n deprioritize_source_gateway: z.boolean().optional(),\n});\n\nconst discordIntegrationStateSchema = z.object({\n enabled: z.boolean(),\n required: z.boolean(),\n connected: z.boolean(),\n});\n\nconst shopPaymentGatewayFeeSchema = z.object({\n gateway: z.string().nullable().optional(),\n active_type: z.string().nullable().optional(),\n percent_amount: stringOrNumberSchema.nullable().optional(),\n fixed_amount: stringOrNumberSchema.nullable().optional(),\n fixed_currency: z.string().nullable().optional(),\n});\n\nconst invoiceRewardItemSchema = z.object({\n id: z.string(),\n type: z.enum(['WALLET_CREDIT', 'COUPON']),\n status: z.enum(['PENDING', 'FULFILLED', 'FAILED', 'REVOKED']),\n amount: z.string().nullable(),\n currency: z.string().nullable(),\n coupon_code: z.string().nullable(),\n reason: z.enum([\n 'ORDER_COMPLETED',\n 'ORDER_COUNT_REACHED',\n 'SPEND_AMOUNT_REACHED',\n 'POSITIVE_REVIEW_LEFT',\n 'FIRST_PURCHASE_COMPLETED',\n ]),\n trigger_reference_type: z.string(),\n trigger_reference_id: z.string(),\n created_at: z.number(),\n fulfilled_at: z.number().nullable(),\n expires_at: z.number().nullable(),\n});\n\nconst invoiceRewardsSchema = z.object({\n summary: z.object({\n available: z.string(),\n pending: z.string(),\n lifetime_earned: z.string(),\n redeemed: z.string().nullable(),\n currency: z.string(),\n }),\n activity: z.array(invoiceRewardItemSchema),\n earned_after_invoice: z.array(invoiceRewardItemSchema),\n pending_after_invoice: z.array(invoiceRewardItemSchema),\n});\n\n/**\n * Public invoice JSON after `toInvoiceTransportSnakeCase`.\n *\n * Gateway-specific invoice row fields can still pass the backend allowlist.\n * Unknown top-level keys are therefore preserved, while every known key is\n * validated whenever it is present.\n */\nexport const publicInvoiceWireSchema = z.object({\n already_paid_amount: stringOrNumberSchema.nullable().optional(),\n apm_method: z.string().nullable().optional(),\n blockchain: z.string().nullable(),\n buyer_identity: buyerIdentitySchema.nullable().optional(),\n checkout_tipping: checkoutTippingSchema.nullable().optional(),\n country_regulations: z.string().nullable().optional(),\n coupon_applied: z.boolean().optional(),\n crypto_mode: z.string().nullable().optional(),\n crypto_transactions: z.array(cryptoTransactionSchema).optional(),\n currency: z.string().nullable(),\n custom_fields: unknownRecordSchema.nullable().optional(),\n custom_gateways: z.array(customGatewaySchema).optional(),\n external_payment_adapters: z.array(externalPaymentAdapterSchema).optional(),\n customer_balance: customerBalanceSchema.nullable().optional(),\n customer_email_masked: z.string().nullable().optional(),\n dark_mode: z.union([z.literal(0), z.literal(1)]).optional(),\n delivery: deliverySchema.optional(),\n delivery_info: deliverySchema.optional(),\n discount: z.number().optional(),\n discount_display: stringOrNumberSchema.optional(),\n eligible_gateways: z.array(z.string()).optional(),\n environment: z.string().optional(),\n fee_breakdown: unknownRecordSchema.nullable().optional(),\n gateway: z.string().nullable(),\n gateway_data: unknownRecordSchema.nullable().optional(),\n gateway_eligibility: z.record(z.string(), gatewayEligibilityStateSchema).optional(),\n gateway_fee_previews: z.array(gatewayFeePreviewSchema).optional(),\n gateways_available: z.array(z.string()),\n license: z.union([unknownRecordSchema, z.literal(false)]).optional(),\n name: z.string().nullable(),\n paddle_token: z.string().nullable().optional(),\n paddle_transaction_id: z.unknown().optional(),\n payment_link_id: z.string().nullable().optional(),\n payment_method_overrides: z.array(paymentMethodOverrideSchema).optional(),\n payment_session_state: invoicePaymentSessionStateSchema.nullable().optional(),\n polling: pollingSchema,\n pricing_breakdown: pricingBreakdownSchema.nullable().optional(),\n product: z.array(\n publicInvoiceWireProductSchema.superRefine(requirePriceDisplayUnlessPayWhatYouWant),\n ).optional(),\n quantity: z.number().nullable(),\n rates_snapshot: z.record(z.string(), z.number()).optional(),\n remaining_amount: stringOrNumberSchema.nullable().optional(),\n selected_gateway: z.string().nullable().optional(),\n shop_checkout_ambient_color: z.string().nullable().optional(),\n shop_cloudflare_image_id: z.string().nullable(),\n shop_domain: z.string().nullable().optional(),\n shop_force_paypal_email_delivery: z.union([z.literal(0), z.literal(1)]).optional(),\n shop_image_name: z.string().nullable(),\n shop_image_storage: z.string().nullable().optional(),\n shop_payment_gateways_fees: z.array(unknownRecordSchema).optional(),\n shop_paypal_credit_card: z.union([z.literal(0), z.literal(1)]).optional(),\n shop_return_url: z.string().nullable().optional(),\n shop_slug: z.string().nullable().optional(),\n shop_terms_enabled: z.boolean().optional(),\n shop_terms_of_service: z.string().nullable().optional(),\n shop_terms_url: z.string().nullable().optional(),\n shop_privacy_policy_url: z.string().nullable().optional(),\n shop_refund_policy_url: z.string().nullable().optional(),\n shop_walletconnect_id: z.string().nullable().optional(),\n status: z.string().nullable(),\n status_history: z.array(statusHistoryEntrySchema).optional(),\n status_history_legacy: z.array(statusHistoryEntrySchema).optional(),\n status_history_raw: z.array(statusHistoryEntrySchema).optional(),\n stripe_publishable_key: z.string().nullable().optional(),\n stripe_user_id: z.string().nullable().optional(),\n subtotal: z.number().optional(),\n subtype: z.string().nullable().optional(),\n support: supportSchema.optional(),\n theme: z.string().optional(),\n tip_amount: stringOrNumberSchema.nullable().optional(),\n tip_amount_display: stringOrNumberSchema.nullable().optional(),\n tip_metadata: z.unknown().optional(),\n total: stringOrNumberSchema,\n total_conversions: unknownRecordSchema.optional(),\n total_display: stringOrNumberSchema,\n type: z.string().nullable(),\n underpayment: underpaymentSchema.nullable().optional(),\n underpayment_status: z.string().nullable().optional(),\n uniqid: z.string(),\n void_times: z.array(voidTimeSchema).optional(),\n\n // PUBLIC_INVOICE_FIELDS entries not exercised by the golden fixtures.\n addons: z.unknown().optional(),\n affiliate_data: z.unknown().optional(),\n affiliate_revenue_customer_id: z.string().nullable().optional(),\n bill_info: z.unknown().optional(),\n binance_checkout_url: z.string().nullable().optional(),\n binance_invoice_id: z.string().nullable().optional(),\n binance_qrcode: z.string().nullable().optional(),\n bundle_config: z.unknown().optional(),\n bundles: z.unknown().optional(),\n cashapp_cashtag: z.string().nullable().optional(),\n cashapp_note: z.string().nullable().optional(),\n cashapp_qrcode: z.string().nullable().optional(),\n created_at: z.string().optional(),\n crypto_address: z.string().nullable().optional(),\n crypto_amount: stringOrNumberSchema.optional(),\n crypto_confirmations_needed: z.number().nullable().optional(),\n crypto_exchange_rate: stringOrNumberSchema.nullable().optional(),\n crypto_received: stringOrNumberSchema.optional(),\n crypto_uri: z.string().nullable().optional(),\n developer_invoice: z.unknown().optional(),\n developer_return_url: z.string().nullable().optional(),\n developer_title: z.string().nullable().optional(),\n exchange_rate: stringOrNumberSchema.nullable().optional(),\n external_order_id: z.string().nullable().optional(),\n lex_order_id: z.string().nullable().optional(),\n lex_payment_method: z.string().nullable().optional(),\n paydash_payment_id: z.string().nullable().optional(),\n paypal_apm: z.string().nullable().optional(),\n paypal_email_delivery: z.boolean().optional(),\n paypal_fee: stringOrNumberSchema.nullable().optional(),\n paypal_order_id: z.string().nullable().optional(),\n paypal_payer_email: z.string().nullable().optional(),\n paypal_subscription_id: z.string().nullable().optional(),\n paypal_subscription_link: z.string().nullable().optional(),\n perfectmoney_id: z.string().nullable().optional(),\n product_addons: z.unknown().optional(),\n product_id: z.string().nullable().optional(),\n product_title: z.string().nullable().optional(),\n product_type: z.string().nullable().optional(),\n product_variants: z.unknown().optional(),\n recurring_billing_id: z.string().nullable().optional(),\n skrill_link: z.string().nullable().optional(),\n skrill_sid: z.string().nullable().optional(),\n status_details: z.unknown().optional(),\n stripe_apm: z.string().nullable().optional(),\n stripe_client_secret: z.string().nullable().optional(),\n stripe_id: z.string().nullable().optional(),\n stripe_price_id: z.string().nullable().optional(),\n subscription: z.unknown().optional(),\n subscription_id: z.string().nullable().optional(),\n sumup_id: z.string().nullable().optional(),\n telegram_stars_payment_link: z.string().nullable().optional(),\n telegram_stars_payment_note: z.string().nullable().optional(),\n updated_at: z.string().optional(),\n virtual_payments_id: z.string().nullable().optional(),\n void_details: z.unknown().optional(),\n}).catchall(z.unknown());\n\nexport type PublicInvoiceWire = z.infer<typeof publicInvoiceWireSchema>;\n\nexport const embedCheckoutProductWireSchema = publicInvoiceWireProductSchema.extend({\n available_addons: z.array(publicInvoiceWireAvailableAddonSchema).optional(),\n delivery_instructions: z.string().nullable().optional(),\n delivery_instructions_config: z.object({\n enabled: z.literal(true),\n required: z.boolean(),\n label: z.string(),\n placeholder: z.string().nullable().optional(),\n help_text: z.string().nullable().optional(),\n max_length: z.number(),\n }).nullable().optional(),\n delivery_instructions_label: z.string().nullable().optional(),\n image_url: z.string().nullable().optional(),\n redirectLink: z.string().nullable().optional(),\n redirectTime: z.number().nullable().optional(),\n serviceText: z.string().nullable().optional(),\n}).superRefine(requirePriceDisplayUnlessPayWhatYouWant);\n\nexport type EmbedCheckoutProductWire = z.infer<typeof embedCheckoutProductWireSchema>;\n\n/**\n * Invoice carried by the embed-start response.\n *\n * The public invoice contract validates the shared wire. These additions pin\n * fields that the checkout consumes directly and the legacy `products` alias\n * accepted by embedded clients.\n */\nexport const embedCheckoutInvoiceWireSchema = publicInvoiceWireSchema.extend({\n uniqid: z.string().uuid(),\n shop_id: z.union([z.string(), z.number()]).nullable(),\n customer_email: z.string().nullable(),\n checkout_style: checkoutStyleStateSchema.nullable().optional(),\n coupon_id: z.string().nullable().optional(),\n discount_breakdown: unknownRecordSchema.nullable().optional(),\n affiliate_code: z.string().nullable().optional(),\n country: z.string().nullable().optional(),\n paypal_email: z.string().nullable().optional(),\n pandabase_available_payment_methods: z.array(z.string()).optional(),\n payment_rescue: paymentRescueSchema.nullable().optional(),\n discord_integration: discordIntegrationStateSchema.nullable().optional(),\n payment_session_state: embedInvoicePaymentSessionStateSchema.nullable().optional(),\n shop_payment_gateways_fees: z.array(shopPaymentGatewayFeeSchema).optional(),\n product: z.array(embedCheckoutProductWireSchema).optional(),\n products: z.array(embedCheckoutProductWireSchema).optional(),\n rewards: invoiceRewardsSchema.nullable().optional(),\n}).superRefine((invoice, context) => {\n if (invoice.product === undefined && invoice.products === undefined) {\n context.addIssue({\n code: 'custom',\n message: 'Embed checkout invoice must include product or products.',\n path: ['product'],\n });\n }\n});\n\nexport type EmbedCheckoutInvoiceWire = z.infer<typeof embedCheckoutInvoiceWireSchema>;\n\n/** Critical runtime boundary for the public embed-start response. */\nexport const embedCheckoutStartWireSchema = z.object({\n data: z.object({\n invoice: embedCheckoutInvoiceWireSchema,\n invoice_url: z.string().nullable(),\n checkout_url: z.string().nullable(),\n selected_gateway: z.string().nullable(),\n session_started: z.boolean(),\n payment_session: embedPaymentSessionWireSchema.nullable(),\n completion_access_grant: z.string().nullable(),\n }).passthrough(),\n}).passthrough();\n\nexport type EmbedCheckoutStartWire = z.infer<typeof embedCheckoutStartWireSchema>;\n","/**\n * Catalog unit prices support mills (one thousandth of a currency unit).\n *\n * This is intentionally separate from invoice and payment totals. A unit can\n * cost $0.012, while the payable line total is still rounded to the currency's\n * minor unit after `unit price × quantity`.\n */\nexport const CATALOG_UNIT_PRICE_DECIMAL_PLACES = 3;\n\n/**\n * Payable line amounts and invoice totals remain cent amounts. This is a\n * separate boundary from catalog unit prices: multiply the mill-priced unit by\n * quantity first, then round the resulting line amount to this precision.\n */\nexport const PAYABLE_AMOUNT_DECIMAL_PLACES = 2;\n\nexport const CATALOG_UNIT_PRICE_FORMAT_OPTIONS = {\n maximumFractionDigits: CATALOG_UNIT_PRICE_DECIMAL_PLACES,\n} as const;\n\n/**\n * Browser-safe half-up rounding for non-negative payable amounts.\n *\n * The exponent shift avoids the common `1.005 * 100` binary-float trap and\n * mirrors the backend's decimal.js ROUND_HALF_UP policy. Negative values are\n * handled symmetrically so the helper remains safe for display calculations.\n */\nexport function roundPayableAmount(value: number): number {\n if (!Number.isFinite(value)) return value;\n\n const sign = value < 0 ? -1 : 1;\n const shifted = shiftDecimal(Math.abs(value), PAYABLE_AMOUNT_DECIMAL_PLACES);\n const rounded = Math.round(shifted);\n if (rounded === 0) return 0;\n return sign * shiftDecimal(rounded, -PAYABLE_AMOUNT_DECIMAL_PLACES);\n}\n\nfunction shiftDecimal(value: number, places: number): number {\n const [coefficient, currentExponent = '0'] = String(value).split('e');\n return Number(`${coefficient}e${Number(currentExponent) + places}`);\n}\n\nfunction countSignificantDecimalPlaces(value: string | number): number | null {\n const source = String(value).trim();\n const match = source.match(/^[-+]?(\\d+)(?:\\.(\\d*))?(?:e([-+]?\\d+))?$/i)\n ?? source.match(/^[-+]?\\.(\\d+)(?:e([-+]?\\d+))?$/i);\n if (!match) return null;\n\n const startsWithDecimalPoint = /^[-+]?\\./.test(source);\n const integerPart = startsWithDecimalPoint ? '0' : match[1];\n const fractionPart = startsWithDecimalPoint ? match[1] : (match[2] ?? '');\n const exponentText = startsWithDecimalPoint ? match[2] : match[3];\n const exponent = Number(exponentText ?? 0);\n if (!Number.isInteger(exponent)) return null;\n\n const digitsWithoutInsignificantZeros = `${integerPart}${fractionPart}`.replace(/0+$/, '');\n if (digitsWithoutInsignificantZeros.length === 0) return 0;\n\n const decimalPoint = integerPart.length + exponent;\n return Math.max(0, digitsWithoutInsignificantZeros.length - decimalPoint);\n}\n\nexport function hasCatalogUnitPricePrecision(value: string | number): boolean {\n const decimalPlaces = countSignificantDecimalPlaces(value);\n return decimalPlaces !== null && decimalPlaces <= CATALOG_UNIT_PRICE_DECIMAL_PLACES;\n}\n\nexport function getCatalogUnitPricePrecisionMessage(value: string | number): string {\n return `Price supports at most ${CATALOG_UNIT_PRICE_DECIMAL_PLACES} decimal places; received ${String(value)}.`;\n}\n","/**\n * @shoppex/contracts\n *\n * Shared TypeScript types generated from OpenAPI spec.\n * These types ensure type-safety between the Elysia API runtime and frontend apps.\n *\n * Usage:\n * import { paths, components } from '@shoppex/contracts/api-types';\n * import { createApiClient } from '@shoppex/contracts';\n */\n\nimport createClient from 'openapi-fetch';\nimport type { paths } from './api-types.js';\n\n// Re-export generated types\nexport * from './api-types.js';\nexport * from './navigation.js';\nexport * from './observability.js';\nexport * from './email-marketing.js';\nexport * from './payment-gateways.js';\nexport * from './platform-billing.js';\nexport * from './style-center.js';\nexport * from './style-center/presets.js';\nexport * from './storefront-addons.js';\nexport * from './api-error-codes.js';\nexport * from './merchant-safe-errors.js';\nexport * from './manual-gateway-template.js';\nexport * from './external-payment-adapter.js';\nexport * from './redirect-link-template.js';\nexport * from './checkout-api.js';\nexport * from './invoice-wire.js';\nexport * from './developer-webhook.js';\nexport * from './catalog-unit-price.js';\nexport * from './customer-portal-wire.js';\nexport * from './type-assertions.js';\nexport * from './theme-ai-handoff.js';\n\n/**\n * Create a type-safe API client\n *\n * @example\n * const client = createApiClient('https://api.shoppex.io/v1');\n *\n * // Fully typed request and response\n * const { data, error } = await client.GET('/products', {\n * params: { query: { page: 1, limit: 25 } }\n * });\n */\nexport function createApiClient(baseUrl: string, token?: string) {\n return createClient<paths>({\n baseUrl,\n headers: token ? { Authorization: `Bearer ${token}` } : undefined,\n });\n}\n\n// Common response types used across the app\nexport interface ApiResponse<T> {\n status: number;\n data: T | null;\n error: string | null;\n message: string | null;\n env: string;\n}\n\nexport interface PaginatedResponse<T> {\n data: T[];\n meta: {\n total: number;\n page: number;\n perPage: number;\n totalPages: number;\n };\n}\n\nexport interface ApiError {\n status: number;\n error: string;\n message: string;\n}\n","/**\n * Typed OpenAPI client factory.\n *\n * Surfaces the generated `createApiClient` from `@shoppex/contracts` with the\n * SDK's configured `apiBaseUrl`. This lets consumers of `@shoppexio/storefront`\n * call any public Dev API endpoint with full end-to-end types without\n * rebuilding a client from scratch.\n *\n * Prefer the high-level modules (`shoppex.getProducts()` etc.) for common\n * read flows — they handle caching, pagination defaults, and storefront\n * scoping. Drop down to `shoppex.client()` only when you need an endpoint\n * the high-level API does not cover yet.\n */\n\nimport { createApiClient } from '@shoppex/contracts';\nimport { DEFAULT_API_BASE_URL, getConfig } from './config';\n\ntype ApiClient = ReturnType<typeof createApiClient>;\n\nlet cachedClient: ApiClient | null = null;\nlet cachedBaseUrl: string | null = null;\n\n/**\n * Return a typed OpenAPI client bound to the SDK's configured API base URL.\n * The client is cached per base URL and recreated when the SDK is re-initialized\n * against a different host.\n */\nexport function getTypedClient(token?: string): ApiClient {\n const config = getConfig();\n const baseUrl = config.apiBaseUrl ?? DEFAULT_API_BASE_URL;\n\n if (cachedClient && cachedBaseUrl === baseUrl && !token) {\n return cachedClient;\n }\n\n const client = createApiClient(baseUrl, token);\n\n if (!token) {\n cachedClient = client;\n cachedBaseUrl = baseUrl;\n }\n\n return client;\n}\n\n/**\n * Reset the cached client. Called when the SDK is re-initialized so that a new\n * `apiBaseUrl` takes effect immediately on the next `client()` call.\n */\nexport function resetTypedClient(): void {\n cachedClient = null;\n cachedBaseUrl = null;\n}\n","/**\n * SDK Configuration Management\n */\n\nimport type { ShoppexConfig, ShoppexInitOptions } from '../types';\nimport { clearCache } from './cache';\nimport { NotInitializedError } from './errors';\nimport { resetTypedClient } from './typed-client';\n\nexport const DEFAULT_API_BASE_URL = 'https://api.shoppex.io';\n\nlet currentConfig: ShoppexConfig | null = null;\nlet cachedShopId: string | null = null;\n\nexport const DEFAULT_CHECKOUT_BASE_URL = 'https://checkout.shoppex.io';\n\nexport function initConfig(\n storeSlug: string,\n options?: ShoppexInitOptions\n): ShoppexConfig {\n const normalizedShopId = options?.shopId?.trim();\n\n // Reset cached shop id on every init to avoid cross-store leakage\n // when the SDK is re-initialized with a different slug.\n cachedShopId = normalizedShopId ? normalizedShopId : null;\n\n const previousLocale = currentConfig?.locale;\n currentConfig = {\n storeSlug,\n locale: options?.locale,\n currency: options?.currency,\n apiBaseUrl: options?.apiBaseUrl ?? DEFAULT_API_BASE_URL,\n checkoutBaseUrl: options?.checkoutBaseUrl ?? DEFAULT_CHECKOUT_BASE_URL,\n };\n // Response cache keys are locale-agnostic (products:slug, product:id, …) —\n // a locale switch across re-inits must not serve the previous locale's\n // payloads for up to the cache TTL (Codex P2).\n if (previousLocale !== currentConfig.locale) {\n clearCache();\n }\n resetTypedClient();\n return currentConfig;\n}\n\nexport function getConfig(): ShoppexConfig {\n if (!currentConfig) {\n throw new NotInitializedError();\n }\n return currentConfig;\n}\n\nexport function isInitialized(): boolean {\n return currentConfig !== null;\n}\n\nexport function resetConfig(): void {\n currentConfig = null;\n cachedShopId = null;\n resetTypedClient();\n}\n\nexport function setShopId(shopId: string): void {\n cachedShopId = shopId;\n}\n\nexport function getShopId(): string | null {\n return cachedShopId;\n}\n","export interface StorefrontCustomField {\n name: string;\n type: string;\n required: boolean;\n defaultValue: string;\n placeholder: string;\n regex?: string;\n}\n\nfunction parseCustomFieldsSource(raw: unknown): unknown[] {\n if (Array.isArray(raw)) return raw;\n\n if (typeof raw === 'string') {\n try {\n const parsed = JSON.parse(raw) as unknown;\n if (Array.isArray(parsed)) return parsed;\n if (parsed && typeof parsed === 'object') {\n const fields = (parsed as { custom_fields?: unknown[]; customFields?: unknown[] }).custom_fields\n ?? (parsed as { custom_fields?: unknown[]; customFields?: unknown[] }).customFields;\n return Array.isArray(fields) ? fields : [];\n }\n } catch {\n return [];\n }\n\n return [];\n }\n\n if (raw && typeof raw === 'object') {\n const fields = (raw as { custom_fields?: unknown[]; customFields?: unknown[] }).custom_fields\n ?? (raw as { custom_fields?: unknown[]; customFields?: unknown[] }).customFields;\n return Array.isArray(fields) ? fields : [];\n }\n\n return [];\n}\n\nexport function normalizeStorefrontCustomFields(raw: unknown): StorefrontCustomField[] {\n return parseCustomFieldsSource(raw)\n .filter((field): field is Record<string, unknown> => !!field && typeof field === 'object' && !Array.isArray(field))\n .map((field) => {\n const rawType = typeof field.type === 'string' ? field.type.trim().toLowerCase() : 'text';\n const type = rawType.length > 0 ? rawType : 'text';\n const defaultValue = [\n field.default_value,\n field.default,\n field.value,\n ].find((candidate) => typeof candidate === 'string' && candidate.trim().length > 0);\n\n return {\n name: typeof field.name === 'string' ? field.name.trim() : '',\n type,\n required: field.required === true || field.required === 'true' || field.required === 1 || field.required === '1',\n defaultValue: typeof defaultValue === 'string' ? defaultValue : '',\n placeholder: typeof field.placeholder === 'string' ? field.placeholder : '',\n regex: typeof field.regex === 'string' ? field.regex : undefined,\n };\n })\n .filter((field) => field.name.length > 0 && field.type !== 'hidden');\n}\n\nexport function isStorefrontCheckboxCustomFieldValueChecked(value: string | undefined): boolean {\n const normalized = value?.trim().toLowerCase() ?? '';\n return normalized === 'true' || normalized === '1' || normalized === 'yes' || normalized === 'on';\n}\n\nexport function validateStorefrontCustomFieldValue(field: StorefrontCustomField, value: string): string | null {\n if (field.type === 'checkbox') {\n if (field.required && !isStorefrontCheckboxCustomFieldValueChecked(value)) {\n return `${field.name} is required.`;\n }\n return null;\n }\n\n const normalized = value.trim();\n if (field.required && !normalized) {\n return `${field.name} is required.`;\n }\n\n if (field.regex && normalized) {\n try {\n const pattern = new RegExp(field.regex);\n if (!pattern.test(normalized)) {\n return `${field.name} has an invalid format.`;\n }\n } catch {\n return null;\n }\n }\n\n return null;\n}\n\nexport function buildStorefrontCustomFieldPayload(\n fields: StorefrontCustomField[],\n values: Record<string, string>,\n): Record<string, string> {\n const nextValues: Record<string, string> = {};\n\n fields.forEach((field) => {\n const rawValue = values[field.name] ?? field.defaultValue ?? '';\n\n if (field.type === 'checkbox') {\n if (isStorefrontCheckboxCustomFieldValueChecked(rawValue)) {\n nextValues[field.name] = 'true';\n }\n return;\n }\n\n const normalized = rawValue.trim();\n if (normalized.length > 0) {\n nextValues[field.name] = normalized;\n }\n });\n\n return nextValues;\n}\n","import type { Product, PriceVariant, ProductVariant } from '../types/index.js';\n\ntype VariantLike =\n | Pick<ProductVariant, 'stock' | 'orderable' | 'supplier_backed'>\n | Pick<PriceVariant, 'stock' | 'orderable' | 'supplier_backed'>;\n\ntype ProductLike = Pick<Product, 'type' | 'stock' | 'orderable' | 'supplier_backed' | 'on_hold' | 'price_variants' | 'variants'> & {\n onHold?: boolean | number | string | null;\n is_on_hold?: boolean | number | string | null;\n isOnHold?: boolean | number | string | null;\n};\n\n/** The sentinel every predicate in this module already treats as \"unbounded\". */\nconst UNLIMITED_STOCK = -1;\n\n/**\n * Dynamic Delivery (S8): fold `orderable` into the stock value.\n *\n * `orderable` is the backend's authoritative buyability predicate — `local stock\n * covers one unit OR an eligible supplier source can fulfil the line` — and it is\n * exactly what the order-time gates apply. A supplier-backed row holds NO local\n * stock by design, so gating the buyer on `stock` alone renders it \"out of stock\"\n * and the purchase can never happen.\n *\n * Rather than introduce a fourth availability state, a row that is orderable\n * without local units is normalised to the unlimited sentinel — the same value an\n * unlimited row already carries. Every downstream badge, quantity cap, variant\n * gate and CTA then behaves as it already does for unlimited stock.\n *\n * `orderable` alone cannot decide how far to widen: it is also `true` for an\n * ordinary locally-stocked row, whose finite counter must stay finite. That is what\n * `supplier_backed` settles. A supplier-backed row is fulfilled by the supplier\n * purchase and the completion excludes it from the local decrement, so any residual\n * local units bound NOTHING — its cap is unlimited even at `stock: 1`. A row that is\n * NOT supplier-backed keeps its exact finite counter, and only widens from 0 (the\n * product-wide mapping case, where the backend folded the mapping into `orderable`\n * and left `stock` at 0).\n *\n * When `orderable` is absent (an older payload or a cached response shape that\n * predates the field) the raw value is returned UNCHANGED, and an absent\n * `supplier_backed` widens nothing beyond what the previous rule already did. That\n * is the only permitted fallback direction: a missing field must never flip a\n * genuinely sold-out row into a buyable one, nor a finite counter into unlimited.\n */\nfunction applyOrderable(stock: number, orderable: unknown, supplierBacked?: unknown): number {\n if (orderable !== true) {\n return stock;\n }\n // Supplier-backed: local units do not bound the line, at any stock value.\n if (supplierBacked === true) {\n return UNLIMITED_STOCK;\n }\n // Already buyable or already unbounded — nothing to widen.\n if (stock !== 0) {\n return stock;\n }\n return UNLIMITED_STOCK;\n}\n\nfunction normalizeStockValue(value: unknown): number | null {\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n return null;\n }\n\n return Math.trunc(value);\n}\n\nfunction isTruthyFlag(value: unknown): boolean {\n if (value === true) return true;\n if (typeof value === 'number' && Number.isFinite(value)) return value !== 0;\n if (typeof value === 'string') {\n const normalized = value.trim().toLowerCase();\n return normalized === 'true' || normalized === '1';\n }\n return false;\n}\n\nfunction isProductOnHold(product: ProductLike | null | undefined): boolean {\n if (!product) return false;\n return isTruthyFlag(product.on_hold)\n || isTruthyFlag(product.onHold)\n || isTruthyFlag(product.is_on_hold)\n || isTruthyFlag(product.isOnHold);\n}\n\nfunction collectVariantStocks(product: ProductLike): number[] {\n const priceVariants = Array.isArray(product.price_variants) ? product.price_variants : [];\n if (priceVariants.length > 0) {\n return priceVariants.map((variant) => resolveVariantStockValue(variant));\n }\n\n const legacyVariants = Array.isArray(product.variants) ? product.variants : [];\n\n return legacyVariants.map((variant) => resolveVariantStockValue(variant));\n}\n\nexport function resolveVariantStockValue(variant: VariantLike | null | undefined): number {\n const normalized = normalizeStockValue(variant?.stock);\n return applyOrderable(normalized ?? UNLIMITED_STOCK, variant?.orderable, variant?.supplier_backed);\n}\n\nexport function resolveDisplayStock(product: ProductLike | null | undefined): number {\n if (!product) {\n return UNLIMITED_STOCK;\n }\n\n if (typeof product.type === 'string' && product.type.toUpperCase() === 'SERIALS') {\n return applyOrderable(\n normalizeStockValue(product.stock) ?? UNLIMITED_STOCK,\n product.orderable,\n product.supplier_backed,\n );\n }\n\n const variantStocks = collectVariantStocks(product);\n if (variantStocks.length > 0) {\n // A single unbounded option (including a supplier-backed one, already folded\n // into the sentinel above) makes the product unbounded — summing finite\n // siblings would understate it.\n if (variantStocks.some((stock) => stock < 0)) {\n return UNLIMITED_STOCK;\n }\n\n const total = variantStocks.reduce((sum, stock) => sum + Math.max(stock, 0), 0);\n // The product-level flag still applies: the backend folds a product-wide\n // supplier mapping into it, and that mapping backs options with no local units.\n return applyOrderable(total, product.orderable, product.supplier_backed);\n }\n\n return applyOrderable(\n normalizeStockValue(product.stock) ?? UNLIMITED_STOCK,\n product.orderable,\n product.supplier_backed,\n );\n}\n\nexport function isProductOutOfStock(product: ProductLike | null | undefined): boolean {\n // `on_hold` is a merchant pause, not a supply signal — it forces unavailable\n // BEFORE any `orderable` widening can apply.\n if (isProductOnHold(product)) return true;\n return resolveDisplayStock(product) === 0;\n}\n\nexport function isProductInStock(product: ProductLike | null | undefined): boolean {\n return !isProductOutOfStock(product);\n}\n\nexport function isVariantOutOfStock(variant: VariantLike | null | undefined): boolean {\n return resolveVariantStockValue(variant) === 0;\n}\n","import type { Product, ProductGroup } from '../types/index.js';\n\nexport function buildStorefrontProductLookup(products: Product[] = []): Map<string, Product> {\n const lookup = new Map<string, Product>();\n for (const product of products) {\n if (!product?.uniqid || lookup.has(product.uniqid)) continue;\n lookup.set(product.uniqid, product);\n }\n return lookup;\n}\n\n// Groups reference their products by uniqid; the objects live once in `products`.\nexport function getStorefrontGroupProducts(\n group: ProductGroup,\n productsOrLookup: Product[] | Map<string, Product> = [],\n): Product[] {\n const lookup = productsOrLookup instanceof Map\n ? productsOrLookup\n : buildStorefrontProductLookup(productsOrLookup);\n return (group.product_uniqids ?? []).flatMap((uniqid) => {\n const product = lookup.get(uniqid);\n return product ? [product] : [];\n });\n}\n\nexport function getMergedStorefrontProducts(products: Product[] = []): Product[] {\n return Array.from(buildStorefrontProductLookup(products).values());\n}\n","import type { Product, ProductGroup } from '../types/index.js';\nimport {\n buildStorefrontProductLookup,\n getMergedStorefrontProducts,\n getStorefrontGroupProducts,\n} from './storefront-catalog.js';\nimport { isProductInStock } from './storefront-stock.js';\n\nexport interface StorefrontSearchFilterOptions {\n hideOutOfStock?: boolean;\n maxResults?: number;\n}\n\nexport type StorefrontCatalogSearchItem =\n | { type: 'product'; product: Product }\n // Groups only carry `product_uniqids`; `products` holds the resolved product\n // objects (in group order) so consumers never re-resolve references themselves.\n | { type: 'group'; group: ProductGroup; products: Product[] };\n\nexport function stripHtmlFromText(value: string | null | undefined): string {\n if (!value) return '';\n return value.replace(/<[^>]*>/g, ' ').replace(/\\s+/g, ' ').trim();\n}\n\nexport function normalizeSearchQuery(query: string): string {\n return query.trim().toLowerCase();\n}\n\nfunction pushSearchPart(parts: string[], value: string | null | undefined): void {\n const normalized = stripHtmlFromText(value).toLowerCase();\n if (normalized) {\n parts.push(normalized);\n }\n}\n\nexport function collectProductSearchHaystack(product: Product): string[] {\n const parts: string[] = [];\n\n pushSearchPart(parts, product.title);\n pushSearchPart(parts, product.slug ?? undefined);\n pushSearchPart(parts, product.description);\n\n for (const highlight of product.product_highlights ?? []) {\n pushSearchPart(parts, highlight);\n }\n\n for (const variant of product.variants ?? []) {\n pushSearchPart(parts, variant.title);\n }\n\n for (const variant of product.price_variants ?? []) {\n pushSearchPart(parts, variant.title ?? variant.label);\n }\n\n return parts;\n}\n\nexport function productMatchesSearchQuery(product: Product, query: string): boolean {\n const normalized = normalizeSearchQuery(query);\n if (!normalized) return false;\n\n return collectProductSearchHaystack(product).some((haystack) => haystack.includes(normalized));\n}\n\nexport function groupMatchesSearchQuery(group: ProductGroup, query: string): boolean {\n const normalized = normalizeSearchQuery(query);\n if (!normalized) return false;\n\n const title = stripHtmlFromText(group.title).toLowerCase();\n const slug = stripHtmlFromText(group.slug ?? group.name ?? undefined).toLowerCase();\n const description = stripHtmlFromText(group.description).toLowerCase();\n\n return title.includes(normalized)\n || slug.includes(normalized)\n || description.includes(normalized);\n}\n\nexport function filterProductsBySearchQuery(\n products: Product[],\n query: string,\n options?: StorefrontSearchFilterOptions,\n): Product[] {\n const normalized = normalizeSearchQuery(query);\n if (!normalized) return [];\n\n let results = products.filter((product) => productMatchesSearchQuery(product, normalized));\n\n if (options?.hideOutOfStock) {\n results = results.filter((product) => isProductInStock(product));\n }\n\n if (options?.maxResults != null) {\n return results.slice(0, options.maxResults);\n }\n\n return results;\n}\n\nfunction groupHasVisibleProducts(\n groupProducts: Product[],\n hideOutOfStock: boolean,\n): boolean {\n if (groupProducts.length === 0) return false;\n if (!hideOutOfStock) return true;\n return groupProducts.some((product) => isProductInStock(product));\n}\n\nexport function searchMergedStorefrontCatalogItems(\n products: Product[],\n groups: ProductGroup[],\n query: string,\n options?: StorefrontSearchFilterOptions,\n): StorefrontCatalogSearchItem[] {\n const normalized = normalizeSearchQuery(query);\n if (!normalized) return [];\n\n const hideOutOfStock = options?.hideOutOfStock === true;\n const coveredProductIds = new Set<string>();\n const coveredGroupIds = new Set<string>();\n const results: StorefrontCatalogSearchItem[] = [];\n // Build the uniqid lookup once per search run; groups resolve against it.\n const lookup = buildStorefrontProductLookup(products);\n\n for (const group of groups) {\n const groupKey = group.uniqid ?? group.id;\n if (!groupKey || coveredGroupIds.has(groupKey)) continue;\n if (!groupMatchesSearchQuery(group, normalized)) continue;\n\n const groupProducts = getStorefrontGroupProducts(group, lookup);\n if (!groupHasVisibleProducts(groupProducts, hideOutOfStock)) continue;\n\n coveredGroupIds.add(groupKey);\n for (const product of groupProducts) {\n if (product?.uniqid) coveredProductIds.add(product.uniqid);\n }\n results.push({ type: 'group', group, products: groupProducts });\n }\n\n const merged = getMergedStorefrontProducts(products);\n for (const product of merged) {\n if (!product?.uniqid || coveredProductIds.has(product.uniqid)) continue;\n if (!productMatchesSearchQuery(product, normalized)) continue;\n if (hideOutOfStock && !isProductInStock(product)) continue;\n coveredProductIds.add(product.uniqid);\n results.push({ type: 'product', product });\n }\n\n if (options?.maxResults != null) {\n return results.slice(0, options.maxResults);\n }\n\n return results;\n}\n\nexport function searchMergedStorefrontCatalog(\n products: Product[],\n groups: ProductGroup[],\n query: string,\n options?: StorefrontSearchFilterOptions,\n): Product[] {\n const items = searchMergedStorefrontCatalogItems(products, groups, query, options);\n const matchedIds = new Set<string>();\n const results: Product[] = [];\n\n const addProduct = (product: Product) => {\n if (!product?.uniqid || matchedIds.has(product.uniqid)) return;\n if (options?.hideOutOfStock && !isProductInStock(product)) return;\n matchedIds.add(product.uniqid);\n results.push(product);\n };\n\n for (const item of items) {\n if (item.type === 'product') {\n addProduct(item.product);\n continue;\n }\n\n for (const product of item.products) {\n addProduct(product);\n }\n }\n\n if (options?.maxResults != null) {\n return results.slice(0, options.maxResults);\n }\n\n return results;\n}\n","import { DEFAULT_API_BASE_URL } from '../core/config';\n\nexport type StorefrontContactTicketInput = {\n shopSlug: string;\n email: string;\n message: string;\n title?: string;\n name?: string;\n invoiceId?: string;\n apiBaseUrl?: string;\n};\n\nexport type StorefrontContactTicketResult = {\n uniqid: string;\n};\n\nfunction isLocalDevHost(host: string): boolean {\n if (host === 'localhost' || host === '127.0.0.1' || host === '::1' || host.endsWith('.localhost')) {\n return true;\n }\n if (/^10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/.test(host)) {\n return true;\n }\n if (/^192\\.168\\.\\d{1,3}\\.\\d{1,3}$/.test(host)) {\n return true;\n }\n const private172 = host.match(/^172\\.(\\d{1,2})\\.\\d{1,3}\\.\\d{1,3}$/);\n if (private172) {\n const octet = Number(private172[1]);\n return octet >= 16 && octet <= 31;\n }\n return false;\n}\n\nexport function resolveStorefrontApiBaseUrl(options?: {\n apiBaseUrl?: string;\n hostname?: string;\n}): string {\n if (options?.apiBaseUrl?.trim()) {\n return options.apiBaseUrl.replace(/\\/+$/, '');\n }\n\n const hostname = options?.hostname\n ?? (typeof window !== 'undefined' ? window.location.hostname : '');\n\n if (hostname && !isLocalDevHost(hostname)) {\n return DEFAULT_API_BASE_URL;\n }\n\n // Edge/njk commerce is a classic IIFE (not an ES module) — import.meta is a syntax error there.\n // Storefront bootstrap sets window.apiBaseUrl; Vite/React callers may pass options.apiBaseUrl.\n if (typeof window !== 'undefined') {\n const bootstrapBase = (window as { apiBaseUrl?: unknown }).apiBaseUrl;\n if (typeof bootstrapBase === 'string' && bootstrapBase.trim()) {\n return bootstrapBase.replace(/\\/+$/, '');\n }\n }\n\n return 'http://localhost:3001'.replace(/\\/+$/, '');\n}\n\nexport function buildStorefrontContactMessage(input: {\n name?: string;\n message: string;\n maxLength?: number;\n}): string {\n const customerName = input.name?.trim() ?? '';\n const baseMessage = input.message.trim();\n const fullMessage = `${customerName ? `Name: ${customerName}\\n\\n` : ''}${baseMessage}`;\n const maxLength = input.maxLength ?? 2000;\n return fullMessage.slice(0, maxLength);\n}\n\nexport async function submitStorefrontContactTicket(\n input: StorefrontContactTicketInput,\n): Promise<StorefrontContactTicketResult> {\n const shopSlug = input.shopSlug.trim();\n if (!shopSlug) {\n throw new Error('Store data is not ready yet. Please try again in a moment.');\n }\n\n const normalizedEmail = input.email.trim().toLowerCase();\n const subject = input.title?.trim() ?? '';\n const title = subject.length >= 2 ? subject.slice(0, 30) : 'Contact Request';\n const message = buildStorefrontContactMessage({\n name: input.name,\n message: input.message,\n });\n const invoiceId = input.invoiceId?.trim() || undefined;\n const apiBaseUrl = resolveStorefrontApiBaseUrl({ apiBaseUrl: input.apiBaseUrl });\n\n const response = await fetch(\n `${apiBaseUrl}/v1/storefront/shops/name/${encodeURIComponent(shopSlug)}/tickets`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n },\n body: JSON.stringify({\n email: normalizedEmail,\n title,\n message,\n ...(invoiceId ? { invoice_id: invoiceId } : {}),\n }),\n },\n );\n\n const payload = await response.json().catch(() => null) as {\n message?: string;\n error?: string;\n data?: { uniqid?: string };\n } | null;\n\n if (!response.ok) {\n throw new Error(payload?.message || payload?.error || 'Failed to send your message.');\n }\n\n const uniqid = payload?.data?.uniqid;\n if (!uniqid) {\n throw new Error('Ticket created, but the response was incomplete.');\n }\n\n return { uniqid };\n}\n\nexport type StorefrontSocialLinks = {\n discord?: string | null;\n telegram?: string | null;\n};\n\nexport function resolveStorefrontSocialLinks(store: {\n discord_link?: string | null;\n telegram_link?: string | null;\n social?: Record<string, string | null | undefined> | null;\n} | null | undefined): StorefrontSocialLinks {\n return {\n discord: store?.discord_link ?? store?.social?.discord ?? null,\n telegram: store?.telegram_link ?? store?.social?.telegram ?? null,\n };\n}\n","const PARAM_PATTERN = /:([A-Za-z0-9_]+)/g;\n\nexport function buildEndpoint(\n template: string,\n params: Record<string, string | number | null | undefined>\n): string {\n return template.replace(PARAM_PATTERN, (_, key: string) => {\n const rawValue = params[key];\n if (rawValue === null || rawValue === undefined) {\n throw new Error(`Missing endpoint param: ${key}`);\n }\n\n const value = String(rawValue).trim();\n if (!value) {\n throw new Error(`Endpoint param \"${key}\" must not be empty`);\n }\n\n return encodeURIComponent(value);\n });\n}\n","/**\n * localStorage Wrapper\n *\n * Handles localStorage access with error handling for\n * environments where localStorage is not available.\n */\n\nconst STORAGE_PREFIX = 'shoppex_';\n\nfunction getKey(key: string): string {\n return `${STORAGE_PREFIX}${key}`;\n}\n\nexport function getItem<T>(key: string): T | null {\n try {\n const item = localStorage.getItem(getKey(key));\n if (!item) return null;\n return JSON.parse(item) as T;\n } catch {\n return null;\n }\n}\n\nexport function setItem<T>(key: string, value: T): void {\n try {\n localStorage.setItem(getKey(key), JSON.stringify(value));\n } catch {\n console.warn('[shoppex] Failed to save to localStorage');\n }\n}\n\nexport function removeItem(key: string): void {\n try {\n localStorage.removeItem(getKey(key));\n } catch {\n // Ignore errors\n }\n}\n","import { getConfig, getShopId, isInitialized } from './config';\nimport { buildEndpoint } from './endpoint';\nimport { getItem, setItem } from '../utils/storage';\n\nconst CONNECTION_ID_STORAGE_PREFIX = 'presence_connection_';\nconst CLIENT_ERROR_DEDUPE_WINDOW_MS = 15_000;\n\ntype VisibilityStateValue = 'hidden' | 'visible' | 'prerender' | 'unloaded';\ntype RequestMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';\n\nexport interface StorefrontClientErrorPayload {\n endpoint: string;\n method: RequestMethod;\n message: string;\n statusCode?: number;\n source?: 'sdk';\n phase?: 'request';\n attemptCount?: number;\n responseReceived?: boolean;\n pageUrl?: string;\n requestUrl?: string;\n online?: boolean;\n visibilityState?: VisibilityStateValue;\n}\n\nfunction createPresenceConnectionId(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n }\n return `spx_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;\n}\n\nexport function getStorefrontConnectionId(storeSlug: string): string | null {\n if (typeof window === 'undefined') return null;\n\n const storageKey = `${CONNECTION_ID_STORAGE_PREFIX}${storeSlug}`;\n const existing = getItem<string>(storageKey);\n if (existing && existing.trim()) {\n return existing;\n }\n\n const nextId = createPresenceConnectionId();\n setItem(storageKey, nextId);\n return nextId;\n}\n\nfunction getRecentClientErrorKey(payload: StorefrontClientErrorPayload): string {\n return [\n payload.method,\n payload.endpoint,\n payload.statusCode ?? 'none',\n payload.message.trim().toLowerCase(),\n payload.responseReceived ? 'response' : 'no-response',\n ].join('|');\n}\n\nfunction shouldSkipDuplicateClientError(payload: StorefrontClientErrorPayload): boolean {\n const dedupeKey = `client_error_${getRecentClientErrorKey(payload)}`;\n const now = Date.now();\n const lastSeenAt = getItem<number>(dedupeKey);\n if (typeof lastSeenAt === 'number' && now - lastSeenAt < CLIENT_ERROR_DEDUPE_WINDOW_MS) {\n return true;\n }\n\n setItem(dedupeKey, now);\n return false;\n}\n\nexport async function reportStorefrontClientError(payload: StorefrontClientErrorPayload): Promise<void> {\n if (!isInitialized()) return;\n if (typeof window === 'undefined') return;\n if (shouldSkipDuplicateClientError(payload)) return;\n\n const config = getConfig();\n const shopId = getShopId();\n const endpoint = shopId\n ? buildEndpoint('/v1/storefront/shops/id/:id/ping', { id: shopId })\n : buildEndpoint('/v1/storefront/shops/:storeSlug/ping', { storeSlug: config.storeSlug });\n const body = JSON.stringify({\n event_type: 'client_error',\n referer: document.referrer || undefined,\n connection_id: getStorefrontConnectionId(config.storeSlug) ?? undefined,\n client_error: {\n source: payload.source ?? 'sdk',\n phase: payload.phase ?? 'request',\n endpoint: payload.endpoint,\n method: payload.method,\n message: payload.message,\n status_code: payload.statusCode,\n attempt_count: payload.attemptCount,\n response_received: payload.responseReceived ?? false,\n page_url: payload.pageUrl ?? window.location.href,\n request_url: payload.requestUrl,\n online: payload.online ?? (typeof navigator !== 'undefined' ? navigator.onLine : undefined),\n visibility_state:\n payload.visibilityState ??\n (typeof document !== 'undefined'\n ? (document.visibilityState as VisibilityStateValue)\n : undefined),\n },\n });\n\n const targetUrl = `${config.apiBaseUrl}${endpoint}`;\n\n try {\n if (typeof navigator !== 'undefined' && typeof navigator.sendBeacon === 'function') {\n const beaconBody = new Blob([body], { type: 'application/json' });\n if (navigator.sendBeacon(targetUrl, beaconBody)) {\n return;\n }\n }\n\n await fetch(targetUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body,\n keepalive: true,\n });\n } catch {\n // Telemetry must never break storefront usage.\n }\n}\n","/**\n * HTTP Client for SDK\n *\n * IMPORTANT: No credentials! SDK runs on external domains,\n * and CORS with wildcard origin doesn't allow credentials.\n * All endpoints are public storefront endpoints.\n */\n\nimport type { ApiChallenge, ApiResponse, SDKResponse } from '../types';\nimport { getConfig, isInitialized } from './config';\nimport { ApiError, NetworkError, ShoppexError } from './errors';\nimport { getOrFetch, type CacheOptions } from './cache';\nimport { reportStorefrontClientError } from './telemetry';\n\nconst DEFAULT_TIMEOUT = 10000;\nconst MAX_RETRIES = 2;\n\ninterface RequestOptions {\n method?: 'GET' | 'POST' | 'PUT' | 'DELETE';\n body?: unknown;\n timeout?: number;\n retries?: number;\n baseUrl?: string;\n headers?: Record<string, string>;\n cache?: (CacheOptions & { key?: string }) | false;\n}\n\ninterface ParsedResponsePayload {\n data: unknown | null;\n rawText: string | null;\n}\n\ninterface FailureInfo {\n message: string;\n statusCode?: number;\n isTransport: boolean;\n responseReceived: boolean;\n responseDefinitive: boolean;\n challenge?: ApiChallenge;\n /** The server's `error_code`, when the failure was a named refusal. */\n code?: string;\n errorParams?: Record<string, unknown>;\n}\n\nasync function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport async function request<T>(\n endpoint: string,\n options: RequestOptions = {}\n): Promise<SDKResponse<T>> {\n const config = options.baseUrl ? null : getConfig();\n // The locale travels with EVERY request of an initialized SDK — a baseUrl\n // override (e.g. resolveStoreByDomain) must not silently drop it back to\n // Accept-Language negotiation (Codex P2).\n const localeConfig = config ?? (isInitialized() ? getConfig() : null);\n const {\n method = 'GET',\n body,\n timeout = DEFAULT_TIMEOUT,\n retries,\n baseUrl,\n headers: requestHeaders,\n cache,\n } = options;\n const retryCount =\n retries ?? (method === 'GET' ? MAX_RETRIES : 0);\n\n const apiBaseUrl = baseUrl ?? config?.apiBaseUrl ?? '';\n const url = `${apiBaseUrl}${endpoint}`;\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n ...requestHeaders,\n };\n // Explicit request locale (ADR-0055): without it the backend would fall\n // back to Accept-Language, detaching catalog content from the page locale.\n if (typeof localeConfig?.locale === 'string' && localeConfig.locale.trim()) {\n headers['x-shoppex-locale'] = localeConfig.locale.trim();\n }\n\n let lastFailure: FailureInfo | null = null;\n\n const executeRequest = async (): Promise<SDKResponse<T>> => {\n for (let attempt = 0; attempt <= retryCount; attempt++) {\n let responseReceived = false;\n let responseDefinitive = false;\n let responseChallenge: ApiChallenge | undefined;\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n const response = await fetch(url, {\n method,\n headers,\n body: body ? JSON.stringify(body) : undefined,\n signal: controller.signal,\n });\n responseReceived = true;\n\n clearTimeout(timeoutId);\n\n const payload = await parseResponsePayload(response);\n responseChallenge = readResponseChallenge(payload.data);\n\n if (!response.ok) {\n responseDefinitive = isDefinitiveHttpRefusal(payload.data)\n && response.status >= 400\n && response.status < 500\n && response.status !== 408;\n const fallbackHttpMessage = response.statusText\n ? `HTTP ${response.status}: ${response.statusText}`\n : `HTTP ${response.status}`;\n const message =\n (payload.data && typeof payload.data === 'object' && 'error' in payload.data && typeof payload.data.error === 'string'\n ? payload.data.error\n : null) ??\n (payload.data && typeof payload.data === 'object' && 'message' in payload.data && typeof payload.data.message === 'string'\n ? payload.data.message\n : null) ??\n payload.rawText ??\n fallbackHttpMessage;\n\n // A named server refusal keeps its name. Everything else stays a\n // NetworkError, exactly as before.\n const named = readErrorCodeFields(payload.data);\n if (named.code) {\n throw new ApiError(message, named.code, response.status, named.errorParams);\n }\n\n throw new NetworkError(message, response.status);\n }\n\n if (response.status === 204 && payload.data === null) {\n return {\n success: true,\n };\n }\n\n if (!payload.data || typeof payload.data !== 'object' || !('status' in payload.data)) {\n throw new NetworkError('Invalid API response', response.status);\n }\n\n const data = payload.data as ApiResponse<T>;\n const mapped = mapApiResponse(data);\n return mapped.success\n ? mapped\n : {\n ...mapped,\n responseReceived: true,\n responseDefinitive: data.status >= 400 && data.status < 500 && data.status !== 408,\n status: response.status,\n ...(responseChallenge ? { challenge: responseChallenge } : {}),\n };\n } catch (error) {\n let normalizedError = error instanceof Error ? error : new Error(String(error));\n\n if (error instanceof DOMException && error.name === 'AbortError') {\n normalizedError = new NetworkError('Request timeout', 408);\n }\n\n // Read from the base class, not NetworkError: a named ApiError also\n // carries the HTTP status, and losing it would misclassify a 400\n // refusal as a transport failure — retried and reported as an outage.\n const statusCode =\n normalizedError instanceof ShoppexError\n ? normalizedError.statusCode\n : undefined;\n\n lastFailure = {\n message: normalizedError.message,\n statusCode,\n isTransport: statusCode === undefined || statusCode === 408,\n responseReceived,\n responseDefinitive,\n ...(responseChallenge ? { challenge: responseChallenge } : {}),\n ...(normalizedError instanceof ApiError\n ? {\n code: normalizedError.code,\n ...(normalizedError.errorParams ? { errorParams: normalizedError.errorParams } : {}),\n }\n : {}),\n };\n\n // A named 4xx is the server's decision, not a transport hiccup:\n // `ApiError` only exists when the response carried an error code, and\n // a client-error status means the request itself was refused. Repeating\n // it verbatim cannot change the answer — it just multiplies the load\n // and delays the refusal the caller is waiting on by the full backoff\n // schedule. 408 stays retryable (it is a timeout wearing a 4xx) and\n // every 5xx, network failure and unnamed error retries exactly as\n // before.\n const isNamedClientRefusal =\n normalizedError instanceof ApiError\n && statusCode !== undefined\n && statusCode >= 400\n && statusCode < 500\n && statusCode !== 408;\n\n if (isNamedClientRefusal) {\n break;\n }\n\n if (attempt < retryCount) {\n await sleep(Math.pow(2, attempt) * 500);\n continue;\n }\n }\n }\n\n return {\n success: false,\n message: lastFailure?.message ?? 'Unknown error',\n ...(lastFailure ? { responseReceived: lastFailure.responseReceived } : {}),\n ...(lastFailure?.responseDefinitive ? { responseDefinitive: true } : {}),\n ...(lastFailure?.responseReceived && lastFailure.statusCode !== undefined\n ? { status: lastFailure.statusCode }\n : {}),\n ...(lastFailure?.challenge ? { challenge: lastFailure.challenge } : {}),\n ...(lastFailure?.code ? { code: lastFailure.code } : {}),\n ...(lastFailure?.errorParams ? { errorParams: lastFailure.errorParams } : {}),\n };\n };\n\n const result =\n method === 'GET' && cache && cache.ttl > 0\n ? await getOrFetch(\n cache.key ?? `GET:${url}`,\n executeRequest,\n { ttl: cache.ttl, staleWhileRevalidate: cache.staleWhileRevalidate },\n (value) => value.success\n )\n : await executeRequest();\n\n const failureForTelemetry = lastFailure as FailureInfo | null;\n\n if (!result.success && failureForTelemetry?.isTransport) {\n\n await reportStorefrontClientError({\n endpoint,\n method,\n message: result.message ?? failureForTelemetry.message,\n statusCode: failureForTelemetry.statusCode,\n attemptCount: retryCount + 1,\n requestUrl: url,\n responseReceived: failureForTelemetry.responseReceived,\n });\n }\n\n return result;\n}\n\nasync function parseResponsePayload(response: Response): Promise<ParsedResponsePayload> {\n const responseWithOptionalMethods = response as Response & {\n text?: () => Promise<string>;\n json?: () => Promise<unknown>;\n };\n\n // Runtime-safe fallback for test mocks that only implement `json()`.\n if (typeof responseWithOptionalMethods.text !== 'function') {\n if (typeof responseWithOptionalMethods.json === 'function') {\n try {\n return {\n data: await responseWithOptionalMethods.json(),\n rawText: null,\n };\n } catch {\n return { data: null, rawText: null };\n }\n }\n return { data: null, rawText: null };\n }\n\n try {\n const rawText = await responseWithOptionalMethods.text();\n if (!rawText) {\n return { data: null, rawText: null };\n }\n\n try {\n return {\n data: JSON.parse(rawText) as unknown,\n rawText: null,\n };\n } catch {\n const normalizedText = rawText.trim();\n return {\n data: null,\n rawText: normalizedText.length > 0 ? normalizedText : null,\n };\n }\n } catch {\n return { data: null, rawText: null };\n }\n}\n\nfunction readResponseChallenge(payload: unknown): ApiChallenge | undefined {\n if (!payload || typeof payload !== 'object') {\n return undefined;\n }\n const data = (payload as { data?: unknown }).data;\n if (!data || typeof data !== 'object') {\n return undefined;\n }\n const challenge = (data as { challenge?: unknown }).challenge;\n if (!challenge || typeof challenge !== 'object') {\n return undefined;\n }\n const provider = (challenge as { provider?: unknown }).provider;\n const siteKey = (challenge as { site_key?: unknown }).site_key;\n if (provider !== 'turnstile' || typeof siteKey !== 'string' || !siteKey.trim()) {\n return undefined;\n }\n return { provider, siteKey: siteKey.trim() };\n}\n\nfunction isDefinitiveHttpRefusal(payload: unknown): boolean {\n if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {\n return false;\n }\n\n const record = payload as Record<string, unknown>;\n return typeof record.status === 'number' && record.status >= 400 && record.status < 500;\n}\n\nfunction mapApiResponse<T>(apiResponse: ApiResponse<T>): SDKResponse<T> {\n if (apiResponse.status >= 200 && apiResponse.status < 300) {\n return {\n success: true,\n data: apiResponse.data,\n ...(apiResponse.message ? { message: apiResponse.message } : {}),\n };\n }\n\n return {\n success: false,\n message: apiResponse.error ?? apiResponse.message ?? `Request failed with status ${apiResponse.status}`,\n // The refusal the server actually made, kept machine-readable. Without it\n // a caller can only string-match a localized sentence, which breaks in\n // every locale but one.\n ...readErrorCodeFields(apiResponse),\n };\n}\n\n/**\n * Pull the localized-error envelope (`error_code` / `error_params`) off any\n * server payload shape. Returns an empty object when the payload carries none,\n * so the fields stay absent rather than becoming `undefined` keys.\n */\nfunction readErrorCodeFields(payload: unknown): { code?: string; errorParams?: Record<string, unknown> } {\n if (!payload || typeof payload !== 'object') {\n return {};\n }\n\n const record = payload as Record<string, unknown>;\n const code = typeof record.error_code === 'string' && record.error_code.length > 0\n ? record.error_code\n : null;\n if (!code) {\n return {};\n }\n\n const params = record.error_params;\n return {\n code,\n ...(params && typeof params === 'object' && !Array.isArray(params)\n ? { errorParams: params as Record<string, unknown> }\n : {}),\n };\n}\n\nexport async function get<T>(\n endpoint: string,\n options?: Omit<RequestOptions, 'method' | 'body'>\n): Promise<SDKResponse<T>> {\n return request<T>(endpoint, { ...options, method: 'GET' });\n}\n\nexport async function post<T>(\n endpoint: string,\n body?: unknown,\n options?: Omit<RequestOptions, 'method' | 'body'>\n): Promise<SDKResponse<T>> {\n return request<T>(endpoint, { ...options, method: 'POST', body });\n}\n","/**\n * Store Module\n *\n * API methods for store data.\n */\n\nimport { get } from '../core/client';\nimport { DEFAULT_API_BASE_URL, getConfig, isInitialized, setShopId } from '../core/config';\nimport { buildEndpoint } from '../core/endpoint';\nimport type {\n SDKResponse,\n Shop,\n Product,\n StorefrontData,\n ProductGroup,\n Category,\n StorefrontAddonBootstrap,\n CursorPagination,\n} from '../types';\n\ninterface StoreResponse {\n shop: Shop;\n products?: Product[];\n products_pagination?: CursorPagination | null;\n groups?: ProductGroup[];\n items?: StorefrontData['items'];\n categories?: Category[];\n addons?: StorefrontAddonBootstrap;\n}\n\ninterface StorefrontResponse {\n shop: Shop;\n}\n\nexport interface GetStorefrontOptions {\n productsLimit?: number;\n productsCursor?: string | null;\n}\n\nconst STORE_CACHE_TTL = 5 * 60 * 1000;\n\nexport async function getStore(): Promise<SDKResponse<Shop>> {\n const config = getConfig();\n const response = await get<StoreResponse>(\n buildEndpoint('/v1/storefront/shops/name/:storeSlug', {\n storeSlug: config.storeSlug,\n }),\n {\n cache: {\n key: `store:${config.storeSlug}`,\n ttl: STORE_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data) {\n // Cache the shopId for slug lookups\n if (response.data.shop?.id) {\n setShopId(response.data.shop.id);\n }\n return {\n success: true,\n data: response.data.shop,\n };\n }\n\n return {\n success: false,\n message: response.message,\n };\n}\n\nexport async function resolveStoreByDomain(\n domain?: string,\n apiBaseUrl?: string\n): Promise<SDKResponse<Shop>> {\n const resolvedDomain =\n domain ??\n (typeof window !== 'undefined' ? window.location.hostname : '');\n\n if (!resolvedDomain) {\n return {\n success: false,\n message: 'Domain is required to resolve store',\n };\n }\n\n const cleanDomain = resolvedDomain\n .replace(/^https?:\\/\\//, '')\n .split('/')[0]\n .trim();\n\n const baseUrl =\n apiBaseUrl ??\n (isInitialized() ? getConfig().apiBaseUrl : DEFAULT_API_BASE_URL);\n\n const response = await get<StorefrontResponse>(\n buildEndpoint('/v1/storefront/shops/domain/:domain', {\n domain: cleanDomain,\n }),\n {\n baseUrl,\n cache: {\n key: `store:domain:${cleanDomain}`,\n ttl: STORE_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data?.shop) {\n if (response.data.shop.id) {\n setShopId(response.data.shop.id);\n }\n return {\n success: true,\n data: response.data.shop,\n };\n }\n\n return {\n success: false,\n message: response.message ?? 'Failed to resolve store',\n };\n}\n\nexport async function getStorefront(options?: GetStorefrontOptions): Promise<SDKResponse<StorefrontData>> {\n const config = getConfig();\n const query = new URLSearchParams();\n if (Number.isFinite(options?.productsLimit)) {\n query.set('products_limit', String(Math.max(1, Math.floor(options?.productsLimit ?? 0))));\n }\n if (typeof options?.productsCursor === 'string' && options.productsCursor.trim().length > 0) {\n query.set('products_cursor', options.productsCursor);\n }\n const querySuffix = query.size > 0 ? `?${query.toString()}` : '';\n const response = await get<StoreResponse>(\n `${buildEndpoint('/v1/storefront/shops/name/:storeSlug', {\n storeSlug: config.storeSlug,\n })}${querySuffix}`,\n {\n cache: {\n key: `storefront:${config.storeSlug}:${options?.productsLimit ?? 'full'}:${options?.productsCursor ?? 'start'}`,\n ttl: STORE_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data) {\n // Cache the shopId for slug lookups\n if (response.data.shop?.id) {\n setShopId(response.data.shop.id);\n }\n return {\n success: true,\n data: {\n shop: response.data.shop,\n products: response.data.products ?? [],\n products_pagination: response.data.products_pagination ?? null,\n groups: response.data.groups ?? [],\n items: response.data.items ?? [],\n categories: response.data.categories ?? [],\n addons: response.data.addons ?? { items: [] },\n },\n };\n }\n\n return {\n success: false,\n message: response.message,\n };\n}\n\nexport async function getStoreLogoUrl(): Promise<string | null> {\n const response = await getStore();\n\n if (response.success && response.data?.logo) {\n return response.data.logo;\n }\n\n return null;\n}\n\nexport async function getStoreBannerUrl(): Promise<string | null> {\n const response = await getStore();\n\n if (response.success && response.data?.banner) {\n return response.data.banner;\n }\n\n return null;\n}\n","/**\n * Products Module\n *\n * API methods for product data.\n */\n\nimport { get } from '../core/client';\nimport { getConfig, getShopId } from '../core/config';\nimport { buildEndpoint } from '../core/endpoint';\nimport type {\n SDKResponse,\n Product,\n ProductCategory,\n ProductGroup,\n ProductVariant,\n PriceVariant,\n CursorPagination,\n} from '../types';\nimport { getStore } from './store';\nimport { getMergedStorefrontProducts } from '../utils/storefront-catalog';\n\ninterface ProductsResponse {\n products: Product[];\n groups?: ProductGroup[];\n pagination?: CursorPagination | null;\n}\n\ninterface ProductResponse {\n product: Product;\n}\n\nconst PRODUCTS_CACHE_TTL = 2 * 60 * 1000;\n\nexport interface GetStorefrontProductsPageOptions {\n cursor?: string | null;\n limit?: number;\n sort?: 'featured' | 'newest' | 'price-asc' | 'price-desc' | string | null;\n category?: string | null;\n hideOutOfStock?: boolean;\n}\n\nfunction getStorefrontProductsPageCategoryCacheKey(category: string | null | undefined): string {\n if (category === undefined) return 'category:unset';\n if (category === null) return 'category:null';\n return `category:${category}`;\n}\n\nfunction priceVariantToProductVariant(variant: PriceVariant & { stock?: number }): ProductVariant {\n return {\n id: variant.id,\n title: variant.title ?? variant.label ?? '',\n price: typeof variant.price === 'number' ? variant.price : Number(variant.price) || 0,\n stock: typeof variant.stock === 'number' ? variant.stock : undefined,\n // Dynamic Delivery (S8): carry the availability pair through. A supplier-backed\n // variant reports `stock: 0`, so dropping `orderable` here would make the mapped\n // variant look sold out. Left `undefined` when the source omits it, which keeps\n // the historical stock-only behaviour for payloads that predate the field.\n orderable: typeof variant.orderable === 'boolean' ? variant.orderable : undefined,\n supplier_backed:\n typeof variant.supplier_backed === 'boolean' ? variant.supplier_backed : undefined,\n quantity_min: variant.quantity_min,\n quantity_max: variant.quantity_max,\n quantityMin: variant.quantityMin,\n quantityMax: variant.quantityMax,\n image_id: variant.image_id,\n imageId: variant.imageId,\n cloudflare_image_id: variant.cloudflare_image_id,\n cloudflareImageId: variant.cloudflareImageId,\n image_url: variant.image_url,\n imageUrl: variant.imageUrl,\n };\n}\n\nfunction normalizeProduct(product: Product): Product {\n if (product.variants && product.variants.length > 0) {\n return product;\n }\n\n const priceVariants = product.price_variants;\n if (!Array.isArray(priceVariants) || priceVariants.length === 0) {\n return product;\n }\n\n return {\n ...product,\n variants: priceVariants.map((variant) =>\n priceVariantToProductVariant(variant as PriceVariant & { stock?: number })\n ),\n };\n}\n\nexport async function getProducts(): Promise<SDKResponse<Product[]>> {\n const config = getConfig();\n const response = await get<ProductsResponse>(\n buildEndpoint('/v1/storefront/products/public/:storeSlug', {\n storeSlug: config.storeSlug,\n }),\n {\n cache: {\n key: `products:${config.storeSlug}`,\n ttl: PRODUCTS_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data) {\n // The public route returns every public product exactly once in the flat `products` array —\n // group-bound products (e.g. variant-style DYNAMIC products) are included there too, so no\n // group merge is needed anymore. Groups only carry `product_uniqids` references into this\n // list. getMergedStorefrontProducts just dedupes by uniqid (first entry wins).\n return {\n success: true,\n data: getMergedStorefrontProducts(response.data.products.map(normalizeProduct)),\n };\n }\n\n return {\n success: false,\n message: response.message,\n data: [],\n };\n}\n\nexport async function getStorefrontProductsPage(\n options?: GetStorefrontProductsPageOptions,\n): Promise<SDKResponse<{ products: Product[]; pagination: CursorPagination | null }>> {\n const config = getConfig();\n const query = new URLSearchParams();\n if (typeof options?.cursor === 'string' && options.cursor.trim().length > 0) {\n query.set('cursor', options.cursor);\n }\n if (Number.isFinite(options?.limit)) {\n query.set('limit', String(Math.max(1, Math.floor(options?.limit ?? 0))));\n }\n if (typeof options?.sort === 'string' && options.sort.trim().length > 0) {\n query.set('sort', options.sort.trim());\n }\n if (typeof options?.category === 'string' && options.category.trim().length > 0) {\n query.set('category', options.category.trim());\n }\n if (options?.hideOutOfStock === true) {\n query.set('hide_out_of_stock', 'true');\n }\n const querySuffix = query.size > 0 ? `?${query.toString()}` : '';\n\n const response = await get<ProductsResponse>(\n `${buildEndpoint('/v1/storefront/products/shop/:storeSlug', {\n storeSlug: config.storeSlug,\n })}${querySuffix}`,\n {\n cache: {\n key: `products:page:${config.storeSlug}:${options?.limit ?? 'default'}:${options?.cursor ?? 'start'}:${options?.sort ?? 'featured'}:${getStorefrontProductsPageCategoryCacheKey(options?.category)}:${options?.hideOutOfStock === true ? 'in-stock' : 'all-stock'}`,\n ttl: PRODUCTS_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data) {\n return {\n success: true,\n data: {\n products: response.data.products.map(normalizeProduct),\n pagination: response.data.pagination ?? null,\n },\n };\n }\n\n return {\n success: false,\n message: response.message,\n };\n}\n\nexport async function getProduct(\n idOrSlug: string\n): Promise<SDKResponse<Product>> {\n // Slug lookups need the current shop id. Resolve it lazily so callers do not\n // have to remember to call getStore()/getStorefront() first.\n let shopId = getShopId();\n if (!shopId) {\n const store = await getStore();\n shopId = store.success ? (store.data?.id ?? null) : null;\n }\n\n const queryParams = shopId ? `?slug_shop_id=${encodeURIComponent(shopId)}` : '';\n\n const response = await get<ProductResponse>(\n `${buildEndpoint('/v1/storefront/products/unique/:idOrSlug', { idOrSlug })}${queryParams}`,\n {\n cache: {\n key: `product:${idOrSlug}:${shopId ?? 'no-shop'}`,\n ttl: PRODUCTS_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data?.product) {\n return {\n success: true,\n data: normalizeProduct(response.data.product),\n };\n }\n\n return {\n success: false,\n message: response.message,\n };\n}\n\nexport async function getCategories(): Promise<SDKResponse<string[]>> {\n const products = await getProducts();\n\n if (!products.success || !products.data) {\n return {\n success: false,\n message: products.message,\n };\n }\n\n const categories = new Set<string>();\n for (const product of products.data) {\n if (product.categories) {\n for (const category of product.categories) {\n if (typeof category === 'string') {\n categories.add(category);\n } else if (category && typeof category === 'object' && 'uniqid' in category) {\n categories.add((category as ProductCategory).uniqid);\n }\n }\n }\n }\n\n return {\n success: true,\n data: Array.from(categories),\n };\n}\n","import { getConfig, isInitialized } from '../core/config';\nimport { post } from '../core/client';\nimport type { AffiliateValidation, SDKResponse } from '../types';\n\nconst STORAGE_KEY = 'shoppex:affiliate_code:v1';\nconst SESSION_STORAGE_KEY = 'shoppex:affiliate_session:v1';\nconst DEFAULT_TTL_DAYS = 30;\n// 24 base-36 characters provide about 124 bits of entropy and stay within the API's 8-64 character limit.\nconst FALLBACK_SESSION_KEY_LENGTH = 24;\nconst SESSION_KEY_ALPHABET = 'abcdefghijklmnopqrstuvwxyz0123456789';\n\ntype StoredAffiliate = {\n code: string;\n expiresAt: number;\n};\n\nfunction nowMs() {\n return Date.now();\n}\n\nfunction ttlMs(days: number) {\n return Math.max(1, days) * 24 * 60 * 60 * 1000;\n}\n\nfunction normalizeAffiliateCode(code: string | null | undefined): string | null {\n const normalized = code?.trim().toLowerCase();\n return normalized ? normalized : null;\n}\n\nfunction safeRead(): StoredAffiliate | null {\n if (typeof window === 'undefined') return null;\n try {\n const raw = window.localStorage.getItem(STORAGE_KEY);\n if (!raw) return null;\n const parsed = JSON.parse(raw) as StoredAffiliate;\n if (!parsed || typeof parsed.code !== 'string' || typeof parsed.expiresAt !== 'number') return null;\n return parsed;\n } catch {\n return null;\n }\n}\n\nfunction safeWrite(value: StoredAffiliate) {\n if (typeof window === 'undefined') return;\n try {\n window.localStorage.setItem(STORAGE_KEY, JSON.stringify(value));\n } catch {\n // ignore\n }\n}\n\nexport function setAffiliateCode(code: string | null | undefined, ttlDays = DEFAULT_TTL_DAYS): string | null {\n const normalized = normalizeAffiliateCode(code);\n if (!normalized) {\n clearAffiliateCode();\n return null;\n }\n\n safeWrite({ code: normalized, expiresAt: nowMs() + ttlMs(ttlDays) });\n return normalized;\n}\n\nexport function clearAffiliateCode(): void {\n if (typeof window === 'undefined') return;\n try {\n window.localStorage.removeItem(STORAGE_KEY);\n } catch {\n // ignore\n }\n}\n\nexport function getAffiliateCode(): string | null {\n const stored = safeRead();\n if (!stored) return null;\n if (stored.expiresAt <= nowMs()) {\n clearAffiliateCode();\n return null;\n }\n return normalizeAffiliateCode(stored.code);\n}\n\nfunction createAffiliateSessionKey(): string {\n try {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n }\n } catch {\n // Fall through to the browser-safe random key.\n }\n\n let key = '';\n for (let index = 0; index < FALLBACK_SESSION_KEY_LENGTH; index += 1) {\n key += SESSION_KEY_ALPHABET[Math.floor(Math.random() * SESSION_KEY_ALPHABET.length)];\n }\n return key;\n}\n\n// Retained for the page's lifetime when sessionStorage is unavailable, so\n// repeated events in a storage-restricted browser still share one key and the\n// server-side session dedupe keeps working.\nlet inMemorySessionKey: string | null = null;\n\nfunction getAffiliateSessionKey(): string {\n try {\n const stored = window.sessionStorage.getItem(SESSION_STORAGE_KEY);\n if (stored && stored.length >= 8 && stored.length <= 64) {\n return stored;\n }\n } catch {\n // Read blocked entirely: the retained key is all we have.\n if (inMemorySessionKey) return inMemorySessionKey;\n }\n\n const key = createAffiliateSessionKey();\n try {\n window.sessionStorage.setItem(SESSION_STORAGE_KEY, key);\n // A write that silently no-ops (quota) must not hand out a fresh key per\n // event — verify it landed before trusting storage over the retained key.\n if (window.sessionStorage.getItem(SESSION_STORAGE_KEY) === key) {\n inMemorySessionKey = key;\n return key;\n }\n } catch {\n // Fall through to the retained key.\n }\n\n if (!inMemorySessionKey) inMemorySessionKey = key;\n return inMemorySessionKey;\n}\n\nexport async function trackAffiliateEvent(\n eventType: 'add_to_cart' | 'checkout_started',\n options?: {\n /**\n * The code the surrounding call actually resolved and submitted (e.g.\n * checkout()'s tri-state result). `null` means the caller explicitly\n * submitted WITHOUT a referral — no event is recorded, so an ambient\n * stored code is never credited for a sale it did not get. Omit the\n * options object entirely to attribute to the stored ambient code.\n */\n code: string | null;\n /**\n * Overrides the per-browser-session dedupe key. checkout entry points\n * pass `inv:<invoiceId>` so every created invoice counts as exactly one\n * checkout — a session-wide key would drop the second checkout of a\n * buyer who orders twice in one session while both sales still count.\n */\n dedupeKey?: string;\n }\n): Promise<void> {\n try {\n if (typeof window === 'undefined' || !isInitialized()) return;\n\n const code = options === undefined\n ? getAffiliateCode()\n : normalizeAffiliateCode(options.code);\n if (!code) return;\n\n const config = getConfig();\n // Raw fetch instead of the shared post helper: `keepalive` lets the\n // request survive the checkout redirect that immediately follows, which\n // would otherwise cancel it and undercount checkouts.\n await fetch(`${config.apiBaseUrl}/v1/storefront/affiliates/events`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n keepalive: true,\n body: JSON.stringify({\n shop_slug: config.storeSlug,\n code,\n event_type: eventType,\n // Dedupe key: per browser session by default (one add-to-cart per\n // session per link), or the caller's key — checkout passes one per\n // created invoice.\n session_key: options?.dedupeKey?.slice(0, 64) ?? getAffiliateSessionKey(),\n }),\n });\n } catch {\n // Funnel tracking must never break cart or checkout behavior.\n }\n}\n\nexport async function validateAffiliateCode(code: string): Promise<SDKResponse<AffiliateValidation>> {\n const normalizedCode = normalizeAffiliateCode(code);\n if (!normalizedCode) {\n return {\n success: false,\n data: {\n valid: false,\n affiliate_code: null,\n discount_active: false,\n discount_percent: 0,\n },\n message: 'Affiliate code is required',\n };\n }\n\n const config = getConfig();\n const response = await post<AffiliateValidation>(\n '/v1/storefront/affiliates/resolve',\n {\n shop_slug: config.storeSlug,\n code: normalizedCode,\n },\n { retries: 0 }\n );\n\n if (!response.success) {\n return response;\n }\n\n if (!response.data?.valid || !response.data.affiliate_code) {\n const programDisabled = response.data?.program_enabled === false;\n return {\n success: false,\n data: {\n valid: false,\n ...(response.data?.program_enabled !== undefined ? { program_enabled: response.data.program_enabled } : {}),\n affiliate_code: null,\n discount_active: false,\n discount_percent: 0,\n },\n message: response.message\n ?? (programDisabled ? 'Affiliate program is disabled for this shop.' : 'Invalid affiliate code.'),\n };\n }\n\n return {\n success: true,\n data: {\n valid: true,\n ...(response.data.program_enabled !== undefined ? { program_enabled: response.data.program_enabled } : {}),\n affiliate_code: normalizeAffiliateCode(response.data.affiliate_code),\n discount_active: Boolean(response.data.discount_active),\n discount_percent: Number(response.data.discount_percent ?? 0),\n },\n ...(response.message ? { message: response.message } : {}),\n };\n}\n\nexport async function applyAffiliateCode(code: string): Promise<SDKResponse<AffiliateValidation>> {\n const result = await validateAffiliateCode(code);\n if (result.success && result.data?.affiliate_code) {\n setAffiliateCode(result.data.affiliate_code);\n }\n\n return result;\n}\n\n/**\n * Capture an affiliate code from the current URL and store it for 30 days (last-click).\n *\n * Example:\n * - URL: https://mystore.com/product/abc?ref=deadbeef\n * - captureAffiliateFromUrl() stores \"deadbeef\" and returns it.\n */\nexport async function captureAffiliateFromUrl(param = 'ref'): Promise<string | null> {\n if (typeof window === 'undefined') return null;\n\n let code: string | null = null;\n try {\n const url = new URL(window.location.href);\n const raw = url.searchParams.get(param);\n code = raw ? raw.trim() : null;\n } catch {\n code = null;\n }\n\n code = normalizeAffiliateCode(code);\n if (!code) return null;\n\n // Store immediately so we don't lose it if attribution call fails.\n setAffiliateCode(code);\n\n // Optional: validate + normalize with backend. If invalid, clear it.\n if (isInitialized()) {\n try {\n const config = getConfig();\n const res = await post<{ accepted?: boolean; affiliate_code?: string | null }>(\n '/v1/storefront/affiliates/attribution',\n { shop_slug: config.storeSlug, code },\n { retries: 0 }\n );\n if (res.success && res.data?.accepted && res.data.affiliate_code) {\n setAffiliateCode(res.data.affiliate_code);\n return res.data.affiliate_code;\n }\n // Clear only on a definitive refusal (the server answered and said the\n // code is not attributable). A rate limit or transport failure must not\n // destroy a valid referral before checkout — from-cart validates later.\n if (res.success && res.data && res.data.accepted === false) {\n clearAffiliateCode();\n return null;\n }\n return code;\n } catch {\n // keep stored raw code, from-cart will validate later\n return code;\n }\n }\n\n return code;\n}\n","import type { CartAddon, CartItem } from '../types/cart';\n\nfunction hashString(value: string): string {\n let hash = 2166136261;\n for (let i = 0; i < value.length; i += 1) {\n hash ^= value.charCodeAt(i);\n hash += (hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24);\n }\n return (hash >>> 0).toString(16);\n}\n\nfunction normalizeAddons(addons: CartAddon[] | undefined): CartAddon[] {\n if (!addons?.length) return [];\n return [...addons]\n .map((addon) => ({ id: addon.id, quantity: addon.quantity ?? 1 }))\n .sort((a, b) => a.id.localeCompare(b.id));\n}\n\nfunction normalizeCustomFields(fields: Record<string, string> | undefined): Record<string, string> {\n if (!fields) return {};\n const entries = Object.entries(fields)\n .filter(([, value]) => typeof value === 'string')\n .sort(([a], [b]) => a.localeCompare(b));\n return Object.fromEntries(entries);\n}\n\nexport type CartLineIdentityInput = Pick<\n CartItem,\n 'product_id' | 'variant_id' | 'price_variant_id' | 'addons' | 'custom_fields' | 'price_data' | 'pay_what_you_want_price'\n>;\n\nexport function computeCartLineId(input: CartLineIdentityInput): string {\n const payload = {\n product_id: input.product_id,\n variant_id: input.variant_id,\n price_variant_id: input.price_variant_id ?? null,\n addons: normalizeAddons(input.addons),\n custom_fields: normalizeCustomFields(input.custom_fields),\n unit_price:\n typeof input.price_data?.unit_price === 'number' && Number.isFinite(input.price_data.unit_price)\n ? input.price_data.unit_price\n : null,\n pay_what_you_want_price:\n typeof input.pay_what_you_want_price === 'number' && Number.isFinite(input.pay_what_you_want_price)\n ? input.pay_what_you_want_price\n : null,\n };\n return hashString(JSON.stringify(payload));\n}\n\nexport function ensureCartLineId(item: CartItem): CartItem {\n if (typeof item.line_id === 'string' && item.line_id.trim()) {\n return item;\n }\n return { ...item, line_id: computeCartLineId(item) };\n}\n","export function normalizeRequestedCurrency(value: string | null | undefined): string | null {\n const normalized = value?.trim().toUpperCase();\n return normalized && /^[A-Z]{3}$/.test(normalized) ? normalized : null;\n}\n\nexport function getRequestedCurrencyFromLocation(): string | null {\n if (typeof window === 'undefined' || !window.location) {\n return null;\n }\n\n const search = typeof window.location.search === 'string' ? window.location.search : '';\n if (search) {\n return normalizeRequestedCurrency(new URLSearchParams(search).get('currency'));\n }\n\n const href = typeof window.location.href === 'string' ? window.location.href : '';\n if (!href) {\n return null;\n }\n\n try {\n return normalizeRequestedCurrency(\n new URL(href, 'https://storefront.shoppex.local').searchParams.get('currency'),\n );\n } catch {\n return null;\n }\n}\n","/**\n * Cart Module\n *\n * localStorage-based cart with support for Shoppex features:\n * - Addons (express shipping, gift wrap, etc.)\n * - Custom Fields (engraving, gift message, etc.)\n * - Price Variants (different pricing tiers)\n */\n\nimport { getItem, setItem, removeItem } from '../utils/storage';\nimport { getConfig } from '../core/config';\nimport { post } from '../core/client';\nimport { CartError } from '../core/errors';\nimport type {\n CartItem,\n CartAddOptions,\n CartItemUpdate,\n CartPayload,\n CartMetadata,\n CartStats,\n CartQuote,\n CartBasketMergeLine,\n CartCodeSource,\n} from '../types';\nimport { getAffiliateCode, trackAffiliateEvent } from './affiliates';\nimport { computeCartLineId, ensureCartLineId } from '../utils/cart-line-id';\nimport {\n getRequestedCurrencyFromLocation,\n normalizeRequestedCurrency,\n} from '../utils/requested-currency';\nimport { roundPayableAmount } from '@shoppex/contracts/catalog-unit-price';\n\nconst STORAGE_KEYS = {\n cart: 'cart',\n cartBackup: 'cart_backup',\n meta: 'cart_meta',\n metaBackup: 'cart_backup_meta',\n coupon: 'cart_coupon',\n couponBackup: 'cart_coupon_backup',\n} as const;\n\ntype StorageKeyType = keyof typeof STORAGE_KEYS;\n\nfunction getStorageKey(type: StorageKeyType): string {\n return `${STORAGE_KEYS[type]}_${getConfig().storeSlug}`;\n}\n\nfunction hashString(value: string): string {\n let hash = 2166136261;\n for (let i = 0; i < value.length; i += 1) {\n hash ^= value.charCodeAt(i);\n hash += (hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24);\n }\n return (hash >>> 0).toString(16);\n}\n\nfunction computeChecksum(cart: CartItem[]): string {\n return hashString(JSON.stringify(cart));\n}\n\nfunction normalizeQuantity(value: number): number {\n if (!Number.isFinite(value)) {\n throw new CartError('quantity must be a finite number');\n }\n return Math.floor(value);\n}\n\nfunction normalizeCouponCode(value: string | null | undefined): string | null {\n const normalized = value?.trim().toUpperCase();\n return normalized ? normalized : null;\n}\n\ntype StoredCartCode = {\n code: string;\n source: CartCodeSource;\n};\n\nfunction getStoredCartCode(): StoredCartCode | null {\n const raw = getItem<unknown>(getStorageKey('coupon'));\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {\n return null;\n }\n const record = raw as Record<string, unknown>;\n const code = typeof record.code === 'string' ? normalizeCouponCode(record.code) : null;\n const source = record.source === 'COUPON' || record.source === 'AFFILIATE'\n ? record.source\n : null;\n return code && source ? { code, source } : null;\n}\n\nfunction normalizeCartItems(value: unknown): CartItem[] {\n if (!Array.isArray(value)) return [];\n const normalized: CartItem[] = [];\n for (const entry of value) {\n if (!entry || typeof entry !== 'object') continue;\n const record = entry as Record<string, unknown>;\n const productId = typeof record.product_id === 'string' ? record.product_id.trim() : '';\n const variantId = typeof record.variant_id === 'string' ? record.variant_id.trim() : '';\n const quantity = Number(record.quantity);\n\n if (!productId || !variantId || !Number.isFinite(quantity) || quantity < 1) {\n continue;\n }\n\n const item: CartItem = {\n line_id: '',\n product_id: productId,\n variant_id: variantId,\n quantity: Math.floor(quantity),\n };\n\n if (typeof record.price_variant_id === 'string') {\n item.price_variant_id = record.price_variant_id;\n }\n if (record.price_data && typeof record.price_data === 'object') {\n const priceData = record.price_data as Record<string, unknown>;\n if (typeof priceData.unit_price === 'number' && Number.isFinite(priceData.unit_price)) {\n item.price_data = { unit_price: priceData.unit_price };\n }\n }\n if (typeof record.pay_what_you_want_price === 'number' && Number.isFinite(record.pay_what_you_want_price)) {\n item.pay_what_you_want_price = record.pay_what_you_want_price;\n }\n if (Array.isArray(record.addons)) {\n item.addons = record.addons as CartItem['addons'];\n }\n if (record.custom_fields && typeof record.custom_fields === 'object' && !Array.isArray(record.custom_fields)) {\n item.custom_fields = record.custom_fields as Record<string, string>;\n }\n\n // Preserve the optional display snapshot (title/variant_title/image_url/addon_labels) across the\n // localStorage round-trip so the njk cart drawer/page can render without a product fetch.\n if (typeof record.title === 'string') {\n item.title = record.title;\n }\n if (typeof record.variant_title === 'string') {\n item.variant_title = record.variant_title;\n }\n if (typeof record.image_url === 'string') {\n item.image_url = record.image_url;\n }\n if (Array.isArray(record.addon_labels)) {\n item.addon_labels = record.addon_labels.filter((label): label is string => typeof label === 'string');\n }\n if (typeof record.max_quantity === 'number' && Number.isFinite(record.max_quantity)) {\n item.max_quantity = record.max_quantity;\n }\n if (typeof record.min_quantity === 'number' && Number.isFinite(record.min_quantity)) {\n item.min_quantity = record.min_quantity;\n }\n\n // Self-heal on READ: clamp quantity to the stored [min,max] here, after the bounds are read. This is\n // the single chokepoint every access flows through (getCart -> getCartPayload -> serializeCart/\n // quoteCart -> checkout), so a stale/tampered/restored localStorage line can never reach checkout\n // out of bounds — closing restoreCartFromBackup and direct-localStorage-edit at the root, not just\n // the write paths.\n clampQuantityToBounds(item);\n\n const storedLineId = typeof record.line_id === 'string' ? record.line_id.trim() : '';\n item.line_id = storedLineId || computeCartLineId(item);\n\n normalized.push(ensureCartLineId(item));\n }\n return normalized;\n}\n\nfunction getCartMetadata(): CartMetadata | null {\n return getItem<CartMetadata>(getStorageKey('meta'));\n}\n\nexport function getCartCoupon(): string | null {\n return getStoredCartCode()?.code ?? null;\n}\n\nexport function getCartCouponSource(): CartCodeSource | null {\n return getStoredCartCode()?.source ?? null;\n}\n\nexport function setCartCoupon(\n coupon: string | null | undefined,\n source: CartCodeSource = 'COUPON',\n): string | null {\n const normalizedCoupon = normalizeCouponCode(coupon);\n if (!normalizedCoupon) {\n removeItem(getStorageKey('coupon'));\n return null;\n }\n\n setItem(getStorageKey('coupon'), { code: normalizedCoupon, source });\n return normalizedCoupon;\n}\n\nexport function clearCartCoupon(): void {\n removeItem(getStorageKey('coupon'));\n}\n\nfunction writeCart(cart: CartItem[]): void {\n const normalizedCart = normalizeCartItems(cart);\n setItem(getStorageKey('cart'), normalizedCart);\n const now = Date.now();\n const previous = getCartMetadata();\n const nextMeta: CartMetadata = {\n created_at: previous?.created_at ?? now,\n last_modified: now,\n version: (previous?.version ?? 0) + 1,\n checksum: computeChecksum(normalizedCart),\n };\n setItem(getStorageKey('meta'), nextMeta);\n\n if (normalizedCart.length === 0) {\n clearCartCoupon();\n }\n}\n\nfunction setCartWithMetadata(cart: CartItem[], metadata?: CartMetadata | null): void {\n const normalizedCart = normalizeCartItems(cart);\n setItem(getStorageKey('cart'), normalizedCart);\n const now = Date.now();\n const base = metadata ?? getCartMetadata();\n const nextMeta: CartMetadata = {\n created_at: base?.created_at ?? now,\n last_modified: now,\n version: base?.version ?? 1,\n checksum: computeChecksum(normalizedCart),\n };\n setItem(getStorageKey('meta'), nextMeta);\n}\n\nexport function getCart(): CartItem[] {\n const raw = getItem<unknown>(getStorageKey('cart'));\n return normalizeCartItems(raw);\n}\n\n/** Resolve a cart line_id for product+variant. When multiple configs exist, returns the first line. */\nexport function resolveCartLineId(\n productId: string,\n variantId: string,\n cart: CartItem[] = getCart(),\n): string {\n const matches = cart.filter(\n (item) => item.product_id === productId && item.variant_id === variantId,\n );\n if (matches.length === 0) {\n throw new CartError(`No cart line found for ${productId}/${variantId}`);\n }\n return matches[0].line_id;\n}\n\nexport function getCartItemCount(): number {\n const cart = getCart();\n return cart.reduce((sum, item) => sum + item.quantity, 0);\n}\n\nexport function addToCart(\n productId: string,\n variantId: string,\n quantity: number = 1,\n options?: CartAddOptions\n): void {\n if (!productId || !variantId) {\n throw new CartError('product_id and variant_id are required');\n }\n\n const normalizedQuantity = normalizeQuantity(quantity);\n if (normalizedQuantity < 1) {\n throw new CartError('quantity must be at least 1');\n }\n\n const cart = getCart();\n\n const lineId = computeCartLineId({\n product_id: productId,\n variant_id: variantId,\n addons: options?.addons,\n custom_fields: options?.custom_fields,\n price_variant_id: options?.price_variant_id,\n price_data: options?.price_data,\n pay_what_you_want_price: options?.pay_what_you_want_price,\n });\n\n const existingIndex = cart.findIndex((item) => item.line_id === lineId);\n const quantityBeforeAdd = existingIndex >= 0 ? cart[existingIndex].quantity : 0;\n\n if (existingIndex >= 0) {\n cart[existingIndex].quantity += normalizedQuantity;\n\n if (options?.addons) {\n cart[existingIndex].addons = options.addons;\n }\n if (options?.custom_fields) {\n cart[existingIndex].custom_fields = options.custom_fields;\n }\n if (options?.price_variant_id) {\n cart[existingIndex].price_variant_id = options.price_variant_id;\n }\n if (options?.price_data) {\n cart[existingIndex].price_data = options.price_data;\n }\n if (options?.pay_what_you_want_price !== undefined) {\n cart[existingIndex].pay_what_you_want_price = options.pay_what_you_want_price;\n }\n applyDisplaySnapshot(cart[existingIndex], options);\n clampQuantityToBounds(cart[existingIndex]);\n } else {\n const pushed: CartItem = {\n line_id: lineId,\n product_id: productId,\n variant_id: variantId,\n quantity: normalizedQuantity,\n addons: options?.addons,\n custom_fields: options?.custom_fields,\n price_variant_id: options?.price_variant_id,\n price_data: options?.price_data,\n pay_what_you_want_price: options?.pay_what_you_want_price,\n title: options?.title,\n variant_title: options?.variant_title,\n image_url: options?.image_url,\n addon_labels: options?.addon_labels,\n max_quantity: options?.max_quantity,\n min_quantity: options?.min_quantity,\n };\n clampQuantityToBounds(pushed);\n cart.push(pushed);\n }\n\n const intendedQuantity = (existingIndex >= 0 ? cart[existingIndex] : cart[cart.length - 1]).quantity;\n writeCart(cart);\n // The storage wrapper swallows quota/availability failures, and the cart\n // and metadata writes can fail independently, so the funnel event is gated\n // on the LINE itself: the post-clamp quantity actually grew (a clamped\n // max-quantity no-op did not add anything) AND that exact quantity is\n // readable back from storage (the write of the cart payload landed).\n const persistedLine = getCart().find((item) => item.line_id === lineId);\n if (intendedQuantity > quantityBeforeAdd && persistedLine?.quantity === intendedQuantity) {\n // Attribute like checkout() does: a code applied to the cart (AFFILIATE\n // coupon source) outranks the ambient stored referral.\n const cartAffiliateCode = getCartCouponSource() === 'AFFILIATE' ? getCartCoupon() : null;\n void trackAffiliateEvent('add_to_cart', cartAffiliateCode ? { code: cartAffiliateCode } : undefined);\n }\n}\n\n// Cart-wide invariant: a line's quantity must stay within its stored [min_quantity, max_quantity]\n// bounds. Every write path routes through this — addToCart (merge+push), setCartItem (merge+push),\n// updateCartItem, mergeBaskets (merge+push), moveBasketItem (merge+push) — AND, crucially, the READ\n// path normalizeCartItems (getCart) clamps too, so a stale/tampered/restored localStorage line is\n// self-healed before it can reach checkout. No entrypoint can persist or serve a quantity outside the\n// purchasable range the backend would reject.\n// Order matters: apply min FIRST, then max — so on the degenerate min>max case (e.g. quantity_min 2 but\n// only 1 in stock) MAX wins and the line is never pushed above the stock cap (over-stock is the harder\n// backend reject than under-min). Never below 1. No-op for the bound(s) that are absent.\nfunction clampQuantityToBounds(item: CartItem): void {\n const min = item.min_quantity;\n if (typeof min === 'number' && Number.isFinite(min) && item.quantity < min) {\n item.quantity = Math.floor(min);\n }\n const max = item.max_quantity;\n if (typeof max === 'number' && Number.isFinite(max) && item.quantity > max) {\n item.quantity = Math.floor(max);\n }\n if (item.quantity < 1) {\n item.quantity = 1;\n }\n}\n\n// Copy the optional display snapshot fields from add-options onto an existing line. Display-only —\n// kept separate from the pricing/identity fields so the snapshot logic is identical for add and set.\nfunction applyDisplaySnapshot(item: CartItem, options?: CartAddOptions): void {\n // Authoritative full re-snapshot (buy-box producer): replace ALL display fields verbatim, including\n // CLEARING ones the new snapshot omits — a removed add-on or a lifted cap must not leave stale data.\n if (options?.replace_display_snapshot) {\n item.title = options.title;\n item.variant_title = options.variant_title;\n item.image_url = options.image_url;\n item.addon_labels = options.addon_labels;\n item.max_quantity = options.max_quantity;\n item.min_quantity = options.min_quantity;\n return;\n }\n // Partial direct SDK call: only overwrite the fields actually provided.\n if (options?.title !== undefined) {\n item.title = options.title;\n }\n if (options?.variant_title !== undefined) {\n item.variant_title = options.variant_title;\n }\n if (options?.image_url !== undefined) {\n item.image_url = options.image_url;\n }\n if (options?.addon_labels !== undefined) {\n item.addon_labels = options.addon_labels;\n }\n if (options?.max_quantity !== undefined) {\n item.max_quantity = options.max_quantity;\n }\n if (options?.min_quantity !== undefined) {\n item.min_quantity = options.min_quantity;\n }\n}\n\nexport function setCartItem(\n productId: string,\n variantId: string,\n quantity: number = 1,\n options?: CartAddOptions\n): void {\n if (!productId || !variantId) {\n throw new CartError('product_id and variant_id are required');\n }\n\n const normalizedQuantity = normalizeQuantity(quantity);\n if (normalizedQuantity < 1) {\n throw new CartError('quantity must be at least 1');\n }\n\n const cart = getCart();\n const lineId = computeCartLineId({\n product_id: productId,\n variant_id: variantId,\n addons: options?.addons,\n custom_fields: options?.custom_fields,\n price_variant_id: options?.price_variant_id,\n price_data: options?.price_data,\n pay_what_you_want_price: options?.pay_what_you_want_price,\n });\n\n // Buy-now / replace semantics: one visible line per (product_id, variant_id). Drop any prior\n // line_ids for that pair so a config change (addons, price_data) does not leave a stale sibling.\n for (let index = cart.length - 1; index >= 0; index -= 1) {\n if (cart[index].product_id === productId && cart[index].variant_id === variantId) {\n cart.splice(index, 1);\n }\n }\n\n const pushed: CartItem = {\n line_id: lineId,\n product_id: productId,\n variant_id: variantId,\n quantity: normalizedQuantity,\n addons: options?.addons,\n custom_fields: options?.custom_fields,\n price_variant_id: options?.price_variant_id,\n price_data: options?.price_data,\n pay_what_you_want_price: options?.pay_what_you_want_price,\n title: options?.title,\n variant_title: options?.variant_title,\n image_url: options?.image_url,\n addon_labels: options?.addon_labels,\n max_quantity: options?.max_quantity,\n min_quantity: options?.min_quantity,\n };\n clampQuantityToBounds(pushed);\n cart.push(pushed);\n\n writeCart(cart);\n}\n\n/**\n * Patch one cart line.\n *\n * TRI-STATE BOUNDS: `min_quantity`/`max_quantity` accept `null` to DELETE the\n * stored bound — see {@link CartItemUpdate}. `undefined` (or an absent key)\n * leaves it alone, which is why a removed ceiling needs its own spelling.\n *\n * NO-OP UPDATES DO NOT WRITE. An update that leaves the cart byte-identical\n * returns without touching storage: no metadata bump, no `version` increment,\n * and — because the storage write is what other tabs observe — no `storage`\n * event. Writing anyway made an ineffective heal indistinguishable from a real\n * cart change, and two tabs healing the same line could hand the event back and\n * forth indefinitely. Line-shape healing of a legacy stored row is NOT this\n * function's job: `normalizeCartItems` clamps and repairs on every READ, which\n * is the chokepoint every access already flows through.\n */\nexport function updateCartItem(\n lineId: string,\n updates: CartItemUpdate\n): void {\n const cart = getCart();\n const normalizedLineId = lineId.trim();\n if (!normalizedLineId) {\n throw new CartError('line_id is required');\n }\n\n const index = cart.findIndex((item) => item.line_id === normalizedLineId);\n\n if (index < 0) {\n throw new CartError('Item not found in cart');\n }\n\n // The exact bytes the result is compared against, taken BEFORE any mutation.\n const before = JSON.stringify(cart);\n\n if (updates.quantity !== undefined) {\n const normalizedQuantity = normalizeQuantity(updates.quantity);\n if (normalizedQuantity < 1) {\n cart.splice(index, 1);\n writeCart(cart);\n return;\n }\n cart[index].quantity = normalizedQuantity;\n }\n\n if (updates.addons !== undefined) {\n cart[index].addons = updates.addons;\n }\n\n if (updates.custom_fields !== undefined) {\n cart[index].custom_fields = updates.custom_fields;\n }\n\n if (updates.price_variant_id !== undefined) {\n cart[index].price_variant_id = updates.price_variant_id;\n }\n if (updates.price_data !== undefined) {\n cart[index].price_data = updates.price_data;\n }\n if (updates.pay_what_you_want_price !== undefined) {\n cart[index].pay_what_you_want_price = updates.pay_what_you_want_price;\n }\n // Tri-state: `null` is the merchant's bound being REMOVED, and it has to\n // delete the stored key — a bound that can only be raised and lowered but\n // never cleared outlives the limit it describes.\n if (updates.max_quantity !== undefined) {\n if (updates.max_quantity === null) delete cart[index].max_quantity;\n else cart[index].max_quantity = updates.max_quantity;\n }\n if (updates.min_quantity !== undefined) {\n if (updates.min_quantity === null) delete cart[index].min_quantity;\n else cart[index].min_quantity = updates.min_quantity;\n }\n clampQuantityToBounds(cart[index]);\n\n // Pricing and configuration fields are part of a cart line's identity.\n // Recompute after every update and merge if the new identity already exists.\n const nextLineId = computeCartLineId(cart[index]);\n const duplicateIndex = cart.findIndex((item, itemIndex) => itemIndex !== index && item.line_id === nextLineId);\n if (duplicateIndex >= 0) {\n cart[duplicateIndex].quantity += cart[index].quantity;\n clampQuantityToBounds(cart[duplicateIndex]);\n cart.splice(index, 1);\n } else {\n cart[index].line_id = nextLineId;\n }\n\n // Nothing moved: writing would bump `version`/`last_modified` and emit a\n // storage event that says the cart changed when it did not.\n if (JSON.stringify(cart) === before) return;\n\n writeCart(cart);\n}\n\nexport function removeFromCart(lineId: string): void {\n const normalizedLineId = lineId.trim();\n if (!normalizedLineId) {\n throw new CartError('line_id is required');\n }\n\n const cart = getCart();\n const filtered = cart.filter((item) => item.line_id !== normalizedLineId);\n writeCart(filtered);\n}\n\n/**\n * Discards the cart entirely — and with it the proof that describes it.\n *\n * PAYMENT PATH. `latestQuoteToken` is evidence about a specific cart, and this\n * is the one mutation after which that cart does not exist in any form. Held\n * across the clear, the proof outlives its subject: a caller that clears and\n * re-adds (Buy Now REPLACES the cart) hands `/from-cart` a token bound to the\n * previous cart's hash, which is refused as `quote_token_stale` — a hand-off\n * dead-ended by a proof nobody asked for. And with no re-quote in between there\n * is nothing to replace it with, so the retry is refused identically.\n *\n * Only this path clears it. Every OTHER mutation turns one cart into another\n * cart, where a proof that no longer matches is the server's to refuse: it\n * answers `quote_token_stale`, the surfaces re-quote, and the buyer approves the\n * new total. Dropping the proof there instead would silently remove the approved\n * -total ceiling from a checkout that raced the re-quote, which is the failure\n * the token exists to prevent.\n */\nexport function clearCart(): void {\n removeItem(getStorageKey('cart'));\n removeItem(getStorageKey('meta'));\n clearCartCoupon();\n clearLatestQuoteToken();\n}\n\nexport function createCartBackup(): void {\n const cart = getCart();\n setItem(getStorageKey('cartBackup'), cart);\n const cartCode = getStoredCartCode();\n if (cartCode) {\n setItem(getStorageKey('couponBackup'), cartCode);\n } else {\n removeItem(getStorageKey('couponBackup'));\n }\n const metadata = getCartMetadata();\n if (metadata) {\n setItem(getStorageKey('metaBackup'), metadata);\n } else {\n const now = Date.now();\n setItem(getStorageKey('metaBackup'), {\n created_at: now,\n last_modified: now,\n version: 1,\n checksum: computeChecksum(cart),\n });\n }\n}\n\nexport function restoreCartFromBackup(): boolean {\n const backupRaw = getItem<unknown>(getStorageKey('cartBackup'));\n const backup = normalizeCartItems(backupRaw);\n const backupMeta = getItem<CartMetadata>(getStorageKey('metaBackup'));\n const backupCoupon = getItem<unknown>(getStorageKey('couponBackup'));\n\n if (backup && backup.length > 0) {\n setCartWithMetadata(backup, backupMeta);\n if (backupCoupon && typeof backupCoupon === 'object' && !Array.isArray(backupCoupon)) {\n const record = backupCoupon as Record<string, unknown>;\n const source = record.source === 'COUPON' || record.source === 'AFFILIATE'\n ? record.source\n : null;\n if (typeof record.code === 'string' && source) {\n setCartCoupon(record.code, source);\n } else {\n clearCartCoupon();\n }\n } else {\n clearCartCoupon();\n }\n return true;\n }\n\n return false;\n}\n\nexport function mergeBaskets(items: CartBasketMergeLine[]): CartItem[] {\n const cart = getCart();\n\n for (const incoming of items) {\n const productId = typeof incoming.product_id === 'string' ? incoming.product_id.trim() : '';\n const variantId = typeof incoming.variant_id === 'string' ? incoming.variant_id.trim() : '';\n if (!productId || !variantId) {\n continue;\n }\n\n let normalizedQuantity: number;\n try {\n normalizedQuantity = normalizeQuantity(incoming.quantity);\n } catch {\n continue;\n }\n\n if (normalizedQuantity < 1) {\n continue;\n }\n\n const mergedLine = ensureCartLineId({\n ...incoming,\n line_id: incoming.line_id ?? computeCartLineId(incoming),\n product_id: productId,\n variant_id: variantId,\n quantity: normalizedQuantity,\n });\n const index = cart.findIndex((item) => item.line_id === mergedLine.line_id);\n\n if (index >= 0) {\n cart[index].quantity = Math.max(cart[index].quantity, normalizedQuantity);\n clampQuantityToBounds(cart[index]);\n } else {\n clampQuantityToBounds(mergedLine);\n cart.push(mergedLine);\n }\n }\n\n writeCart(cart);\n return cart;\n}\n\nexport function moveBasketItem(\n fromProductId: string,\n fromVariantId: string,\n toProductId: string,\n toVariantId: string\n): void {\n const cart = getCart();\n const fromIndex = cart.findIndex(\n (item) => item.product_id === fromProductId && item.variant_id === fromVariantId\n );\n\n if (fromIndex < 0) {\n throw new CartError('Item not found in cart');\n }\n\n const [fromItem] = cart.splice(fromIndex, 1);\n const toLineId = computeCartLineId({\n ...fromItem,\n product_id: toProductId,\n variant_id: toVariantId,\n });\n const toIndex = cart.findIndex((item) => item.line_id === toLineId);\n\n if (toIndex >= 0) {\n cart[toIndex].quantity += fromItem.quantity;\n clampQuantityToBounds(cart[toIndex]);\n } else {\n const moved = ensureCartLineId({\n ...fromItem,\n product_id: toProductId,\n variant_id: toVariantId,\n line_id: toLineId,\n });\n clampQuantityToBounds(moved);\n cart.push(moved);\n }\n\n writeCart(cart);\n}\n\nexport function validateCartIntegrity(): boolean {\n const cart = getCart();\n const metadata = getCartMetadata();\n const checksum = computeChecksum(cart);\n\n if (!metadata) {\n setCartWithMetadata(cart, null);\n return true;\n }\n\n return metadata.checksum === checksum;\n}\n\nexport function getCartStats(): CartStats {\n const cart = getCart();\n const integrityValid = validateCartIntegrity();\n const metadata = getCartMetadata();\n const backup = getItem<CartItem[]>(getStorageKey('cartBackup')) ?? [];\n const hasCompletePriceSnapshots =\n cart.length > 0 &&\n cart.every((item) => typeof item.price_data?.unit_price === 'number');\n const totalPrice = cart.reduce((sum, item) => {\n const unitPrice = item.price_data?.unit_price ?? 0;\n return sum + roundPayableAmount(unitPrice * item.quantity);\n }, 0);\n\n return {\n item_count: cart.length,\n total_quantity: cart.reduce((sum, item) => sum + item.quantity, 0),\n last_modified: metadata?.last_modified ?? 0,\n version: metadata?.version ?? 0,\n has_backup: backup.length > 0,\n integrity_valid: integrityValid,\n total_price: roundPayableAmount(totalPrice),\n total_price_is_estimate: cart.length > 0 && !hasCompletePriceSnapshots,\n };\n}\n\nexport function getCartPayload(coupon?: string): CartPayload {\n const config = getConfig();\n const normalizedCoupon = normalizeCouponCode(coupon) ?? getCartCoupon() ?? undefined;\n return {\n store_slug: config.storeSlug,\n items: getCart(),\n coupon: normalizedCoupon,\n };\n}\n\n/**\n * The ambient referral code checkout() will submit as `affiliate_code`.\n *\n * Read exactly like checkout()'s normalizeAffiliateCode ambient branch: the\n * referral code the cart itself carries (source `AFFILIATE`) takes precedence\n * over the stored `?ref=` attribution. Sending it with the quote is what makes\n * the displayed total equal the amount the invoice will charge — without it a\n * cart holding both a coupon and a `?ref=` attribution quotes high.\n */\nfunction getAmbientAffiliateCodeForQuote(): string | null {\n const storedCode = getCartCoupon();\n const storedSource = getCartCouponSource();\n if (storedSource === 'AFFILIATE' && storedCode) {\n return storedCode.trim().toLowerCase();\n }\n return getAffiliateCode();\n}\n\n/**\n * The proof from the most recent successful quote, held in memory only.\n *\n * Module-scoped rather than persisted: the token is evidence about a cart as\n * it was priced moments ago, and a stale one from a previous page load is\n * simply ignored by the server. Not exported as public API — `checkout()`\n * reads it, callers do not have to know it exists.\n */\nlet latestQuoteToken: string | null = null;\n\n/**\n * Which quote call the held token belongs to.\n *\n * Quote responses settle in ARRIVAL order, not request order: two overlapping\n * `quoteCart` calls (cart A, then cart A+B) can answer with the OLDER one last,\n * and the token stored is then evidence about a cart the buyer no longer has.\n *\n * That is not a mispricing — `/from-cart` binds the token to a hash of the cart\n * content, currency, shop and submitted codes (`isCartQuoteTokenApplicable`),\n * so a superseded token simply fails to apply and is treated as ABSENT, and the\n * proof is a one-directional CEILING that can never lower a price. What it\n * costs is the ceiling itself: the buyer silently loses the protection for the\n * rest of that checkout. Keeping the newest call's answer is what keeps the\n * proof present for the cart actually on screen.\n */\nlet quoteSequence = 0;\n\n/** @internal — read by checkout(); exported only across module boundaries. */\nexport function getLatestQuoteToken(): string | null {\n return latestQuoteToken;\n}\n\n/** @internal — test seam and cart-reset hook. */\nexport function clearLatestQuoteToken(): void {\n latestQuoteToken = null;\n // A quote already in flight must not resurrect the proof this cleared.\n quoteSequence += 1;\n}\n\nexport async function quoteCart(coupon?: string, currency?: string) {\n const sequence = (quoteSequence += 1);\n const payload = getCartPayload(coupon);\n const normalizedCurrency = normalizeRequestedCurrency(currency)\n ?? getRequestedCurrencyFromLocation()\n ?? normalizeRequestedCurrency(getConfig().currency);\n const response = await post<CartQuote>('/v1/storefront/cart/quote', {\n shop_slug: payload.store_slug,\n cart: payload.items,\n coupon: payload.coupon,\n affiliate_code: getAmbientAffiliateCodeForQuote() ?? undefined,\n currency: normalizedCurrency ?? undefined,\n });\n\n // Only a successful quote replaces the held proof — a failed quote must not\n // clear a still-valid one.\n //\n // A SUCCESSFUL quote that carries no token clears it, rather than leaving the\n // previous one in place. The proof is evidence about one specific priced\n // cart, and `/from-cart` refuses a submitted proof it cannot apply\n // (`quote_token_stale` / `_invalid`) instead of ignoring it. So a held token\n // that this quote did not reissue is not a harmless leftover: every later\n // `checkout()` submits it, is refused, and re-quoting never helps because a\n // tokenless answer used to leave it untouched — a dead end the buyer cannot\n // escape from inside the cart.\n //\n // And only the NEWEST call may replace it: a slower earlier quote answering\n // last would otherwise overwrite the current cart's proof with one bound to a\n // cart hash that no longer exists.\n if (sequence !== quoteSequence) return response;\n if (response.success) {\n latestQuoteToken = typeof response.data?.quote_token === 'string'\n ? response.data.quote_token\n : null;\n }\n\n return response;\n}\n\nexport function serializeCart(coupon?: string): string {\n const payload = getCartPayload(coupon);\n const json = JSON.stringify(payload);\n // UTF-8 safe Base64: encodeURIComponent converts to UTF-8, unescape converts percent-encoding to bytes\n if (typeof btoa !== 'undefined') {\n return btoa(unescape(encodeURIComponent(json)));\n }\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(json, 'utf8').toString('base64');\n }\n throw new CartError('Base64 encoding is not available in this environment');\n}\n","/**\n * Checkout Module\n *\n * Creates invoice via backend API and redirects to hosted checkout page.\n * All checkout flows go through: checkout.shoppex.io/invoice/{invoiceId}\n */\n\nimport { getConfig } from '../core/config';\nimport { post } from '../core/client';\nimport { getCart, getCartCoupon, getCartCouponSource, createCartBackup, clearCart, getLatestQuoteToken } from './cart';\nimport { getAffiliateCode, trackAffiliateEvent } from './affiliates';\nimport type { CartItem, CartAddon } from '../types/cart';\nimport type { ApiChallenge, BuyerRewards } from '../types/api';\nimport {\n findRemainingProductRedirectPlaceholders,\n isSafeHttpsRedirectTemplateUrl,\n} from '@shoppex/contracts/redirect-link-template';\nimport {\n getRequestedCurrencyFromLocation,\n normalizeRequestedCurrency,\n} from '../utils/requested-currency';\n\nexport interface CheckoutOptions {\n autoRedirect?: boolean;\n locale?: string;\n email?: string;\n coupon?: string;\n currency?: string;\n /**\n * Absolute HTTPS URL used after a completed purchase when the product does\n * not define its own redirect. This is persisted on the invoice, so each\n * sales channel can provide its own return destination.\n */\n redirectUrl?: string;\n /**\n * A Cloudflare Turnstile proof for the `storefront_checkout` action.\n *\n * Normally omitted. When checkout returns a challenge, mount the hosted\n * broker with `mountCheckoutChallenge()` and retry with its renewed proof.\n * The proof is transport-only and does not change the checkout intent or its\n * idempotency key.\n */\n turnstileToken?: string;\n /**\n * Referral (affiliate) code to submit, as a tri-state:\n *\n * - `undefined` — the SDK resolves it from storage (cart-applied referral\n * code first, then the ambient `?ref=` attribution).\n * - `''` — explicitly none: submit no referral code and do NOT re-read\n * storage. This is how a caller pins \"quoted WITHOUT a referral\"; without\n * it a code captured between the quote and the submit would be applied to\n * a total the buyer never saw.\n * - non-empty — pinned: submit exactly this code.\n *\n * `referralCode` is an alias and follows the same rules; `affiliateCode`\n * wins when both are present.\n */\n affiliateCode?: string;\n /** Alias of {@link CheckoutOptions.affiliateCode}, same tri-state. */\n referralCode?: string;\n customerCheckoutPath?: '/dashboard/api/checkout';\n /**\n * The cart this hand-off was approved FOR, as `JSON.stringify(getCart())`.\n *\n * PAYMENT PATH. A caller that writes the cart and reads it back before\n * checking out (Buy Now, which replaces the cart, is the sharp case) verifies\n * a cart it read at one moment, while these functions read storage again on\n * their way into the request — and localStorage is shared with every other\n * tab on the domain. A write landing in that gap is billed without ever\n * having passed the caller's verification.\n *\n * The caller cannot close that itself: any check it makes is one more read\n * BEFORE this one. Pinning the expected bytes moves the comparison to the\n * only place it can be conclusive — against the exact cart the call is about\n * to POST. A mismatch refuses before anything is created or sent.\n *\n * Honoured identically by BOTH invoice-creating entry points, `checkout()`\n * and `buildCheckoutUrl()` — they hit the same endpoint and create the same\n * invoice, so a pin that held on one and not the other would be a promise\n * the caller could not rely on. Only the refusal shape differs, following\n * each function's own success shape: `checkout()` returns\n * `{ success: false }`, `buildCheckoutUrl()` throws.\n *\n * Optional and additive: omitted, nothing changes, and the server is not\n * involved either way.\n */\n expectedCart?: string;\n}\n\nexport interface CheckoutResult {\n success: boolean;\n redirectUrl?: string;\n invoiceId?: string;\n rewards?: BuyerRewards | null;\n message?: string;\n /**\n * The server's machine-readable refusal identifier when the checkout was\n * refused, e.g. `errors.checkout.price_increased_since_quote` or\n * `errors.checkout.affiliate_code_not_applicable`. Branch on this rather\n * than on `message`, which is localized display copy.\n *\n * The quote-proof family — `errors.checkout.quote_token_invalid`,\n * `errors.checkout.quote_token_expired`, `errors.checkout.quote_token_stale`\n * — says the proof this call submitted could not be honoured: not ours, past\n * its window, or priced for a cart/currency/codes that have since moved. The\n * server refuses rather than pricing without the ceiling, so the caller's\n * response is always the same: `quoteCart()` again, show the buyer the new\n * total, and only then retry. A retry with the same stale token is refused\n * identically.\n *\n * Absent for failures the server never named (transport, timeout, an empty\n * cart caught client-side).\n */\n code?: string;\n /**\n * Human-verification challenge required before creating the invoice. Mount\n * it with `mountCheckoutChallenge()`, then retry with its proof as\n * `turnstileToken`.\n */\n challenge?: ApiChallenge;\n}\n\n/**\n * Typed refusal from {@link buildCheckoutUrl}. The function keeps its existing\n * throw-based contract while exposing a server-requested human-verification\n * challenge so callers can render it and retry with `turnstileToken`.\n */\nexport class CheckoutCreateError extends Error {\n readonly challenge?: ApiChallenge;\n readonly code?: string;\n readonly status?: number;\n\n constructor(message: string, options: {\n challenge?: ApiChallenge;\n code?: string;\n status?: number;\n } = {}) {\n super(message);\n this.name = 'CheckoutCreateError';\n this.challenge = options.challenge;\n this.code = options.code;\n this.status = options.status;\n Object.setPrototypeOf(this, CheckoutCreateError.prototype);\n }\n}\n\ninterface CheckoutApiResponse {\n invoiceId?: string;\n checkoutUrl?: string;\n invoice_id?: string;\n checkout_url?: string;\n uniqid?: string;\n url?: string;\n url_branded?: string;\n rewards?: BuyerRewards | null;\n invoice?: {\n invoiceId?: string;\n checkoutUrl?: string;\n invoice_id?: string;\n checkout_url?: string;\n uniqid?: string;\n url?: string;\n url_branded?: string;\n rewards?: BuyerRewards | null;\n };\n}\n\ninterface NormalizedCheckoutData {\n invoiceId: string;\n checkoutUrl: string;\n rewards: BuyerRewards | null;\n}\n\nconst CHECKOUT_PREFILL_EMAIL_HASH_KEY = 'shoppex_prefill_email';\n\n/**\n * PAYMENT PATH. The single refusal copy for a broken `expectedCart` pin, shared\n * by every entry point that honours the pin so the buyer reads the same\n * sentence whichever one the theme calls. One literal, because two copies drift\n * and the difference would be visible to buyers on the same storefront.\n */\nconst CART_CHANGED_MESSAGE = 'Your cart changed while checkout was starting. Please review it and try again.';\n\n/**\n * PAYMENT PATH. True when the caller pinned a cart and storage no longer holds\n * it — see `CheckoutOptions.expectedCart`. Compared against the exact array the\n * caller is about to bill, which is the only comparison that is conclusive:\n * anything the caller checks itself is one more read BEFORE the read that\n * feeds the request.\n *\n * An omitted pin is not a mismatch. The pin is additive, and a caller that\n * never made the promise is left exactly as it was.\n */\nfunction isExpectedCartMismatch(cart: CartItem[], expectedCart: string | undefined): boolean {\n return expectedCart !== undefined && JSON.stringify(cart) !== expectedCart;\n}\n\nfunction normalizeCoupon(coupon: string | null | undefined): string | null {\n const normalized = coupon?.trim();\n return normalized ? normalized : null;\n}\n\nfunction normalizeEmail(email: string | null | undefined): string | null {\n const normalized = email?.trim();\n return normalized ? normalized : null;\n}\n\nfunction resolvePostPurchaseRedirectUrl(\n redirectUrl: string | null | undefined,\n): { value: string | null; error: null } | { value: null; error: string } {\n const normalized = redirectUrl?.trim();\n if (!normalized) {\n return { value: null, error: null };\n }\n if (!isSafeHttpsRedirectTemplateUrl(normalized)) {\n return { value: null, error: 'redirectUrl must be an absolute HTTPS URL.' };\n }\n if (findRemainingProductRedirectPlaceholders(normalized).length > 0) {\n return { value: null, error: 'redirectUrl must not contain template placeholders.' };\n }\n return { value: normalized, error: null };\n}\n\ninterface PendingCheckoutCreate {\n fingerprint: string;\n key: string;\n}\n\nconst pendingCheckoutCreates = new Map<string, PendingCheckoutCreate>();\n\nfunction acquireCheckoutCreateIdempotency(\n requestTarget: { endpoint: string; baseUrl?: string },\n createIntent: object,\n): PendingCheckoutCreate {\n const fingerprint = JSON.stringify({\n endpoint: requestTarget.endpoint,\n baseUrl: requestTarget.baseUrl ?? null,\n createIntent,\n });\n const existingAttempt = pendingCheckoutCreates.get(fingerprint);\n if (existingAttempt) {\n return existingAttempt;\n }\n\n const attempt = {\n fingerprint,\n key: globalThis.crypto.randomUUID(),\n };\n pendingCheckoutCreates.set(fingerprint, attempt);\n return attempt;\n}\n\nfunction releaseCheckoutCreateIdempotency(\n attempt: PendingCheckoutCreate,\n outcomeDefinitive: boolean,\n): void {\n // Only a parsed server refusal or a validated success makes the outcome\n // definitive. A rejected fetch, timeout, truncated body, or malformed body\n // may follow a committed create, so the next identical intent replays it.\n if (outcomeDefinitive && pendingCheckoutCreates.get(attempt.fingerprint) === attempt) {\n pendingCheckoutCreates.delete(attempt.fingerprint);\n }\n}\n\nfunction resolveCustomerCheckoutRequestTarget(options: CheckoutOptions): {\n endpoint: string;\n baseUrl?: string;\n} {\n if (\n options.customerCheckoutPath === '/dashboard/api/checkout'\n && typeof window !== 'undefined'\n && typeof window.location?.origin === 'string'\n ) {\n return {\n endpoint: options.customerCheckoutPath,\n baseUrl: window.location.origin,\n };\n }\n\n return { endpoint: '/v1/storefront/invoices/from-cart' };\n}\n\nfunction resolveRequestedCheckoutCurrency(options: CheckoutOptions): string | null {\n return normalizeRequestedCurrency(options.currency)\n ?? getRequestedCurrencyFromLocation()\n ?? normalizeRequestedCurrency(getConfig().currency);\n}\n\nfunction normalizeCheckoutFailureMessage(rawMessage: string | null | undefined): string {\n const message = rawMessage?.trim() ?? '';\n if (!message) {\n return 'Checkout failed. Please try again.';\n }\n\n if (isStaleCartProductError(message)) {\n return 'Your cart is outdated. Please add the products again.';\n }\n\n const httpMatch = message.match(/^HTTP\\s+(\\d{3})(?::\\s*(.*))?$/i);\n if (httpMatch) {\n const status = Number(httpMatch[1]);\n const detail = httpMatch[2]?.trim();\n\n if (detail && detail.length > 0) {\n return `Checkout failed: ${detail}`;\n }\n\n if (status >= 500) {\n return 'Checkout is temporarily unavailable. Please try again.';\n }\n\n if (status === 400) {\n return 'Checkout failed. Please check your details and try again.';\n }\n\n if (status === 401 || status === 403) {\n return 'Checkout is currently unavailable for this request.';\n }\n\n return 'Checkout failed. Please try again.';\n }\n\n if (/^internal server error$/i.test(message)) {\n return 'Checkout is temporarily unavailable. Please try again.';\n }\n\n return message;\n}\n\nfunction isStaleCartProductError(rawMessage: string | null | undefined): boolean {\n const message = rawMessage?.trim().toLowerCase() ?? '';\n if (!message) {\n return false;\n }\n\n return message.includes('product not found')\n || message.includes('product not available')\n || message.includes('products are no longer available')\n || message.includes('outdated product');\n}\n\nfunction validateCheckoutUrl(\n checkoutUrl: string,\n checkoutBaseUrl: string | undefined,\n expectedInvoiceId?: string\n): string | null {\n const expectedBaseUrl = checkoutBaseUrl?.trim();\n if (!expectedBaseUrl) {\n return null;\n }\n\n try {\n const parsedCheckoutUrl = new URL(checkoutUrl);\n const parsedExpectedBaseUrl = new URL(expectedBaseUrl);\n\n if (parsedCheckoutUrl.origin !== parsedExpectedBaseUrl.origin) {\n return null;\n }\n\n const normalizedPath = parsedCheckoutUrl.pathname.replace(/\\/+$/, '');\n const normalizedBasePath = parsedExpectedBaseUrl.pathname.replace(/\\/+$/, '');\n const expectedInvoicePath = `${normalizedBasePath}/invoice/`.replace(/\\/{2,}/g, '/');\n if (!normalizedPath.startsWith(expectedInvoicePath)) {\n return null;\n }\n\n const invoiceIdSegment = normalizedPath.slice(expectedInvoicePath.length);\n if (!invoiceIdSegment || invoiceIdSegment.includes('/')) {\n return null;\n }\n\n if (expectedInvoiceId) {\n const normalizedExpectedInvoiceId = expectedInvoiceId.trim();\n const invoiceIdFromUrl = decodeURIComponent(invoiceIdSegment);\n if (!normalizedExpectedInvoiceId || invoiceIdFromUrl !== normalizedExpectedInvoiceId) {\n return null;\n }\n }\n\n return parsedCheckoutUrl.toString();\n } catch {\n return null;\n }\n}\n\nfunction buildCheckoutUrlFromInvoiceId(\n checkoutBaseUrl: string | undefined,\n invoiceId: string\n): string | null {\n const normalizedBaseUrl = checkoutBaseUrl?.trim();\n if (!normalizedBaseUrl) {\n return null;\n }\n\n try {\n const baseUrl = new URL(normalizedBaseUrl);\n const basePath = baseUrl.pathname.replace(/\\/+$/, '');\n baseUrl.pathname = `${basePath}/invoice/${encodeURIComponent(invoiceId)}`.replace(/\\/{2,}/g, '/');\n baseUrl.search = '';\n baseUrl.hash = '';\n return baseUrl.toString();\n } catch {\n return null;\n }\n}\n\nfunction appendCheckoutUrlOptions(\n checkoutUrl: string,\n options: { email?: string | null; locale?: string },\n): string {\n const normalizedEmail = normalizeEmail(options.email);\n const normalizedLocale = typeof options.locale === 'string' ? options.locale.trim() : '';\n\n if (!normalizedEmail && !normalizedLocale) {\n return checkoutUrl;\n }\n\n try {\n const parsedCheckoutUrl = new URL(checkoutUrl);\n if (normalizedLocale) {\n parsedCheckoutUrl.searchParams.set('locale', normalizedLocale);\n }\n if (normalizedEmail) {\n const hashParams = new URLSearchParams(parsedCheckoutUrl.hash.startsWith('#')\n ? parsedCheckoutUrl.hash.slice(1)\n : parsedCheckoutUrl.hash);\n hashParams.set(CHECKOUT_PREFILL_EMAIL_HASH_KEY, normalizedEmail);\n parsedCheckoutUrl.hash = hashParams.toString();\n }\n return parsedCheckoutUrl.toString();\n } catch {\n return checkoutUrl;\n }\n}\n\nfunction normalizeCheckoutResponse(\n response: CheckoutApiResponse | undefined,\n checkoutBaseUrl: string | undefined\n): NormalizedCheckoutData | null {\n const nestedInvoice = response?.invoice;\n const invoiceId = response?.invoiceId?.trim()\n || response?.invoice_id?.trim()\n || response?.uniqid?.trim()\n || nestedInvoice?.invoiceId?.trim()\n || nestedInvoice?.invoice_id?.trim()\n || nestedInvoice?.uniqid?.trim();\n let checkoutUrl = response?.checkoutUrl?.trim()\n || response?.checkout_url?.trim()\n || response?.url_branded?.trim()\n || response?.url?.trim()\n || nestedInvoice?.checkoutUrl?.trim()\n || nestedInvoice?.checkout_url?.trim()\n || nestedInvoice?.url_branded?.trim()\n || nestedInvoice?.url?.trim();\n\n if (!checkoutUrl && invoiceId && nestedInvoice) {\n checkoutUrl = buildCheckoutUrlFromInvoiceId(checkoutBaseUrl, invoiceId) ?? undefined;\n }\n\n if (!invoiceId || !checkoutUrl) {\n return null;\n }\n\n return {\n invoiceId,\n checkoutUrl,\n rewards: response?.rewards ?? nestedInvoice?.rewards ?? null,\n };\n}\n\nfunction resolveCheckoutOptions(\n couponOrOptions?: string | CheckoutOptions,\n options?: CheckoutOptions\n): CheckoutOptions {\n if (typeof couponOrOptions === 'string') {\n return {\n ...options,\n coupon: couponOrOptions,\n };\n }\n\n return couponOrOptions ?? options ?? {};\n}\n\nfunction normalizeAffiliateCode(options: CheckoutOptions, storedAffiliateCode: string | null): string | null {\n const explicitCode = options.affiliateCode ?? options.referralCode;\n // Tri-state, mirroring `coupon`: an explicit empty string means \"none\" and\n // must suppress the storage re-read. Only `undefined` lets the SDK resolve\n // the code itself — otherwise a referral captured after the quote was\n // rendered would be applied to a total the buyer never saw.\n if (typeof explicitCode === 'string') {\n const normalized = explicitCode.trim().toLowerCase();\n return normalized.length > 0 ? normalized : null;\n }\n\n return storedAffiliateCode?.trim().toLowerCase() ?? getAffiliateCode();\n}\n\nfunction resolveCheckoutCodes(options: CheckoutOptions): {\n coupon: string | null;\n affiliateCode: string | null;\n} {\n const storedCode = getCartCoupon();\n const storedSource = getCartCouponSource();\n const coupon = options.coupon === undefined\n ? (storedSource === 'COUPON' ? storedCode : null)\n : normalizeCoupon(options.coupon);\n const storedAffiliateCode = options.coupon === undefined && storedSource === 'AFFILIATE'\n ? storedCode\n : null;\n\n return {\n coupon,\n affiliateCode: normalizeAffiliateCode(options, storedAffiliateCode),\n };\n}\n\nfunction mapCartItemsForApi(items: CartItem[]) {\n const normalizeVariantIdForApi = (value: string | null | undefined): string | null => {\n const normalized = value?.trim();\n if (!normalized) return null;\n // Themes use \"default\" as a sentinel for \"no variant selected\".\n // Backend expects `null` in that case.\n if (normalized.toLowerCase() === 'default') return null;\n return normalized;\n };\n\n return items.map((item) => ({\n product_id: item.product_id,\n variant_id: normalizeVariantIdForApi(item.variant_id),\n quantity: item.quantity,\n addons: item.addons?.map((a: CartAddon) => ({ id: a.id, quantity: a.quantity ?? 1 })),\n custom_fields: item.custom_fields,\n price_variant_id: item.price_variant_id || null,\n pay_what_you_want_price: item.pay_what_you_want_price,\n }));\n}\n\nexport async function checkout(\n couponOrOptions?: string | CheckoutOptions,\n options?: CheckoutOptions\n): Promise<CheckoutResult> {\n const resolvedOptions = resolveCheckoutOptions(couponOrOptions, options);\n const { autoRedirect = true, email } = resolvedOptions;\n const checkoutCodes = resolveCheckoutCodes(resolvedOptions);\n const normalizedCoupon = checkoutCodes.coupon;\n const normalizedEmail = normalizeEmail(email);\n const normalizedAffiliateCode = checkoutCodes.affiliateCode;\n const requestedCurrency = resolveRequestedCheckoutCurrency(resolvedOptions);\n const postPurchaseRedirect = resolvePostPurchaseRedirectUrl(resolvedOptions.redirectUrl);\n\n const cart = getCart();\n if (cart.length === 0) {\n return {\n success: false,\n message: 'Cart is empty',\n };\n }\n\n // PAYMENT PATH. The cart the caller approved, compared against the cart this\n // call will actually POST — see `CheckoutOptions.expectedCart`. Refused\n // before the backup and before the request, so a cart that changed under the\n // caller is never billed and nothing is left half-done.\n if (isExpectedCartMismatch(cart, resolvedOptions.expectedCart)) {\n return {\n success: false,\n message: CART_CHANGED_MESSAGE,\n };\n }\n if (postPurchaseRedirect.error) {\n return {\n success: false,\n message: postPurchaseRedirect.error,\n };\n }\n\n createCartBackup();\n\n const config = getConfig();\n const checkoutRequestTarget = resolveCustomerCheckoutRequestTarget(resolvedOptions);\n\n const createIntent = {\n shop_slug: config.storeSlug,\n cart: mapCartItemsForApi(cart),\n email: normalizedEmail,\n coupon: normalizedCoupon,\n currency: requestedCurrency,\n return_url: postPurchaseRedirect.value ?? undefined,\n affiliate_code: normalizedAffiliateCode,\n // Proof of the total the buyer approved, from the last quoteCart(). Sent\n // automatically so the server can refuse an invoice priced above it.\n // Undefined when nothing has been quoted this session — the endpoint\n // treats that exactly as an older SDK.\n quote_token: getLatestQuoteToken() ?? undefined,\n };\n const createCommand = {\n ...createIntent,\n turnstile_token: resolvedOptions.turnstileToken?.trim() || undefined,\n };\n const createAttempt = acquireCheckoutCreateIdempotency(checkoutRequestTarget, createIntent);\n const response = await post<CheckoutApiResponse>(\n checkoutRequestTarget.endpoint,\n createCommand,\n {\n retries: 0,\n baseUrl: checkoutRequestTarget.baseUrl,\n headers: {\n 'X-Idempotency-Key': createAttempt.key,\n },\n }\n );\n if (!response.success || !response.data) {\n releaseCheckoutCreateIdempotency(createAttempt, response.responseDefinitive === true);\n if (isStaleCartProductError(response.message)) {\n clearCart();\n }\n return {\n success: false,\n message: normalizeCheckoutFailureMessage(response.message),\n // The server's machine-readable refusal, preserved so callers can react\n // to e.g. `errors.checkout.price_increased_since_quote` without matching\n // localized copy.\n ...(response.code ? { code: response.code } : {}),\n ...(response.challenge ? { challenge: response.challenge } : {}),\n };\n }\n\n const checkoutData = normalizeCheckoutResponse(response.data, config.checkoutBaseUrl);\n if (!checkoutData) {\n return {\n success: false,\n message: 'Failed to create invoice',\n };\n }\n\n const { invoiceId } = checkoutData;\n const safeCheckoutUrl = validateCheckoutUrl(\n checkoutData.checkoutUrl,\n config.checkoutBaseUrl,\n invoiceId\n );\n if (!safeCheckoutUrl) {\n return {\n success: false,\n message: 'Failed to create invoice',\n };\n }\n\n releaseCheckoutCreateIdempotency(createAttempt, true);\n\n // One checkout_started per created invoice: dedupes accidental duplicate\n // sends without dropping a buyer's genuine second order in the same session.\n void trackAffiliateEvent('checkout_started', {\n code: normalizedAffiliateCode,\n dedupeKey: `inv:${invoiceId}`,\n });\n\n const checkoutUrlWithPrefill = appendCheckoutUrlOptions(safeCheckoutUrl, {\n email: normalizedEmail,\n locale: resolvedOptions.locale ?? config.locale,\n });\n\n if (autoRedirect) {\n if (typeof window !== 'undefined' && window?.location) {\n window.location.href = checkoutUrlWithPrefill;\n clearCart();\n }\n }\n\n return {\n success: true,\n redirectUrl: checkoutUrlWithPrefill,\n invoiceId,\n rewards: checkoutData.rewards,\n };\n}\n\n/**\n * Build checkout URL by creating invoice first.\n * Returns the checkout URL for the created invoice.\n *\n * PAYMENT PATH. \"Build a URL\" names what this returns, not a lighter way to\n * price a cart: it POSTs the same invoice-creating endpoint as `checkout()` and\n * bills whatever storage holds when it reads. It therefore honours\n * `CheckoutOptions.expectedCart` on exactly the same terms — a pinned cart that\n * moved is refused, not invoiced.\n *\n * A refusal throws, like every other refusal on this function: the success\n * shape is a URL string, so there is no in-band value that a caller could\n * mistake for one. The thrown message is the buyer-facing copy, identical to\n * the sentence `checkout()` returns, and callers that already handle the\n * `Cart is empty` throw handle this one unchanged.\n */\nexport async function buildCheckoutUrl(\n couponOrOptions?: string | CheckoutOptions,\n options?: CheckoutOptions\n): Promise<string> {\n const resolvedOptions = resolveCheckoutOptions(couponOrOptions, options);\n const { email } = resolvedOptions;\n const checkoutCodes = resolveCheckoutCodes(resolvedOptions);\n const normalizedCoupon = checkoutCodes.coupon;\n const normalizedEmail = normalizeEmail(email);\n const normalizedAffiliateCode = checkoutCodes.affiliateCode;\n const requestedCurrency = resolveRequestedCheckoutCurrency(resolvedOptions);\n const postPurchaseRedirect = resolvePostPurchaseRedirectUrl(resolvedOptions.redirectUrl);\n\n const cart = getCart();\n if (cart.length === 0) {\n throw new Error('Cart is empty');\n }\n\n // PAYMENT PATH. Same position `checkout()` puts it in: after the empty-cart\n // check and before anything is created or sent. This path has no cart backup\n // to write, so the request is the first side effect there is — refusing here\n // means a cart that changed under the caller never reaches the endpoint, and\n // the buyer's cart is left exactly as the interfering write left it. It\n // matters most with no quote token in play, because then nothing downstream\n // carries an approved-total ceiling either.\n if (isExpectedCartMismatch(cart, resolvedOptions.expectedCart)) {\n throw new Error(CART_CHANGED_MESSAGE);\n }\n if (postPurchaseRedirect.error) {\n throw new Error(postPurchaseRedirect.error);\n }\n\n const config = getConfig();\n const checkoutRequestTarget = resolveCustomerCheckoutRequestTarget(resolvedOptions);\n\n const createIntent = {\n shop_slug: config.storeSlug,\n cart: mapCartItemsForApi(cart),\n email: normalizedEmail,\n coupon: normalizedCoupon,\n currency: requestedCurrency,\n return_url: postPurchaseRedirect.value ?? undefined,\n affiliate_code: normalizedAffiliateCode,\n // Same invoice-creating endpoint as `checkout()`, so it carries the same\n // proof of the approved total. \"Build a URL\" describes what this returns\n // to the caller, not a different way to price a cart — omitting the\n // token here left a public path on which the server had nothing to check\n // the invoice against. Same optional semantics: undefined when nothing\n // was quoted this session.\n quote_token: getLatestQuoteToken() ?? undefined,\n };\n const createCommand = {\n ...createIntent,\n turnstile_token: resolvedOptions.turnstileToken?.trim() || undefined,\n };\n const createAttempt = acquireCheckoutCreateIdempotency(checkoutRequestTarget, createIntent);\n const response = await post<CheckoutApiResponse>(\n checkoutRequestTarget.endpoint,\n createCommand,\n {\n retries: 0,\n baseUrl: checkoutRequestTarget.baseUrl,\n headers: {\n 'X-Idempotency-Key': createAttempt.key,\n },\n }\n );\n if (!response.success || !response.data) {\n releaseCheckoutCreateIdempotency(createAttempt, response.responseDefinitive === true);\n if (isStaleCartProductError(response.message)) {\n clearCart();\n }\n throw new CheckoutCreateError(normalizeCheckoutFailureMessage(response.message), {\n ...(response.challenge ? { challenge: response.challenge } : {}),\n ...(response.code ? { code: response.code } : {}),\n ...(response.status !== undefined ? { status: response.status } : {}),\n });\n }\n const checkoutData = normalizeCheckoutResponse(response.data, config.checkoutBaseUrl);\n if (!checkoutData) {\n throw new Error('Failed to create invoice');\n }\n\n const safeCheckoutUrl = validateCheckoutUrl(\n checkoutData.checkoutUrl,\n config.checkoutBaseUrl,\n checkoutData.invoiceId\n );\n if (!safeCheckoutUrl) {\n throw new Error('Failed to create invoice');\n }\n\n releaseCheckoutCreateIdempotency(createAttempt, true);\n\n // Same funnel point as checkout(): both entry points create the invoice.\n void trackAffiliateEvent('checkout_started', {\n code: normalizedAffiliateCode,\n dedupeKey: `inv:${checkoutData.invoiceId}`,\n });\n\n return appendCheckoutUrlOptions(safeCheckoutUrl, {\n email: normalizedEmail,\n locale: resolvedOptions.locale ?? config.locale,\n });\n}\n\n/**\n * @deprecated Use buildCheckoutUrl instead.\n * Sync version is no longer supported as invoice creation requires API call.\n */\nexport function buildCheckoutUrlSync(): never {\n throw new Error('buildCheckoutUrlSync is deprecated. Use buildCheckoutUrl (async) instead.');\n}\n","import { getConfig } from '../core/config';\nimport type { ApiChallenge } from '../types/api';\n\nconst TURNSTILE_FRAME_MESSAGE_SOURCE = 'shoppex-turnstile';\nconst TURNSTILE_FRAME_MESSAGE_VERSION = 1;\n// The hosted broker posts `ready` immediately after Turnstile renders. Ten\n// seconds tolerates slow mobile networks while bounding a broken/CSP-blocked frame.\nconst TURNSTILE_FRAME_READY_TIMEOUT_MS = 10_000;\n\nexport interface CheckoutChallengeCallbacks {\n onSuccess(token: string): void;\n onExpired?(): void;\n onUnavailable?(): void;\n}\n\nexport interface CheckoutChallengeFrame {\n element: HTMLIFrameElement;\n dispose(): void;\n}\n\nfunction readFrameMessage(\n value: unknown,\n nonce: string,\n): { type: 'ready' | 'success' | 'expired' | 'timeout' | 'error'; token?: string } | null {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return null;\n const record = value as Record<string, unknown>;\n if (\n record.source !== TURNSTILE_FRAME_MESSAGE_SOURCE\n || record.version !== TURNSTILE_FRAME_MESSAGE_VERSION\n || record.nonce !== nonce\n || !['ready', 'success', 'expired', 'timeout', 'error'].includes(String(record.type))\n ) return null;\n if (record.type === 'success' && (typeof record.token !== 'string' || !record.token.trim())) {\n return null;\n }\n return {\n type: record.type as 'ready' | 'success' | 'expired' | 'timeout' | 'error',\n ...(typeof record.token === 'string' ? { token: record.token.trim() } : {}),\n };\n}\n\n/**\n * Mount the Shoppex-hosted Turnstile broker requested by a checkout refusal.\n *\n * The challenge always executes on the configured hosted-checkout origin, so\n * this works on arbitrary custom storefront domains without adding each one\n * to Cloudflare's widget hostname allowlist. Retry `checkout()` or\n * `buildCheckoutUrl()` with the token delivered to `onSuccess`.\n */\nexport function mountCheckoutChallenge(\n container: HTMLElement,\n challenge: ApiChallenge,\n callbacks: CheckoutChallengeCallbacks,\n): CheckoutChallengeFrame {\n if (challenge.provider !== 'turnstile' || !challenge.siteKey.trim()) {\n throw new Error('Checkout challenge is invalid.');\n }\n\n const win = container.ownerDocument.defaultView;\n if (!win) throw new Error('Checkout challenge requires a browser document.');\n\n const checkoutBaseUrl = getConfig().checkoutBaseUrl;\n const frameUrl = new URL('/turnstile', checkoutBaseUrl);\n if (frameUrl.protocol !== 'https:' && frameUrl.protocol !== 'http:') {\n throw new Error('Checkout base URL must use http or https.');\n }\n const nonce = win.crypto.randomUUID();\n frameUrl.searchParams.set('site_key', challenge.siteKey.trim());\n frameUrl.searchParams.set('nonce', nonce);\n\n const frame = container.ownerDocument.createElement('iframe');\n frame.src = frameUrl.toString();\n frame.title = 'Checkout verification';\n frame.referrerPolicy = 'no-referrer';\n frame.style.border = '0';\n frame.style.width = '100%';\n frame.style.height = '72px';\n\n let disposed = false;\n let ready = false;\n const readyTimeout = win.setTimeout(() => {\n if (!disposed && !ready) callbacks.onUnavailable?.();\n }, TURNSTILE_FRAME_READY_TIMEOUT_MS);\n const onMessage = (event: MessageEvent) => {\n if (\n disposed\n || event.origin !== frameUrl.origin\n || event.source !== frame.contentWindow\n ) return;\n const message = readFrameMessage(event.data, nonce);\n if (!message) return;\n ready = true;\n win.clearTimeout(readyTimeout);\n if (message.type === 'success') callbacks.onSuccess(message.token!);\n if (message.type === 'expired' || message.type === 'timeout') callbacks.onExpired?.();\n if (message.type === 'error') callbacks.onUnavailable?.();\n };\n const onFrameError = () => callbacks.onUnavailable?.();\n\n win.addEventListener('message', onMessage);\n frame.addEventListener('error', onFrameError, { once: true });\n container.appendChild(frame);\n\n return {\n element: frame,\n dispose() {\n if (disposed) return;\n disposed = true;\n win.clearTimeout(readyTimeout);\n win.removeEventListener('message', onMessage);\n frame.removeEventListener('error', onFrameError);\n frame.remove();\n },\n };\n}\n","/**\n * Coupons Module\n *\n * Coupon validation before checkout.\n */\n\nimport { post } from '../core/client';\nimport { getShopId } from '../core/config';\nimport { getStore } from './store';\nimport { getCart } from './cart';\nimport type { SDKResponse, CouponValidation, CouponValidationOptions } from '../types';\n\nasync function resolveShopId(): Promise<string | null> {\n const cachedShopId = getShopId();\n if (cachedShopId) {\n return cachedShopId;\n }\n\n const storeResult = await getStore();\n if (!storeResult.success || !storeResult.data?.id) {\n return null;\n }\n\n return storeResult.data.id;\n}\n\nexport async function validateCoupon(\n code: string,\n productOrOptions?: string | CouponValidationOptions\n): Promise<SDKResponse<CouponValidation>> {\n const trimmedCode = code.trim();\n if (!trimmedCode) {\n return {\n success: false,\n message: 'Coupon code is required',\n };\n }\n\n const payload: Record<string, unknown> = {\n code: trimmedCode,\n };\n const productId = typeof productOrOptions === 'string'\n ? productOrOptions\n : productOrOptions?.productId;\n const variantId = typeof productOrOptions === 'string'\n ? undefined\n : productOrOptions?.variantId;\n\n if (variantId && !productId) {\n return {\n success: false,\n message: 'productId is required when variantId is provided',\n };\n }\n\n if (productId) {\n payload.product_id = productId;\n if (variantId) {\n payload.variant_id = variantId;\n }\n } else {\n const cart = getCart();\n if (cart.length === 0) {\n return {\n success: false,\n message: 'Cart is empty',\n };\n }\n\n const shopId = await resolveShopId();\n if (!shopId) {\n return {\n success: false,\n message: 'Failed to resolve store',\n };\n }\n\n payload.cart = JSON.stringify({\n shop_id: shopId,\n products: cart.map((item) => ({\n uniqid: item.product_id,\n quantity: item.quantity,\n variant_id: item.variant_id,\n price_variant_id: item.price_variant_id,\n addons: item.addons?.map((addon) => ({\n id: addon.id,\n quantity: addon.quantity ?? 1,\n })),\n })),\n });\n }\n\n const response = await post<CouponValidation>(\n '/v1/storefront/coupons/check',\n payload\n );\n\n return response;\n}\n","/**\n * Reviews Module\n *\n * Shop-level feedback/reviews.\n * Note: Shoppex has shop-level feedback, not product-level reviews.\n */\n\nimport { get } from '../core/client';\nimport { getConfig } from '../core/config';\nimport { buildEndpoint } from '../core/endpoint';\nimport type { SDKResponse, Feedback, ShopReviewsPage } from '../types';\n\nconst REVIEWS_PAGE_LIMIT = 100;\nconst REVIEWS_CACHE_TTL = 2 * 60 * 1000;\n\nfunction toFiniteNumber(value: unknown): number | null {\n if (typeof value === 'number' && Number.isFinite(value)) {\n return value;\n }\n\n if (typeof value === 'string' && value.trim() !== '') {\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : null;\n }\n\n return null;\n}\n\nfunction firstString(...values: unknown[]): string | undefined {\n for (const value of values) {\n if (typeof value === 'string' && value.length > 0) {\n return value;\n }\n }\n\n return undefined;\n}\n\nfunction normalizeFeedback(raw: Feedback, index: number): Feedback {\n const record = raw as Feedback & Record<string, unknown>;\n const rating = toFiniteNumber(record.rating) ?? toFiniteNumber(record.score) ?? 0;\n const comment = firstString(record.comment, record.message);\n const author = firstString(record.author, record.customer_name);\n const createdAt = record.created_at ?? record.createdAt;\n const created_at =\n typeof createdAt === 'number' || typeof createdAt === 'string'\n ? String(createdAt)\n : '';\n const id = firstString(record.id, record.uniqid) ?? `review:${created_at || index}`;\n\n return {\n ...record,\n id,\n rating,\n ...(comment ? { comment } : {}),\n ...(author ? { author } : {}),\n created_at,\n };\n}\n\nexport async function getShopReviewsPage(cursor?: string | null): Promise<SDKResponse<ShopReviewsPage>> {\n const config = getConfig();\n const query = new URLSearchParams();\n query.set('limit', String(REVIEWS_PAGE_LIMIT));\n if (typeof cursor === 'string' && cursor.trim().length > 0) {\n query.set('cursor', cursor);\n }\n const querySuffix = `?${query.toString()}`;\n\n const response = await get<ShopReviewsPage>(\n `${buildEndpoint('/v1/storefront/feedback/shop/:storeSlug', {\n storeSlug: config.storeSlug,\n })}${querySuffix}`,\n {\n cache: {\n key: `reviews:${config.storeSlug}:${cursor ?? 'start'}:${REVIEWS_PAGE_LIMIT}`,\n ttl: REVIEWS_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data) {\n return {\n success: true,\n data: {\n ...response.data,\n feedback: response.data.feedback.map(normalizeFeedback),\n },\n };\n }\n\n return {\n success: false,\n message: response.message,\n };\n}\n\nexport async function getShopReviews(): Promise<SDKResponse<Feedback[]>> {\n const allFeedback: Feedback[] = [];\n const seenCursors = new Set<string>();\n let cursor: string | null = null;\n\n while (true) {\n const response = await getShopReviewsPage(cursor);\n if (!response.success || !response.data) {\n return {\n success: false,\n message: response.message,\n data: [],\n };\n }\n\n allFeedback.push(...response.data.feedback);\n\n const pagination = response.data.pagination;\n if (!pagination?.has_more || !pagination.next_cursor) {\n break;\n }\n\n if (seenCursors.has(pagination.next_cursor)) {\n break;\n }\n\n seenCursors.add(pagination.next_cursor);\n cursor = pagination.next_cursor;\n }\n\n return {\n success: true,\n data: allFeedback,\n };\n}\n","/**\n * Customer Module\n *\n * Authenticated customer account calls for code-lane storefronts. The edge\n * worker owns the HttpOnly session cookie and derives the shop from the host.\n * This module therefore sends neither a session token nor shop identity.\n */\n\nimport {\n customerLoyaltyRedeemSchema,\n customerLoyaltySchema,\n customerPortalDashboardSchema,\n customerPortalInvoiceDetailSchema,\n customerPortalPaginatedInvoicesSchema,\n customerWarrantyClaimSchema,\n customerWarrantyListSchema,\n type CustomerLoyaltyRedeemWire,\n type CustomerLoyaltyWire,\n type CustomerPortalDashboardWire,\n type CustomerPortalInvoiceDetailWire,\n type CustomerPortalPaginatedInvoicesWire,\n type CustomerWarrantyClaimWire,\n type CustomerWarrantyListWire,\n} from '@shoppex/contracts';\nimport type { SDKResponse } from '../types';\n\nconst CUSTOMER_API_PREFIX = '/api/customer';\n\ntype CustomerMethod = 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE';\n\n/**\n * A producer-owned schema for the response payload.\n *\n * Only the endpoints whose shape is defined in `@shoppex/contracts` get one.\n * The rest stay `unknown` on purpose: inventing a type here would assert a wire\n * shape the producer never promised, which is the pattern the retired portal's\n * 544-line hand-written type file demonstrates the cost of.\n */\ninterface CustomerPayloadSchema<T> {\n safeParse(value: unknown): { success: true; data: T } | { success: false };\n}\n\ninterface CustomerRequestOptions<T> {\n method?: CustomerMethod;\n body?: unknown;\n /** Multipart payload. Mutually exclusive with `body`; the browser sets the boundary. */\n formData?: FormData;\n schema?: CustomerPayloadSchema<T>;\n}\n\nexport interface CustomerOrdersQuery {\n page?: number;\n limit?: number;\n /**\n * Invoice status filter, verbatim from the producer's enum. Anything else is\n * answered with a 400 rather than quietly ignored, so pass what the buyer\n * actually chose.\n */\n status?: string;\n /** Partial invoice-id search. The producer trims it to 64 characters. */\n search?: string;\n}\n\ninterface CustomerApiEnvelope {\n status: number;\n data: unknown;\n error?: unknown;\n message?: unknown;\n error_code?: unknown;\n error_params?: unknown;\n}\n\nexport interface CustomerTicketPayload {\n title?: string;\n message: string;\n invoice_id?: string;\n}\n\nexport interface CustomerProfilePatch {\n name: string;\n}\n\nexport interface CustomerSubscriptionCancelOptions {\n cancel_at_period_end?: boolean;\n reason?: string | null;\n}\n\nexport interface CustomerEmailPreferencesPatch {\n global_unsubscribed?: boolean;\n list_subscriptions?: Array<{ list_id: string; subscribed: boolean }>;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction narrowEnvelope(value: unknown): CustomerApiEnvelope | null {\n if (!isRecord(value) || typeof value.status !== 'number' || !('data' in value)) {\n return null;\n }\n\n return value as unknown as CustomerApiEnvelope;\n}\n\nfunction readMessage(envelope: CustomerApiEnvelope, response: Response): string {\n if (typeof envelope.error === 'string' && envelope.error.length > 0) {\n return envelope.error;\n }\n\n if (typeof envelope.message === 'string' && envelope.message.length > 0) {\n return envelope.message;\n }\n\n return response.statusText\n ? `HTTP ${response.status}: ${response.statusText}`\n : `HTTP ${response.status}`;\n}\n\nfunction readErrorFields(envelope: CustomerApiEnvelope): Pick<SDKResponse<unknown>, 'code' | 'errorParams'> {\n const code = typeof envelope.error_code === 'string' && envelope.error_code.length > 0\n ? envelope.error_code\n : null;\n\n if (!code) {\n return {};\n }\n\n return {\n code,\n ...(isRecord(envelope.error_params) ? { errorParams: envelope.error_params } : {}),\n };\n}\n\nasync function requestCustomer<T = unknown>(\n path: string,\n options: CustomerRequestOptions<T> = {},\n): Promise<SDKResponse<T>> {\n const method = options.method ?? 'GET';\n const headers: Record<string, string> = {\n Accept: 'application/json',\n };\n\n if (options.body !== undefined) {\n headers['Content-Type'] = 'application/json';\n }\n\n // FormData carries its own multipart boundary in the Content-Type the browser\n // generates; setting the header here would produce a body the server cannot parse.\n const payload = options.formData ?? (options.body !== undefined ? JSON.stringify(options.body) : undefined);\n\n try {\n const response = await fetch(`${CUSTOMER_API_PREFIX}${path}`, {\n method,\n headers,\n body: payload,\n credentials: 'same-origin',\n cache: 'no-store',\n });\n\n if (response.status === 204) {\n return response.ok\n ? { success: true, status: response.status }\n : {\n success: false,\n status: response.status,\n message: readMessage({ status: response.status, data: null }, response),\n };\n }\n\n let rawEnvelope: unknown;\n try {\n rawEnvelope = await response.json();\n } catch {\n return { success: false, status: response.status, message: 'Invalid customer API response' };\n }\n\n const envelope = narrowEnvelope(rawEnvelope);\n if (!envelope) {\n return { success: false, status: response.status, message: 'Invalid customer API response' };\n }\n\n if (!response.ok || envelope.status < 200 || envelope.status >= 300) {\n return {\n success: false,\n // The transport status, not the envelope's: a caller deciding whether\n // the buyer is signed out must not be steered by a body the edge may\n // never have produced.\n status: response.status,\n message: readMessage(envelope, response),\n ...readErrorFields(envelope),\n };\n }\n\n const message = typeof envelope.message === 'string' && envelope.message.length > 0\n ? { message: envelope.message }\n : {};\n\n if (!options.schema) {\n return { success: true, data: envelope.data as T, ...message };\n }\n\n const parsed = options.schema.safeParse(envelope.data);\n if (!parsed.success) {\n // Fail loudly instead of handing back a payload that does not match what\n // the producer promised. A silently reshaped or partially-read response\n // is how a contract drift reaches the buyer's screen as wrong data.\n return { success: false, message: 'Customer API response did not match the expected contract' };\n }\n\n return { success: true, data: parsed.data, ...message };\n } catch (error) {\n return {\n success: false,\n message: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\n/** One basket line for a QUOTE. `variant_id` is omitted, never null, when a product has no variants. */\nexport interface ResellerOrderItem {\n product_id: string;\n variant_id?: string;\n quantity: number;\n}\n\nexport interface ResellerCatalogQuery {\n search?: string;\n page?: number;\n per_page?: number;\n}\n\nexport interface ResellerOrdersQuery {\n page?: number;\n per_page?: number;\n}\n\nexport function requestOtp(email: string): Promise<SDKResponse<unknown>> {\n return requestCustomer('/auth/otp/request', {\n method: 'POST',\n body: { email },\n });\n}\n\n/**\n * The wire field is `otp`, not `code` — `CustomerOtpVerifyBodySchema` in\n * `apps/backend-elysia/src/routes/v1/customer/schemas.ts` requires it under that\n * name, and a `code` body is rejected with 400.\n */\nexport function verifyOtp(email: string, otp: string): Promise<SDKResponse<unknown>> {\n return requestCustomer('/auth/otp/verify', {\n method: 'POST',\n body: { email, otp },\n });\n}\n\nexport function logout(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/auth/logout', { method: 'POST' });\n}\n\nexport function me(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/me');\n}\n\nexport function dashboard(): Promise<SDKResponse<CustomerPortalDashboardWire>> {\n return requestCustomer('/dashboard', { schema: customerPortalDashboardSchema });\n}\n\n/**\n * Paginated order history.\n *\n * Page-based, matching the producer: `invoices.routes.ts` reads `page` and\n * `limit` and answers with a `has_more` envelope. A cursor parameter would be\n * ignored upstream and silently return page one forever.\n *\n * `status` and `search` are filtered SERVER-side, which is why they belong\n * here rather than in the caller: `/invoices` is paged, and a filter applied\n * to the page in hand would filter only the rows that page happens to hold.\n * The producer spells the search `q`.\n */\nexport function orders(options: CustomerOrdersQuery = {}): Promise<SDKResponse<CustomerPortalPaginatedInvoicesWire>> {\n const query = new URLSearchParams();\n if (options.page !== undefined) query.set('page', String(options.page));\n if (options.limit !== undefined) query.set('limit', String(options.limit));\n if (options.status) query.set('status', options.status);\n if (options.search) query.set('q', options.search);\n\n const suffix = query.size > 0 ? `?${query.toString()}` : '';\n return requestCustomer(`/invoices${suffix}`, { schema: customerPortalPaginatedInvoicesSchema });\n}\n\nexport function order(id: string): Promise<SDKResponse<CustomerPortalInvoiceDetailWire>> {\n return requestCustomer(`/invoice/${encodeURIComponent(id)}`, {\n schema: customerPortalInvoiceDetailSchema,\n });\n}\n\nexport function loyalty(): Promise<SDKResponse<CustomerLoyaltyWire>> {\n return requestCustomer('/loyalty', { schema: customerLoyaltySchema });\n}\n\nexport function redeemLoyaltyPoints(input: {\n points: number;\n idempotencyKey: string;\n}): Promise<SDKResponse<CustomerLoyaltyRedeemWire>> {\n return requestCustomer('/loyalty/redeem', {\n method: 'POST',\n body: {\n points: input.points,\n idempotency_key: input.idempotencyKey,\n },\n schema: customerLoyaltyRedeemSchema,\n });\n}\n\n/**\n * The warranties this buyer holds — all of them, or the ones on one order.\n *\n * `invoiceUniqid` becomes the producer's own `invoice=` filter, which matches\n * `invoices.uniqid`: the id an order carries everywhere a storefront shows one.\n * So an order detail asks for its own cover rather than reading every warranty\n * the buyer owns and discarding most of them.\n */\nexport function warranties(invoiceUniqid?: string): Promise<SDKResponse<CustomerWarrantyListWire>> {\n const suffix = invoiceUniqid ? `?invoice=${encodeURIComponent(invoiceUniqid)}` : '';\n return requestCustomer(`/warranties${suffix}`, { schema: customerWarrantyListSchema });\n}\n\nexport function claimWarranty(\n uniqid: string,\n message?: string,\n): Promise<SDKResponse<CustomerWarrantyClaimWire>> {\n return requestCustomer(`/warranties/${encodeURIComponent(uniqid)}/claim`, {\n method: 'POST',\n body: message ? { message } : {},\n schema: customerWarrantyClaimSchema,\n });\n}\n\n// ---------------------------------------------------------------------------\n// Licenses, subscriptions and tickets have NO collection route.\n//\n// Those three lists arrive inside `/dashboard` — `licenses.routes.ts`,\n// `subscriptions.routes.ts` and `tickets.routes.ts` expose per-item routes only.\n// A `GET /licenses` here would 404 on every call, which is what the earlier\n// spelling of this module did.\n// ---------------------------------------------------------------------------\n\nexport function resetLicenseHwid(uniqid: string): Promise<SDKResponse<unknown>> {\n return requestCustomer(`/licenses/${encodeURIComponent(uniqid)}/reset-hwid`, {\n method: 'POST',\n body: {},\n });\n}\n\nexport function subscriptionBillingHistory(uniqid: string): Promise<SDKResponse<unknown>> {\n return requestCustomer(`/subscriptions/${encodeURIComponent(uniqid)}/billing-history`);\n}\n\nexport function cancelSubscription(\n uniqid: string,\n options: CustomerSubscriptionCancelOptions = {},\n): Promise<SDKResponse<unknown>> {\n return requestCustomer(`/subscriptions/${encodeURIComponent(uniqid)}/cancel`, {\n method: 'POST',\n body: {\n ...(options.cancel_at_period_end !== undefined\n ? { cancel_at_period_end: options.cancel_at_period_end }\n : {}),\n ...(options.reason !== undefined ? { reason: options.reason } : {}),\n },\n });\n}\n\nexport function pauseSubscription(uniqid: string): Promise<SDKResponse<unknown>> {\n return requestCustomer(`/subscriptions/${encodeURIComponent(uniqid)}/pause`, {\n method: 'POST',\n body: {},\n });\n}\n\nexport function resumeSubscription(uniqid: string): Promise<SDKResponse<unknown>> {\n return requestCustomer(`/subscriptions/${encodeURIComponent(uniqid)}/resume`, {\n method: 'POST',\n body: {},\n });\n}\n\nexport function favorites(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/favorites');\n}\n\n/** Idempotent upstream, and a PUT — `customer-favorites.ts` has no POST route. */\nexport function addFavorite(productUniqid: string): Promise<SDKResponse<unknown>> {\n return requestCustomer(`/favorites/${encodeURIComponent(productUniqid)}`, { method: 'PUT' });\n}\n\nexport function removeFavorite(productUniqid: string): Promise<SDKResponse<unknown>> {\n return requestCustomer(`/favorites/${encodeURIComponent(productUniqid)}`, { method: 'DELETE' });\n}\n\nexport function affiliate(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/affiliate');\n}\n\nexport function affiliateStats(days?: number): Promise<SDKResponse<unknown>> {\n const suffix = days === undefined ? '' : `?days=${encodeURIComponent(String(days))}`;\n return requestCustomer(`/affiliate/stats${suffix}`);\n}\n\nexport function createTicket(payload: CustomerTicketPayload): Promise<SDKResponse<unknown>> {\n return requestCustomer('/tickets', {\n method: 'POST',\n body: {\n ...(payload.title !== undefined ? { title: payload.title } : {}),\n message: payload.message,\n ...(payload.invoice_id !== undefined ? { invoice_id: payload.invoice_id } : {}),\n },\n });\n}\n\nexport function ticket(uniqid: string): Promise<SDKResponse<unknown>> {\n return requestCustomer(`/tickets/${encodeURIComponent(uniqid)}`);\n}\n\nexport function replyToTicket(uniqid: string, message: string): Promise<SDKResponse<unknown>> {\n return requestCustomer(`/tickets/${encodeURIComponent(uniqid)}/reply`, {\n method: 'POST',\n body: { message },\n });\n}\n\n/**\n * The producer is `POST /v1/customer/profile`, not PATCH.\n *\n * There is no `GET /profile` to pair with it — the buyer's own record comes from\n * `/me` and `/dashboard`.\n */\nexport function updateProfile(patch: CustomerProfilePatch): Promise<SDKResponse<unknown>> {\n return requestCustomer('/profile', {\n method: 'POST',\n body: { name: patch.name },\n });\n}\n\nexport function updateAvatar(file: File): Promise<SDKResponse<unknown>> {\n const form = new FormData();\n form.append('file', file);\n return requestCustomer('/profile/avatar', { method: 'POST', formData: form });\n}\n\nexport function removeAvatar(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/profile/avatar', { method: 'DELETE' });\n}\n\nexport function emailPreferences(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/email-marketing/preferences');\n}\n\nexport function updateEmailPreferences(\n patch: CustomerEmailPreferencesPatch,\n): Promise<SDKResponse<unknown>> {\n return requestCustomer('/email-marketing/preferences', {\n method: 'PATCH',\n body: {\n ...(patch.global_unsubscribed !== undefined\n ? { global_unsubscribed: patch.global_unsubscribed }\n : {}),\n ...(patch.list_subscriptions !== undefined\n ? { list_subscriptions: patch.list_subscriptions }\n : {}),\n },\n });\n}\n\nexport function sessions(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/sessions');\n}\n\nexport function revokeSession(id: string): Promise<SDKResponse<unknown>> {\n return requestCustomer(`/sessions/${encodeURIComponent(id)}`, { method: 'DELETE' });\n}\n\n/**\n * Ends every session except this one.\n *\n * `others=true` is required, not decorative: `RevokeOtherSessionsQuerySchema`\n * declares it as a literal, so the route answers 400 without it. The selector\n * is explicit on purpose — \"revoke sessions\" with no qualifier is one typo away\n * from signing the buyer out of the device they are holding.\n */\nexport function revokeAllSessions(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/sessions?others=true', { method: 'DELETE' });\n}\n\n// ---------------------------------------------------------------------------\n// Wholesale (reseller program)\n//\n// A second program on the same account: its own way in, its own prepaid\n// balance, its own prices. Every route re-checks \"program enabled AND this\n// reseller is ACTIVE\" server-side, so nothing a storefront caches can widen\n// what a buyer may do here.\n//\n// Two writes are deliberately absent, and adding them back would be adding\n// methods that answer 404: the storefront worker refuses them. On a code\n// storefront the JavaScript on this origin is the MERCHANT's and it holds the\n// buyer's cookie, so the edge's same-origin check proves that script sent the\n// request, never that the buyer wanted it.\n// - placing a wholesale order debits the buyer's prepaid balance; a purchase\n// needs a boundary the merchant does not control\n// - minting an API key hands back a plaintext credential that keeps\n// authorizing orders after the session ends\n// Pricing a basket stays, because it writes nothing.\n// ---------------------------------------------------------------------------\n\n/** The program's state and this buyer's place in it. Null reseller means not enrolled. */\nexport function reseller(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/reseller');\n}\n\n/** `APPLICATION` mode. The note is optional unless the shop requires one. */\nexport function applyForReseller(note?: string): Promise<SDKResponse<unknown>> {\n return requestCustomer('/reseller/apply', {\n method: 'POST',\n body: note === undefined ? {} : { note },\n });\n}\n\n/** `OPEN` mode: no application, the buyer is a reseller when they say so. */\nexport function enrollAsReseller(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/reseller/enroll', { method: 'POST', body: {} });\n}\n\n/** `MANUAL` mode: the merchant invited this buyer and gave them a token. */\nexport function acceptResellerInvite(token: string): Promise<SDKResponse<unknown>> {\n return requestCustomer('/reseller/accept-invite', { method: 'POST', body: { token } });\n}\n\n/** The buyer's own tier prices. Page-based, like the order history. */\nexport function resellerCatalog(options: ResellerCatalogQuery = {}): Promise<SDKResponse<unknown>> {\n const query = new URLSearchParams();\n if (options.search !== undefined) query.set('search', options.search);\n if (options.page !== undefined) query.set('page', String(options.page));\n if (options.per_page !== undefined) query.set('per_page', String(options.per_page));\n\n const suffix = query.size > 0 ? `?${query.toString()}` : '';\n return requestCustomer(`/reseller/catalog${suffix}`);\n}\n\n/**\n * Prices a basket and writes nothing.\n *\n * The volume discount cannot be derived from the catalog — it only reports that\n * one exists — so a storefront that adds up unit prices itself shows a total\n * the shop will not charge. This is the number to display.\n */\nexport function quoteResellerOrder(items: ResellerOrderItem[]): Promise<SDKResponse<unknown>> {\n return requestCustomer('/reseller/orders/quote', { method: 'POST', body: { items } });\n}\n\nexport function resellerOrders(options: ResellerOrdersQuery = {}): Promise<SDKResponse<unknown>> {\n const query = new URLSearchParams();\n if (options.page !== undefined) query.set('page', String(options.page));\n if (options.per_page !== undefined) query.set('per_page', String(options.per_page));\n\n const suffix = query.size > 0 ? `?${query.toString()}` : '';\n return requestCustomer(`/reseller/orders${suffix}`);\n}\n\n/** One order with its lines, delivery state and delivered serials. */\nexport function resellerOrder(uniqid: string): Promise<SDKResponse<unknown>> {\n return requestCustomer(`/reseller/orders/${encodeURIComponent(uniqid)}`);\n}\n\n/** The prepaid balance the wholesale orders are paid from. */\nexport function resellerWallet(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/reseller/wallet');\n}\n\nexport function resellerApiKeys(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/reseller/api-keys');\n}\n\n/*\n * There is no `revokeResellerApiKey`. Revoking is irreversible and stops\n * whatever the key was driving, and this SDK is the transport for code\n * storefronts — merchant-authored JavaScript running with the buyer's session,\n * where a confirmation proves nothing because the merchant renders it. The\n * edge omits the DELETE from `CUSTOMER_API_ALLOWLIST`\n * (`workers/storefront/src/customer-api.ts`), so exporting a method for it\n * would advertise a call that always answers 404.\n */\n","import { getStorefront } from './store.js';\nimport { isInitialized } from '../core/config.js';\nimport {\n searchMergedStorefrontCatalog,\n searchMergedStorefrontCatalogItems,\n type StorefrontCatalogSearchItem,\n} from '../utils/storefront-search.js';\nimport type { SDKResponse, Product } from '../types/index.js';\n\nexport interface SearchOptions {\n hideOutOfStock?: boolean;\n maxResults?: number;\n}\n\nexport type { StorefrontCatalogSearchItem };\n\nexport async function searchCatalogItems(\n query: string,\n options?: SearchOptions,\n): Promise<SDKResponse<StorefrontCatalogSearchItem[]>> {\n if (!isInitialized()) {\n return { success: false, message: 'SDK not initialized' };\n }\n\n const trimmed = query.trim();\n if (!trimmed) {\n return { success: true, data: [] };\n }\n\n const storefront = await getStorefront();\n if (!storefront.success || !storefront.data) {\n return {\n success: false,\n message: storefront.message ?? 'Failed to fetch storefront catalog',\n };\n }\n\n const results = searchMergedStorefrontCatalogItems(\n storefront.data.products ?? [],\n storefront.data.groups ?? [],\n trimmed,\n {\n hideOutOfStock: options?.hideOutOfStock,\n maxResults: options?.maxResults,\n },\n );\n\n return { success: true, data: results };\n}\n\nexport async function searchProducts(\n query: string,\n options?: SearchOptions,\n): Promise<SDKResponse<Product[]>> {\n if (!isInitialized()) {\n return { success: false, message: 'SDK not initialized' };\n }\n\n const trimmed = query.trim();\n if (!trimmed) {\n return { success: true, data: [] };\n }\n\n const storefront = await getStorefront();\n if (!storefront.success || !storefront.data) {\n return {\n success: false,\n message: storefront.message ?? 'Failed to fetch storefront catalog',\n };\n }\n\n const results = searchMergedStorefrontCatalog(\n storefront.data.products ?? [],\n storefront.data.groups ?? [],\n trimmed,\n {\n hideOutOfStock: options?.hideOutOfStock,\n maxResults: options?.maxResults,\n },\n );\n\n return { success: true, data: results };\n}\n","/**\n * Invoices Module\n *\n * Invoice status checking after payment.\n */\n\nimport { get } from '../core/client';\nimport { buildEndpoint } from '../core/endpoint';\nimport type { SDKResponse, Invoice } from '../types';\n\nfunction normalizeInvoiceId(invoiceId: string): string | null {\n const normalized = invoiceId.trim();\n if (!normalized) {\n return null;\n }\n return normalized;\n}\n\nexport async function getInvoice(\n invoiceId: string\n): Promise<SDKResponse<Invoice>> {\n const normalizedInvoiceId = normalizeInvoiceId(invoiceId);\n if (!normalizedInvoiceId) {\n return {\n success: false,\n message: 'Invoice ID is required',\n };\n }\n\n const response = await get<{ invoice: Invoice }>(\n buildEndpoint('/v1/storefront/invoices/unique/:invoiceId', {\n invoiceId: normalizedInvoiceId,\n })\n );\n if (!response.success) {\n return {\n success: false,\n message: response.message,\n };\n }\n\n if (!response.data?.invoice) {\n return {\n success: false,\n message: 'Invalid invoice response',\n };\n }\n\n return {\n success: true,\n data: response.data.invoice,\n };\n}\n\nexport async function getInvoiceStatus(\n invoiceId: string\n): Promise<SDKResponse<{ status: string }>> {\n const normalizedInvoiceId = normalizeInvoiceId(invoiceId);\n if (!normalizedInvoiceId) {\n return {\n success: false,\n message: 'Invoice ID is required',\n };\n }\n\n const response = await get<{ invoice: { status: string } }>(\n buildEndpoint('/v1/storefront/invoices/status/:invoiceId', {\n invoiceId: normalizedInvoiceId,\n })\n );\n if (!response.success) {\n return {\n success: false,\n message: response.message,\n };\n }\n\n if (!response.data?.invoice?.status) {\n return {\n success: false,\n message: 'Invalid invoice status response',\n };\n }\n\n return {\n success: true,\n data: { status: response.data.invoice.status },\n };\n}\n","/**\n * Pages Module\n *\n * API methods for public pages.\n */\n\nimport { get } from '../core/client';\nimport { getConfig } from '../core/config';\nimport { buildEndpoint } from '../core/endpoint';\nimport type { SDKResponse, Page } from '../types';\n\ninterface PagesResponse {\n pages: Page[];\n}\n\ninterface PageResponse {\n page: Page;\n}\n\nconst PAGES_CACHE_TTL = 5 * 60 * 1000;\n\n/**\n * Get all public pages for the store\n */\nexport async function getPages(): Promise<SDKResponse<Page[]>> {\n const config = getConfig();\n const response = await get<PagesResponse>(\n buildEndpoint('/v1/storefront/shops/name/:storeSlug/pages', {\n storeSlug: config.storeSlug,\n }),\n {\n cache: {\n key: `pages:${config.storeSlug}`,\n ttl: PAGES_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data) {\n return {\n success: true,\n data: response.data.pages,\n };\n }\n\n return {\n success: false,\n message: response.message,\n };\n}\n\n/**\n * Get a public page by slug\n */\nexport async function getPage(slug: string): Promise<SDKResponse<Page>> {\n const config = getConfig();\n const response = await get<PageResponse>(\n buildEndpoint('/v1/storefront/shops/name/:storeSlug/pages/:slug', {\n storeSlug: config.storeSlug,\n slug,\n }),\n {\n cache: {\n key: `page:${config.storeSlug}:${slug}`,\n ttl: PAGES_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data) {\n return {\n success: true,\n data: response.data.page,\n };\n }\n\n return {\n success: false,\n message: response.message,\n };\n}\n","/**\n * Navigation Module\n *\n * API methods for menus and navigation.\n */\n\nimport { get } from '../core/client';\nimport { getConfig } from '../core/config';\nimport { buildEndpoint } from '../core/endpoint';\nimport type { SDKResponse, Menu } from '../types';\nimport type { NavigationMenuSlot } from '@shoppex/contracts/navigation';\nimport { getNavigationMenuTitles } from '@shoppex/contracts/navigation';\n\ninterface MenusResponse {\n menus: Menu[];\n}\n\ninterface MenuResponse {\n menu: Menu;\n}\n\nconst NAVIGATION_CACHE_TTL = 5 * 60 * 1000;\n\n/**\n * Get all menus for the store\n */\nexport async function getMenus(): Promise<SDKResponse<Menu[]>> {\n const config = getConfig();\n const response = await get<MenusResponse>(\n buildEndpoint('/v1/storefront/shops/name/:storeSlug/menus', {\n storeSlug: config.storeSlug,\n }),\n {\n cache: {\n key: `menus:${config.storeSlug}`,\n ttl: NAVIGATION_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data) {\n return {\n success: true,\n data: response.data.menus,\n };\n }\n\n return {\n success: false,\n message: response.message,\n };\n}\n\n/**\n * Get a menu by its exact title.\n */\nexport async function getMenuByTitle(title: string): Promise<SDKResponse<Menu>> {\n const config = getConfig();\n const response = await get<MenuResponse>(\n buildEndpoint('/v1/storefront/shops/name/:storeSlug/menus/:title', {\n storeSlug: config.storeSlug,\n title,\n }),\n {\n cache: {\n key: `menu:${config.storeSlug}:${title}`,\n ttl: NAVIGATION_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data) {\n return {\n success: true,\n data: response.data.menu,\n };\n }\n\n return {\n success: false,\n message: response.message,\n };\n}\n\n/**\n * Get a menu by its exact title.\n */\nexport async function getMenu(title: string): Promise<SDKResponse<Menu>> {\n return getMenuByTitle(title);\n}\n\n/**\n * Get a menu by canonical slot. The backend resolves legacy menu titles too.\n */\nexport async function getMenuBySlot(slot: NavigationMenuSlot): Promise<SDKResponse<Menu>> {\n const config = getConfig();\n const response = await get<MenuResponse>(\n buildEndpoint('/v1/storefront/shops/name/:storeSlug/menus/:title', {\n storeSlug: config.storeSlug,\n title: slot,\n }),\n {\n cache: {\n key: `menu-slot:${config.storeSlug}:${slot}`,\n ttl: NAVIGATION_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data) {\n return {\n success: true,\n data: response.data.menu,\n };\n }\n\n return {\n success: false,\n message: response.message,\n };\n}\n\nexport function getMenuSlotTitles(slot: NavigationMenuSlot): string[] {\n return getNavigationMenuTitles(slot);\n}\n","/**\n * UTM attribution for storefront page views.\n *\n * Campaign parameters only appear on the landing URL, but a visitor usually\n * browses several pages before doing anything interesting. Without persistence\n * every page after the first would be attributed to \"direct\" and the numbers\n * would understate every campaign.\n *\n * Last-touch: a fresh set of parameters replaces the stored one, matching what\n * merchants expect from analytics tools — the most recent campaign gets credit.\n * Navigating without parameters keeps whatever was stored.\n */\n\nconst STORAGE_PREFIX = 'shoppex:utm:';\nconst TTL_MS = 30 * 24 * 60 * 60 * 1000;\n\nconst UTM_KEYS = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content'] as const;\n\ntype UtmKey = (typeof UTM_KEYS)[number];\n\nexport type UtmParameters = Partial<Record<UtmKey, string>>;\n\ninterface StoredAttribution {\n utm: UtmParameters;\n /** Epoch ms of the last touch, used for TTL expiry. */\n at: number;\n}\n\n/** Values are merchant-supplied and land in a text column; keep them bounded. */\nconst MAX_VALUE_LENGTH = 255;\n\nfunction readFromUrl(search: string): UtmParameters {\n let params: URLSearchParams;\n try {\n params = new URLSearchParams(search);\n } catch {\n return {};\n }\n\n const utm: UtmParameters = {};\n for (const key of UTM_KEYS) {\n const value = params.get(key)?.trim();\n if (value) {\n utm[key] = value.slice(0, MAX_VALUE_LENGTH);\n }\n }\n return utm;\n}\n\nfunction storageKey(storeSlug: string): string {\n return `${STORAGE_PREFIX}${storeSlug}`;\n}\n\nfunction readStored(storeSlug: string): UtmParameters {\n try {\n const raw = window.localStorage.getItem(storageKey(storeSlug));\n if (!raw) return {};\n\n const parsed = JSON.parse(raw) as StoredAttribution;\n if (!parsed || typeof parsed.at !== 'number' || typeof parsed.utm !== 'object') return {};\n if (Date.now() - parsed.at > TTL_MS) {\n window.localStorage.removeItem(storageKey(storeSlug));\n return {};\n }\n\n const utm: UtmParameters = {};\n for (const key of UTM_KEYS) {\n const value = parsed.utm?.[key];\n if (typeof value === 'string' && value.length > 0) {\n utm[key] = value.slice(0, MAX_VALUE_LENGTH);\n }\n }\n return utm;\n } catch {\n // Private mode, quota errors, corrupt JSON — attribution is best-effort and\n // must never break a page view.\n return {};\n }\n}\n\nfunction writeStored(storeSlug: string, utm: UtmParameters): void {\n try {\n const payload: StoredAttribution = { utm, at: Date.now() };\n window.localStorage.setItem(storageKey(storeSlug), JSON.stringify(payload));\n } catch {\n // Ignore: the current page view still reports the parameters it just read.\n }\n}\n\n/**\n * Resolves the UTM parameters to report for the current page view.\n *\n * Reads the current URL first; when it carries any campaign parameter that set\n * wins and is persisted. Otherwise the stored set is returned unchanged.\n *\n * @returns the parameters, or undefined when there is nothing to report\n */\nexport function resolveUtmParameters(storeSlug: string): UtmParameters | undefined {\n if (typeof window === 'undefined' || typeof window.location === 'undefined') {\n return undefined;\n }\n\n const fromUrl = readFromUrl(window.location.search);\n if (Object.keys(fromUrl).length > 0) {\n writeStored(storeSlug, fromUrl);\n return fromUrl;\n }\n\n const stored = readStored(storeSlug);\n return Object.keys(stored).length > 0 ? stored : undefined;\n}\n","import { isInitialized, getConfig } from '../core/config';\nimport { buildEndpoint } from '../core/endpoint';\nimport { getStorefrontConnectionId } from '../core/telemetry';\nimport { resolveUtmParameters } from '../core/attribution';\n\nexport async function trackPageView(cartValue?: number, itemCount?: number): Promise<void> {\n if (!isInitialized()) return;\n if (typeof document === 'undefined') return;\n\n const config = getConfig();\n const connectionId = getStorefrontConnectionId(config.storeSlug);\n\n try {\n const endpoint = buildEndpoint('/v1/storefront/shops/:storeSlug/ping', {\n storeSlug: config.storeSlug,\n });\n await fetch(`${config.apiBaseUrl}${endpoint}`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n referer: document.referrer || undefined,\n cart_value: cartValue ?? undefined,\n item_count: itemCount ?? undefined,\n connection_id: connectionId ?? undefined,\n utm: resolveUtmParameters(config.storeSlug),\n }),\n });\n } catch {\n // Intentionally silent - analytics should never block the user experience\n }\n}\n","import { get, post } from '../core/client';\nimport { getConfig, getShopId, isInitialized } from '../core/config';\nimport { buildEndpoint } from '../core/endpoint';\nimport { getStorefrontConnectionId } from '../core/telemetry';\nimport { resolveUtmParameters } from '../core/attribution';\nimport type { SDKResponse, StorefrontOnlineUsers, StorefrontRecentSales } from '../types';\n\n/**\n * Anonymized recent-sales feed for storefront social proof (product title +\n * relative age only — never buyer identity). Empty items when the shop has no\n * recent completed orders.\n */\nexport async function getStorefrontRecentSales(): Promise<SDKResponse<StorefrontRecentSales>> {\n if (!isInitialized()) {\n return { success: false, message: 'SDK not initialized' };\n }\n\n const config = getConfig();\n const shopId = getShopId();\n const endpoint = shopId\n ? buildEndpoint('/v1/storefront/shops/id/:id/recent-sales', { id: shopId })\n : buildEndpoint('/v1/storefront/shops/:storeSlug/recent-sales', {\n storeSlug: config.storeSlug,\n });\n\n return get<StorefrontRecentSales>(endpoint, {\n cache: false,\n retries: 0,\n timeout: 5000,\n });\n}\n\nexport async function getStorefrontOnlineUsers(): Promise<SDKResponse<StorefrontOnlineUsers>> {\n if (!isInitialized()) {\n return { success: false, message: 'SDK not initialized' };\n }\n\n const config = getConfig();\n const shopId = getShopId();\n const endpoint = shopId\n ? buildEndpoint('/v1/storefront/shops/id/:id/online-users', { id: shopId })\n : buildEndpoint('/v1/storefront/shops/:storeSlug/online-users', {\n storeSlug: config.storeSlug,\n });\n\n return get<StorefrontOnlineUsers>(endpoint, {\n cache: false,\n retries: 0,\n timeout: 5000,\n });\n}\n\nexport async function touchStorefrontPresence(): Promise<SDKResponse<{ pong: string }>> {\n if (!isInitialized()) {\n return { success: false, message: 'SDK not initialized' };\n }\n if (typeof document === 'undefined') {\n return { success: false, message: 'Document is not available' };\n }\n\n const config = getConfig();\n const shopId = getShopId();\n const endpoint = shopId\n ? buildEndpoint('/v1/storefront/shops/id/:id/ping', { id: shopId })\n : buildEndpoint('/v1/storefront/shops/:storeSlug/ping', {\n storeSlug: config.storeSlug,\n });\n\n return post<{ pong: string }>(\n endpoint,\n {\n referer: document.referrer || undefined,\n connection_id: getStorefrontConnectionId(config.storeSlug) ?? undefined,\n utm: resolveUtmParameters(config.storeSlug),\n },\n {\n retries: 0,\n timeout: 5000,\n },\n );\n}\n","/**\n * Formatting Utilities\n */\n\nimport { getConfig } from '../core/config';\nimport { CATALOG_UNIT_PRICE_FORMAT_OPTIONS } from '@shoppex/contracts/catalog-unit-price';\n\nexport function createFormatter(\n currency?: string,\n locale?: string\n): Intl.NumberFormat {\n const config = getConfig();\n\n return new Intl.NumberFormat(locale ?? config.locale ?? 'en-US', {\n style: 'currency',\n currency: currency ?? config.currency ?? 'USD',\n ...CATALOG_UNIT_PRICE_FORMAT_OPTIONS,\n });\n}\n\nexport function formatPrice(\n amount: number | string,\n currency?: string,\n locale?: string\n): string {\n const numericAmount = typeof amount === 'string' ? parseFloat(amount) : amount;\n if (Number.isNaN(numericAmount)) {\n return createFormatter(currency, locale).format(0);\n }\n return createFormatter(currency, locale).format(numericAmount);\n}\n","import type { ThemeConfig, ResolvedThemeSettings } from '../types/theme-config';\nimport { get } from '../core/client';\nimport { buildEndpoint } from '../core/endpoint';\n\ntype JsonRecord = Record<string, unknown>;\n\nexport interface PublishedBuilderSettings {\n version: number;\n revision: number;\n theme: {\n content: JsonRecord;\n layout: JsonRecord;\n style_slots: JsonRecord;\n pages?: unknown[];\n terms?: JsonRecord;\n [key: string]: unknown;\n };\n [key: string]: unknown;\n}\n\nexport interface PublishedThemeSettingsPayload {\n settings: ResolvedThemeSettings;\n builder_settings: PublishedBuilderSettings | null;\n content: JsonRecord;\n style_slots: JsonRecord;\n}\n\nfunction isRecord(value: unknown): value is JsonRecord {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction normalizePublishedBuilderSettings(value: unknown): PublishedBuilderSettings | null {\n if (!isRecord(value) || !isRecord(value.theme)) {\n return null;\n }\n\n return {\n ...value,\n version: typeof value.version === 'number' ? value.version : 0,\n revision: typeof value.revision === 'number' ? value.revision : 0,\n theme: {\n ...value.theme,\n content: isRecord(value.theme.content) ? value.theme.content : {},\n layout: isRecord(value.theme.layout) ? value.theme.layout : {},\n style_slots: isRecord(value.theme.style_slots) ? value.theme.style_slots : {},\n ...(Array.isArray(value.theme.pages) ? { pages: value.theme.pages } : {}),\n ...(isRecord(value.theme.terms) ? { terms: value.theme.terms } : {}),\n },\n };\n}\n\nfunction normalizePublishedThemeSettingsPayload(value: unknown): PublishedThemeSettingsPayload | null {\n if (!isRecord(value)) {\n return null;\n }\n\n return {\n settings: isRecord(value.settings) ? value.settings as ResolvedThemeSettings : {},\n builder_settings: normalizePublishedBuilderSettings(value.builder_settings),\n content: isRecord(value.content) ? value.content : {},\n style_slots: isRecord(value.style_slots) ? value.style_slots : {},\n };\n}\n\nexport async function fetchPublishedBuilderSettings(\n shopSlug: string\n): Promise<PublishedThemeSettingsPayload | null> {\n const result = await get<PublishedThemeSettingsPayload>(\n buildEndpoint('/v1/storefront/themes/builder/published/:shopSlug', { shopSlug })\n );\n\n return result.success && result.data ? normalizePublishedThemeSettingsPayload(result.data) : null;\n}\n\nexport async function fetchPublishedThemeSettings(\n shopSlug: string\n): Promise<ResolvedThemeSettings | null> {\n const payload = await fetchPublishedBuilderSettings(shopSlug);\n return payload ? payload.settings : null;\n}\n\nexport function resolveDefaults(config: ThemeConfig): ResolvedThemeSettings {\n const resolved: ResolvedThemeSettings = {};\n for (const [category, fields] of Object.entries(config.settings)) {\n resolved[category] = {};\n for (const [key, field] of Object.entries(fields)) {\n resolved[category][key] = field.default;\n }\n }\n return resolved;\n}\n\nexport function mergeSettings(\n defaults: ResolvedThemeSettings,\n overrides: Partial<ResolvedThemeSettings>\n): ResolvedThemeSettings {\n const merged = { ...defaults };\n for (const [category, fields] of Object.entries(overrides)) {\n if (fields) {\n merged[category] = { ...merged[category], ...fields };\n }\n }\n return merged;\n}\n","/**\n * Shoppex Storefront SDK\n *\n * Usage:\n * ```html\n * <script src=\"https://cdn.shoppex.io/sdk/v1.0/shoppex.umd.js\"></script>\n * <script>\n * shoppex.init('my-store');\n *\n * shoppex.getStore().then(store => console.log(store));\n * shoppex.addToCart('product-id', 'variant-id', 2);\n * shoppex.checkout();\n * </script>\n * ```\n */\n\nimport { initConfig, isInitialized, getConfig } from './core/config';\nimport { getTypedClient } from './core/typed-client';\nimport type { ShoppexInitOptions } from './types';\n\n// Re-export types\nexport * from './types';\nexport * from './core/errors';\nexport {\n buildStorefrontCustomFieldPayload,\n isStorefrontCheckboxCustomFieldValueChecked,\n normalizeStorefrontCustomFields,\n validateStorefrontCustomFieldValue,\n} from './utils/storefront-custom-fields';\nexport type { StorefrontCustomField } from './utils/storefront-custom-fields';\nexport {\n isProductInStock,\n isProductOutOfStock,\n isVariantOutOfStock,\n resolveDisplayStock,\n resolveVariantStockValue,\n} from './utils/storefront-stock';\nexport {\n buildStorefrontProductLookup,\n getMergedStorefrontProducts,\n getStorefrontGroupProducts,\n} from './utils/storefront-catalog';\nexport {\n stripHtmlFromText,\n normalizeSearchQuery,\n collectProductSearchHaystack,\n productMatchesSearchQuery,\n groupMatchesSearchQuery,\n filterProductsBySearchQuery,\n searchMergedStorefrontCatalog,\n searchMergedStorefrontCatalogItems,\n} from './utils/storefront-search';\nexport type { StorefrontSearchFilterOptions, StorefrontCatalogSearchItem } from './utils/storefront-search';\nexport {\n buildStorefrontContactMessage,\n resolveStorefrontApiBaseUrl,\n resolveStorefrontSocialLinks,\n submitStorefrontContactTicket,\n} from './utils/storefront-contact';\nexport type {\n StorefrontContactTicketInput,\n StorefrontContactTicketResult,\n StorefrontSocialLinks,\n} from './utils/storefront-contact';\nexport type {\n BlockDefinition,\n BlockInstance,\n PageLayout,\n ThemeConfig,\n ThemeBlockManifest,\n SettingField,\n SectionDefinition,\n ResolvedThemeSettings,\n} from './types/theme-config';\nexport type { PublishedBuilderSettings, PublishedThemeSettingsPayload } from './modules/theme';\nexport type { NavigationMenuSlot } from '@shoppex/contracts/navigation';\nexport {\n CATALOG_UNIT_PRICE_DECIMAL_PLACES,\n CATALOG_UNIT_PRICE_FORMAT_OPTIONS,\n PAYABLE_AMOUNT_DECIMAL_PLACES,\n roundPayableAmount,\n} from '@shoppex/contracts/catalog-unit-price';\n\n// Store module\nimport {\n getStore,\n getStorefront,\n getStoreLogoUrl,\n getStoreBannerUrl,\n resolveStoreByDomain,\n} from './modules/store';\n\n// Products module\nimport { getProducts, getProduct, getCategories, getStorefrontProductsPage } from './modules/products';\n\n// Cart module\nimport {\n getCart,\n getCartItemCount,\n getCartCoupon,\n getCartCouponSource,\n setCartCoupon,\n clearCartCoupon,\n addToCart,\n setCartItem,\n updateCartItem,\n removeFromCart,\n clearCart,\n createCartBackup,\n restoreCartFromBackup,\n mergeBaskets,\n moveBasketItem,\n getCartStats,\n validateCartIntegrity,\n quoteCart,\n resolveCartLineId,\n} from './modules/cart';\n// resolveCartLineId is re-exported on the default shoppex object below (not only type-only).\nexport { computeCartLineId, ensureCartLineId } from './utils/cart-line-id';\nexport type { CartLineIdentityInput } from './utils/cart-line-id';\n\n// Checkout module\nimport { checkout, buildCheckoutUrl, buildCheckoutUrlSync } from './modules/checkout';\nexport type { CheckoutOptions, CheckoutResult } from './modules/checkout';\nexport { CheckoutCreateError } from './modules/checkout';\nimport { mountCheckoutChallenge } from './modules/checkout-challenge';\nexport { mountCheckoutChallenge } from './modules/checkout-challenge';\nexport type {\n CheckoutChallengeCallbacks,\n CheckoutChallengeFrame,\n} from './modules/checkout-challenge';\nexport type { SearchOptions } from './modules/search';\n\n// Affiliate module\nimport {\n applyAffiliateCode,\n captureAffiliateFromUrl,\n getAffiliateCode,\n setAffiliateCode,\n clearAffiliateCode,\n trackAffiliateEvent,\n validateAffiliateCode,\n} from './modules/affiliates';\n\n// Coupons module\nimport { validateCoupon } from './modules/coupons';\n\n// Reviews module\nimport { getShopReviews, getShopReviewsPage } from './modules/reviews';\nexport { getShopReviewsPage } from './modules/reviews';\n\n// Customer module\nimport {\n requestOtp,\n verifyOtp,\n logout,\n me,\n dashboard,\n orders,\n order,\n loyalty,\n redeemLoyaltyPoints,\n warranties,\n claimWarranty,\n resetLicenseHwid,\n subscriptionBillingHistory,\n cancelSubscription,\n pauseSubscription,\n resumeSubscription,\n favorites,\n addFavorite,\n removeFavorite,\n affiliate,\n affiliateStats,\n createTicket,\n ticket,\n replyToTicket,\n updateProfile,\n updateAvatar,\n removeAvatar,\n emailPreferences,\n updateEmailPreferences,\n sessions,\n revokeSession,\n revokeAllSessions,\n reseller,\n applyForReseller,\n enrollAsReseller,\n acceptResellerInvite,\n resellerCatalog,\n quoteResellerOrder,\n resellerOrders,\n resellerOrder,\n resellerWallet,\n resellerApiKeys,\n} from './modules/customer';\nexport {\n requestOtp,\n verifyOtp,\n logout,\n me,\n dashboard,\n orders,\n order,\n loyalty,\n redeemLoyaltyPoints,\n warranties,\n claimWarranty,\n resetLicenseHwid,\n subscriptionBillingHistory,\n cancelSubscription,\n pauseSubscription,\n resumeSubscription,\n favorites,\n addFavorite,\n removeFavorite,\n affiliate,\n affiliateStats,\n createTicket,\n ticket,\n replyToTicket,\n updateProfile,\n updateAvatar,\n removeAvatar,\n emailPreferences,\n updateEmailPreferences,\n sessions,\n revokeSession,\n revokeAllSessions,\n reseller,\n applyForReseller,\n enrollAsReseller,\n acceptResellerInvite,\n resellerCatalog,\n quoteResellerOrder,\n resellerOrders,\n resellerOrder,\n resellerWallet,\n resellerApiKeys,\n} from './modules/customer';\nexport type {\n CustomerTicketPayload,\n CustomerProfilePatch,\n CustomerSubscriptionCancelOptions,\n CustomerEmailPreferencesPatch,\n ResellerOrderItem,\n ResellerCatalogQuery,\n ResellerOrdersQuery,\n} from './modules/customer';\n\n// Search module\nimport { searchProducts, searchCatalogItems } from './modules/search';\n\n// Invoices module\nimport { getInvoice, getInvoiceStatus } from './modules/invoices';\n\n// Pages module\nimport { getPages, getPage } from './modules/pages';\n\n// Navigation module\nimport { getMenus, getMenu, getMenuBySlot, getMenuByTitle, getMenuSlotTitles } from './modules/navigation';\n\n// Analytics module\nimport { trackPageView } from './modules/analytics';\nimport { getStorefrontOnlineUsers, getStorefrontRecentSales, touchStorefrontPresence } from './modules/presence';\n\n// Format utilities\nimport { createFormatter, formatPrice } from './utils/format';\nimport { clearCache, invalidateCache, getCacheStats } from './core/cache';\nimport { fetchPublishedBuilderSettings, fetchPublishedThemeSettings, resolveDefaults, mergeSettings } from './modules/theme';\n\nexport { fetchPublishedBuilderSettings, fetchPublishedThemeSettings, resolveDefaults, mergeSettings } from './modules/theme';\nexport { trackPageView } from './modules/analytics';\nexport { getStorefrontOnlineUsers, getStorefrontRecentSales, touchStorefrontPresence } from './modules/presence';\nexport { getMenus, getMenu, getMenuBySlot, getMenuByTitle, getMenuSlotTitles } from './modules/navigation';\n\n/**\n * Initialize the SDK with a store slug\n */\nfunction init(storeSlug: string, options?: ShoppexInitOptions): void;\nfunction init(options: ShoppexInitOptions & { storeId: string }): void;\nfunction init(\n storeSlugOrOptions: string | (ShoppexInitOptions & { storeId: string }),\n options?: ShoppexInitOptions\n): void {\n if (typeof storeSlugOrOptions === 'string') {\n initConfig(storeSlugOrOptions, options);\n } else {\n initConfig(storeSlugOrOptions.storeId, storeSlugOrOptions);\n }\n}\n\n/**\n * Shoppex SDK instance\n */\nexport const shoppex = {\n // Initialization\n init,\n isInitialized,\n getConfig,\n\n // Typed OpenAPI client — drop to this when you need an endpoint the\n // high-level modules below do not cover yet.\n client: getTypedClient,\n\n // Store\n getStore,\n getStorefront,\n getStoreLogoUrl,\n getStoreBannerUrl,\n resolveStoreByDomain,\n\n // Products\n getProducts,\n getStorefrontProductsPage,\n getProduct,\n getCategories,\n\n // Cart\n getCart,\n getCartItemCount,\n getCartCoupon,\n getCartCouponSource,\n setCartCoupon,\n clearCartCoupon,\n addToCart,\n setCartItem,\n updateCartItem,\n removeFromCart,\n clearCart,\n createCartBackup,\n restoreCartFromBackup,\n mergeBaskets,\n moveBasketItem,\n getCartStats,\n validateCartIntegrity,\n quoteCart,\n resolveCartLineId,\n\n // Checkout\n checkout,\n buildCheckoutUrl,\n buildCheckoutUrlSync,\n mountCheckoutChallenge,\n\n // Affiliates\n captureAffiliateFromUrl,\n validateAffiliateCode,\n applyAffiliateCode,\n getAffiliateCode,\n setAffiliateCode,\n clearAffiliateCode,\n trackAffiliateEvent,\n\n // Coupons\n validateCoupon,\n\n // Reviews\n getShopReviews,\n getShopReviewsPage,\n\n // Customer account\n requestOtp,\n verifyOtp,\n logout,\n me,\n dashboard,\n orders,\n order,\n loyalty,\n redeemLoyaltyPoints,\n warranties,\n claimWarranty,\n resetLicenseHwid,\n subscriptionBillingHistory,\n cancelSubscription,\n pauseSubscription,\n resumeSubscription,\n favorites,\n addFavorite,\n removeFavorite,\n affiliate,\n affiliateStats,\n createTicket,\n ticket,\n replyToTicket,\n updateProfile,\n updateAvatar,\n removeAvatar,\n emailPreferences,\n updateEmailPreferences,\n sessions,\n revokeSession,\n revokeAllSessions,\n reseller,\n applyForReseller,\n enrollAsReseller,\n acceptResellerInvite,\n resellerCatalog,\n quoteResellerOrder,\n resellerOrders,\n resellerOrder,\n resellerWallet,\n resellerApiKeys,\n\n // Search\n searchProducts,\n searchCatalogItems,\n\n // Invoices\n getInvoice,\n getInvoiceStatus,\n\n // Pages\n getPages,\n getPage,\n\n // Navigation\n getMenus,\n getMenu,\n getMenuBySlot,\n getMenuByTitle,\n getMenuSlotTitles,\n\n // Analytics\n trackPageView,\n getStorefrontOnlineUsers,\n getStorefrontRecentSales,\n touchStorefrontPresence,\n\n // Formatting\n createFormatter,\n formatPrice,\n\n // Cache\n clearCache,\n invalidateCache,\n getCacheStats,\n\n // Theme settings helpers\n fetchPublishedBuilderSettings,\n fetchPublishedThemeSettings,\n resolveDefaults,\n mergeSettings,\n};\n\n// Default export for ES modules\nexport default shoppex;\n\n// UMD global exposure — never clobber an already-initialized client. Theme\n// artifacts can load multiple SDK chunks; a late bundle must not reset init.\nif (typeof window !== 'undefined') {\n const w = window as unknown as { shoppex?: typeof shoppex };\n if (!w.shoppex?.isInitialized?.()) {\n w.shoppex = shoppex;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAuBA,IAAM,QAAQ,oBAAI,IAAiC;AACnD,IAAM,UAAU,oBAAI,IAA8B;AAElD,IAAM,QAAQ;AAAA,EACZ,MAAM;AAAA,EACN,QAAQ;AACV;AAEA,SAAS,UAAU,OAAqC;AACtD,SAAO,KAAK,IAAI,IAAI,MAAM;AAC5B;AAEO,SAAS,gBAA4B;AAC1C,SAAO;AAAA,IACL,MAAM,MAAM;AAAA,IACZ,QAAQ,MAAM;AAAA,IACd,iBAAiB,QAAQ;AAAA,IACzB,SAAS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ACA;AAAA;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAGA,IAAO,cAAQ;AAIf,IAAI,OAAO,WAAW,aAAa;AACjC,QAAM,IAAI;AACV,MAAI,CAAC,EAAE,SAAS,gBAAgB,GAAG;AACjC,MAAE,UAAU;AAAA,EACd;AACF;","names":["fetch","init","request","error","url","final","joiner","url","record","HexColorSchema","url","storageKey","cache","url","record","url","hashString","record","email","normalizeAffiliateCode","record","cachedShopId","record","email","STORAGE_PREFIX","isRecord"]}
1
+ {"version":3,"sources":["../../sdk/src/core/cache.ts","../../sdk/src/core/errors.ts","../../../node_modules/.bun/openapi-fetch@0.17.0/node_modules/openapi-fetch/src/index.js","../../contracts/src/navigation.ts","../../contracts/src/email-marketing.ts","../../contracts/src/payment-gateways.ts","../../contracts/src/style-center.ts","../../contracts/src/storefront-addons.ts","../../contracts/src/manual-gateway-template.ts","../../contracts/src/external-payment-adapter.ts","../../contracts/src/redirect-link-template.ts","../../contracts/src/invoice-wire.ts","../../contracts/src/catalog-unit-price.ts","../../contracts/src/index.ts","../../sdk/src/core/typed-client.ts","../../sdk/src/core/config.ts","../../sdk/src/utils/storefront-custom-fields.ts","../../sdk/src/utils/storefront-stock.ts","../../sdk/src/utils/storefront-catalog.ts","../../sdk/src/utils/storefront-search.ts","../../sdk/src/utils/storefront-contact.ts","../../sdk/src/core/endpoint.ts","../../sdk/src/utils/storage.ts","../../sdk/src/core/telemetry.ts","../../sdk/src/core/client.ts","../../sdk/src/modules/store.ts","../../sdk/src/modules/products.ts","../../sdk/src/modules/affiliates.ts","../../sdk/src/utils/cart-line-id.ts","../../sdk/src/utils/requested-currency.ts","../../sdk/src/modules/cart.ts","../../sdk/src/modules/checkout.ts","../../sdk/src/modules/checkout-challenge.ts","../../sdk/src/modules/coupons.ts","../../sdk/src/modules/reviews.ts","../../sdk/src/modules/customer.ts","../../sdk/src/modules/search.ts","../../sdk/src/modules/invoices.ts","../../sdk/src/modules/pages.ts","../../sdk/src/modules/navigation.ts","../../sdk/src/core/attribution.ts","../../sdk/src/modules/analytics.ts","../../sdk/src/modules/presence.ts","../../sdk/src/utils/format.ts","../../sdk/src/modules/theme.ts","../../sdk/src/index.ts"],"sourcesContent":["/**\n * In-memory cache with pending request deduplication.\n */\n\nexport interface CacheEntry<T> {\n data: T;\n expiresAt: number;\n updatedAt: number;\n ttl: number;\n}\n\nexport interface CacheOptions {\n ttl: number;\n staleWhileRevalidate?: boolean;\n}\n\nexport interface CacheStats {\n hits: number;\n misses: number;\n pendingRequests: number;\n entries: number;\n}\n\nconst cache = new Map<string, CacheEntry<unknown>>();\nconst pending = new Map<string, Promise<unknown>>();\n\nconst stats = {\n hits: 0,\n misses: 0,\n};\n\nfunction isExpired(entry: CacheEntry<unknown>): boolean {\n return Date.now() > entry.expiresAt;\n}\n\nexport function getCacheStats(): CacheStats {\n return {\n hits: stats.hits,\n misses: stats.misses,\n pendingRequests: pending.size,\n entries: cache.size,\n };\n}\n\nexport function clearCache(): void {\n cache.clear();\n pending.clear();\n}\n\nexport function invalidateCache(prefixOrKey: string): void {\n for (const key of cache.keys()) {\n if (key === prefixOrKey || key.startsWith(prefixOrKey)) {\n cache.delete(key);\n }\n }\n}\n\nexport function setCacheEntry<T>(key: string, data: T, ttl: number): void {\n const now = Date.now();\n cache.set(key, {\n data,\n ttl,\n updatedAt: now,\n expiresAt: now + ttl,\n });\n}\n\nexport function getCacheEntry<T>(key: string): CacheEntry<T> | null {\n const entry = cache.get(key) as CacheEntry<T> | undefined;\n if (!entry) return null;\n return entry;\n}\n\nexport async function getOrFetch<T>(\n key: string,\n fetcher: () => Promise<T>,\n options: CacheOptions,\n shouldCache: (value: T) => boolean = () => true\n): Promise<T> {\n const entry = getCacheEntry<T>(key);\n\n if (entry && !isExpired(entry)) {\n stats.hits += 1;\n return entry.data;\n }\n\n if (entry && options.staleWhileRevalidate) {\n stats.hits += 1;\n if (!pending.has(key)) {\n const refreshPromise = (async () => {\n try {\n const data = await fetcher();\n if (shouldCache(data)) {\n setCacheEntry(key, data, options.ttl);\n }\n return data;\n } finally {\n pending.delete(key);\n }\n })();\n pending.set(key, refreshPromise as Promise<unknown>);\n }\n return entry.data;\n }\n\n if (pending.has(key)) {\n return pending.get(key) as Promise<T>;\n }\n\n stats.misses += 1;\n const promise = (async () => {\n try {\n const data = await fetcher();\n if (shouldCache(data)) {\n setCacheEntry(key, data, options.ttl);\n }\n return data;\n } finally {\n pending.delete(key);\n }\n })();\n\n pending.set(key, promise as Promise<unknown>);\n return promise;\n}\n","/**\n * SDK Error Classes\n */\n\nexport class ShoppexError extends Error {\n public readonly code: string;\n public readonly statusCode?: number;\n\n constructor(message: string, code: string, statusCode?: number) {\n super(message);\n this.name = 'ShoppexError';\n this.code = code;\n this.statusCode = statusCode;\n Object.setPrototypeOf(this, ShoppexError.prototype);\n }\n}\n\nexport class NotInitializedError extends ShoppexError {\n constructor() {\n super(\n 'SDK not initialized. Call shoppex.init() first.',\n 'NOT_INITIALIZED'\n );\n this.name = 'NotInitializedError';\n Object.setPrototypeOf(this, NotInitializedError.prototype);\n }\n}\n\nexport class NetworkError extends ShoppexError {\n constructor(message: string, statusCode?: number) {\n super(message, 'NETWORK_ERROR', statusCode);\n this.name = 'NetworkError';\n Object.setPrototypeOf(this, NetworkError.prototype);\n }\n}\n\n/**\n * A refusal the SERVER made and named. `code` is the backend's `error_code`\n * (e.g. `errors.checkout.coupon_no_longer_valid`) — the branchable identity of\n * the refusal, stable across locales, unlike the localized `message`.\n *\n * Distinct from {@link NetworkError}, whose `code` is always `NETWORK_ERROR`:\n * that one means \"the request did not produce a named answer\".\n */\nexport class ApiError extends ShoppexError {\n public readonly errorParams?: Record<string, unknown>;\n\n constructor(\n message: string,\n code: string,\n statusCode?: number,\n errorParams?: Record<string, unknown>,\n ) {\n super(message, code, statusCode);\n this.name = 'ApiError';\n this.errorParams = errorParams;\n Object.setPrototypeOf(this, ApiError.prototype);\n }\n}\n\nexport class ValidationError extends ShoppexError {\n public readonly invalidFields?: string[];\n\n constructor(message: string, invalidFields?: string[]) {\n super(message, 'VALIDATION_ERROR');\n this.name = 'ValidationError';\n this.invalidFields = invalidFields;\n Object.setPrototypeOf(this, ValidationError.prototype);\n }\n}\n\nexport class CartError extends ShoppexError {\n constructor(message: string) {\n super(message, 'BASKET_ERROR');\n this.name = 'CartError';\n Object.setPrototypeOf(this, CartError.prototype);\n }\n}\n","// settings & const\nconst PATH_PARAM_RE = /\\{[^{}]+\\}/g;\n\nconst supportsRequestInitExt = () => {\n return (\n typeof process === \"object\" &&\n Number.parseInt(process?.versions?.node?.substring(0, 2)) >= 18 &&\n process.versions.undici\n );\n};\n\n/**\n * Returns a cheap, non-cryptographically-secure random ID\n * Courtesy of @imranbarbhuiya (https://github.com/imranbarbhuiya)\n */\nexport function randomID() {\n return Math.random().toString(36).slice(2, 11);\n}\n\n/**\n * Create an openapi-fetch client.\n * @type {import(\"./index.js\").default}\n */\nexport default function createClient(clientOptions) {\n let {\n baseUrl = \"\",\n Request: CustomRequest = globalThis.Request,\n fetch: baseFetch = globalThis.fetch,\n querySerializer: globalQuerySerializer,\n bodySerializer: globalBodySerializer,\n pathSerializer: globalPathSerializer,\n headers: baseHeaders,\n requestInitExt = undefined,\n ...baseOptions\n } = { ...clientOptions };\n requestInitExt = supportsRequestInitExt() ? requestInitExt : undefined;\n baseUrl = removeTrailingSlash(baseUrl);\n const globalMiddlewares = [];\n\n /**\n * Per-request fetch (keeps settings created in createClient()\n * @param {T} url\n * @param {import('./index.js').FetchOptions<T>} fetchOptions\n */\n async function coreFetch(schemaPath, fetchOptions) {\n const {\n baseUrl: localBaseUrl,\n fetch = baseFetch,\n Request = CustomRequest,\n headers,\n params = {},\n parseAs = \"json\",\n querySerializer: requestQuerySerializer,\n bodySerializer = globalBodySerializer ?? defaultBodySerializer,\n pathSerializer: requestPathSerializer,\n body,\n middleware: requestMiddlewares = [],\n ...init\n } = fetchOptions || {};\n let finalBaseUrl = baseUrl;\n if (localBaseUrl) {\n finalBaseUrl = removeTrailingSlash(localBaseUrl) ?? baseUrl;\n }\n\n let querySerializer =\n typeof globalQuerySerializer === \"function\"\n ? globalQuerySerializer\n : createQuerySerializer(globalQuerySerializer);\n if (requestQuerySerializer) {\n querySerializer =\n typeof requestQuerySerializer === \"function\"\n ? requestQuerySerializer\n : createQuerySerializer({\n ...(typeof globalQuerySerializer === \"object\" ? globalQuerySerializer : {}),\n ...requestQuerySerializer,\n });\n }\n\n const pathSerializer = requestPathSerializer || globalPathSerializer || defaultPathSerializer;\n\n const serializedBody =\n body === undefined\n ? undefined\n : bodySerializer(\n body,\n // Note: we declare mergeHeaders() both here and below because it’s a bit of a chicken-or-egg situation:\n // bodySerializer() needs all headers so we aren’t dropping ones set by the user, however,\n // the result of this ALSO sets the lowest-priority content-type header. So we re-merge below,\n // setting the content-type at the very beginning to be overwritten.\n // Lastly, based on the way headers work, it’s not a simple “present-or-not” check becauase null intentionally un-sets headers.\n mergeHeaders(baseHeaders, headers, params.header),\n );\n const finalHeaders = mergeHeaders(\n // with no body, we should not to set Content-Type\n serializedBody === undefined ||\n // if serialized body is FormData; browser will correctly set Content-Type & boundary expression\n serializedBody instanceof FormData\n ? {}\n : {\n \"Content-Type\": \"application/json\",\n },\n baseHeaders,\n headers,\n params.header,\n );\n\n // Client level middleware take priority over request-level middleware\n const finalMiddlewares = [...globalMiddlewares, ...requestMiddlewares];\n\n const requestInit = {\n redirect: \"follow\",\n ...baseOptions,\n ...init,\n body: serializedBody,\n headers: finalHeaders,\n };\n\n let id;\n let options;\n let request = new Request(\n createFinalURL(schemaPath, { baseUrl: finalBaseUrl, params, querySerializer, pathSerializer }),\n requestInit,\n );\n let response;\n\n /** Add custom parameters to Request object */\n for (const key in init) {\n if (!(key in request)) {\n request[key] = init[key];\n }\n }\n\n if (finalMiddlewares.length) {\n id = randomID();\n\n // middleware (request)\n options = Object.freeze({\n baseUrl: finalBaseUrl,\n fetch,\n parseAs,\n querySerializer,\n bodySerializer,\n pathSerializer,\n });\n for (const m of finalMiddlewares) {\n if (m && typeof m === \"object\" && typeof m.onRequest === \"function\") {\n const result = await m.onRequest({\n request,\n schemaPath,\n params,\n options,\n id,\n });\n if (result) {\n if (result instanceof Request) {\n request = result;\n } else if (result instanceof Response) {\n response = result;\n break;\n } else {\n throw new Error(\"onRequest: must return new Request() or Response() when modifying the request\");\n }\n }\n }\n }\n }\n\n if (!response) {\n // fetch!\n try {\n response = await fetch(request, requestInitExt);\n } catch (error) {\n let errorAfterMiddleware = error;\n // middleware (error)\n // execute in reverse-array order (first priority gets last transform)\n if (finalMiddlewares.length) {\n for (let i = finalMiddlewares.length - 1; i >= 0; i--) {\n const m = finalMiddlewares[i];\n if (m && typeof m === \"object\" && typeof m.onError === \"function\") {\n const result = await m.onError({\n request,\n error: errorAfterMiddleware,\n schemaPath,\n params,\n options,\n id,\n });\n if (result) {\n // if error is handled by returning a response, skip remaining middleware\n if (result instanceof Response) {\n errorAfterMiddleware = undefined;\n response = result;\n break;\n }\n\n if (result instanceof Error) {\n errorAfterMiddleware = result;\n continue;\n }\n\n throw new Error(\"onError: must return new Response() or instance of Error\");\n }\n }\n }\n }\n\n // rethrow error if not handled by middleware\n if (errorAfterMiddleware) {\n throw errorAfterMiddleware;\n }\n }\n\n // middleware (response)\n // execute in reverse-array order (first priority gets last transform)\n if (finalMiddlewares.length) {\n for (let i = finalMiddlewares.length - 1; i >= 0; i--) {\n const m = finalMiddlewares[i];\n if (m && typeof m === \"object\" && typeof m.onResponse === \"function\") {\n const result = await m.onResponse({\n request,\n response,\n schemaPath,\n params,\n options,\n id,\n });\n if (result) {\n if (!(result instanceof Response)) {\n throw new Error(\"onResponse: must return new Response() when modifying the response\");\n }\n response = result;\n }\n }\n }\n }\n }\n\n const contentLength = response.headers.get(\"Content-Length\");\n // handle empty content\n if (\n response.status === 204 ||\n request.method === \"HEAD\" ||\n (contentLength === \"0\" && !response.headers.get(\"Transfer-Encoding\")?.includes(\"chunked\"))\n ) {\n return response.ok ? { data: undefined, response } : { error: undefined, response };\n }\n\n // parse response (falling back to .text() when necessary)\n if (response.ok) {\n const getResponseData = async () => {\n // if \"stream\", skip parsing entirely\n if (parseAs === \"stream\") {\n return response.body;\n }\n\n if (parseAs === \"json\" && !contentLength) {\n // use text() when no content-length is provided to avoid errors parsing empty bodies (200 with no content)\n const raw = await response.text();\n return raw ? JSON.parse(raw) : undefined;\n }\n\n return await response[parseAs]();\n };\n return { data: await getResponseData(), response };\n }\n\n // handle errors\n let error = await response.text();\n try {\n error = JSON.parse(error); // attempt to parse as JSON\n } catch {\n // noop\n }\n return { error, response };\n }\n\n return {\n request(method, url, init) {\n return coreFetch(url, { ...init, method: method.toUpperCase() });\n },\n /** Call a GET endpoint */\n GET(url, init) {\n return coreFetch(url, { ...init, method: \"GET\" });\n },\n /** Call a PUT endpoint */\n PUT(url, init) {\n return coreFetch(url, { ...init, method: \"PUT\" });\n },\n /** Call a POST endpoint */\n POST(url, init) {\n return coreFetch(url, { ...init, method: \"POST\" });\n },\n /** Call a DELETE endpoint */\n DELETE(url, init) {\n return coreFetch(url, { ...init, method: \"DELETE\" });\n },\n /** Call a OPTIONS endpoint */\n OPTIONS(url, init) {\n return coreFetch(url, { ...init, method: \"OPTIONS\" });\n },\n /** Call a HEAD endpoint */\n HEAD(url, init) {\n return coreFetch(url, { ...init, method: \"HEAD\" });\n },\n /** Call a PATCH endpoint */\n PATCH(url, init) {\n return coreFetch(url, { ...init, method: \"PATCH\" });\n },\n /** Call a TRACE endpoint */\n TRACE(url, init) {\n return coreFetch(url, { ...init, method: \"TRACE\" });\n },\n /** Register middleware */\n use(...middleware) {\n for (const m of middleware) {\n if (!m) {\n continue;\n }\n if (typeof m !== \"object\" || !(\"onRequest\" in m || \"onResponse\" in m || \"onError\" in m)) {\n throw new Error(\"Middleware must be an object with one of `onRequest()`, `onResponse() or `onError()`\");\n }\n globalMiddlewares.push(m);\n }\n },\n /** Unregister middleware */\n eject(...middleware) {\n for (const m of middleware) {\n const i = globalMiddlewares.indexOf(m);\n if (i !== -1) {\n globalMiddlewares.splice(i, 1);\n }\n }\n },\n };\n}\n\nclass PathCallForwarder {\n constructor(client, url) {\n this.client = client;\n this.url = url;\n }\n\n GET = (init) => {\n return this.client.GET(this.url, init);\n };\n PUT = (init) => {\n return this.client.PUT(this.url, init);\n };\n POST = (init) => {\n return this.client.POST(this.url, init);\n };\n DELETE = (init) => {\n return this.client.DELETE(this.url, init);\n };\n OPTIONS = (init) => {\n return this.client.OPTIONS(this.url, init);\n };\n HEAD = (init) => {\n return this.client.HEAD(this.url, init);\n };\n PATCH = (init) => {\n return this.client.PATCH(this.url, init);\n };\n TRACE = (init) => {\n return this.client.TRACE(this.url, init);\n };\n}\n\nclass PathClientProxyHandler {\n constructor() {\n this.client = null;\n }\n\n // Assume the property is an URL.\n get(coreClient, url) {\n const forwarder = new PathCallForwarder(coreClient, url);\n this.client[url] = forwarder;\n return forwarder;\n }\n}\n\n/**\n * Wrap openapi-fetch client to support a path based API.\n * @type {import(\"./index.js\").wrapAsPathBasedClient}\n */\nexport function wrapAsPathBasedClient(coreClient) {\n const handler = new PathClientProxyHandler();\n const proxy = new Proxy(coreClient, handler);\n\n // Put the proxy on the prototype chain of the actual client.\n // This means if we do not have a memoized PathCallForwarder,\n // we fall back to the proxy to synthesize it.\n // However, the proxy itself is not on the hot-path (if we fetch the same\n // endpoint multiple times, only the first call will hit the proxy).\n function Client() {}\n Client.prototype = proxy;\n\n const client = new Client();\n\n // Feed the client back to the proxy handler so it can store the generated\n // PathCallForwarder.\n handler.client = client;\n\n return client;\n}\n\n/**\n * Convenience method to an openapi-fetch path based client.\n * Strictly equivalent to `wrapAsPathBasedClient(createClient(...))`.\n * @type {import(\"./index.js\").createPathBasedClient}\n */\nexport function createPathBasedClient(clientOptions) {\n return wrapAsPathBasedClient(createClient(clientOptions));\n}\n\n// utils\n\n/**\n * Serialize primitive param values\n * @type {import(\"./index.js\").serializePrimitiveParam}\n */\nexport function serializePrimitiveParam(name, value, options) {\n if (value === undefined || value === null) {\n return \"\";\n }\n if (typeof value === \"object\") {\n throw new Error(\n \"Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.\",\n );\n }\n return `${name}=${options?.allowReserved === true ? value : encodeURIComponent(value)}`;\n}\n\n/**\n * Serialize object param (shallow only)\n * @type {import(\"./index.js\").serializeObjectParam}\n */\nexport function serializeObjectParam(name, value, options) {\n if (!value || typeof value !== \"object\") {\n return \"\";\n }\n const values = [];\n const joiner =\n {\n simple: \",\",\n label: \".\",\n matrix: \";\",\n }[options.style] || \"&\";\n\n // explode: false\n if (options.style !== \"deepObject\" && options.explode === false) {\n for (const k in value) {\n values.push(k, options.allowReserved === true ? value[k] : encodeURIComponent(value[k]));\n }\n const final = values.join(\",\"); // note: values are always joined by comma in explode: false (but joiner can prefix)\n switch (options.style) {\n case \"form\": {\n return `${name}=${final}`;\n }\n case \"label\": {\n return `.${final}`;\n }\n case \"matrix\": {\n return `;${name}=${final}`;\n }\n default: {\n return final;\n }\n }\n }\n\n // explode: true\n for (const k in value) {\n const finalName = options.style === \"deepObject\" ? `${name}[${k}]` : k;\n values.push(serializePrimitiveParam(finalName, value[k], options));\n }\n const final = values.join(joiner);\n return options.style === \"label\" || options.style === \"matrix\" ? `${joiner}${final}` : final;\n}\n\n/**\n * Serialize array param (shallow only)\n * @type {import(\"./index.js\").serializeArrayParam}\n */\nexport function serializeArrayParam(name, value, options) {\n if (!Array.isArray(value)) {\n return \"\";\n }\n\n // explode: false\n if (options.explode === false) {\n const joiner = { form: \",\", spaceDelimited: \"%20\", pipeDelimited: \"|\" }[options.style] || \",\"; // note: for arrays, joiners vary wildly based on style + explode behavior\n const final = (options.allowReserved === true ? value : value.map((v) => encodeURIComponent(v))).join(joiner);\n switch (options.style) {\n case \"simple\": {\n return final;\n }\n case \"label\": {\n return `.${final}`;\n }\n case \"matrix\": {\n return `;${name}=${final}`;\n }\n // case \"spaceDelimited\":\n // case \"pipeDelimited\":\n default: {\n return `${name}=${final}`;\n }\n }\n }\n\n // explode: true\n const joiner = { simple: \",\", label: \".\", matrix: \";\" }[options.style] || \"&\";\n const values = [];\n for (const v of value) {\n if (options.style === \"simple\" || options.style === \"label\") {\n values.push(options.allowReserved === true ? v : encodeURIComponent(v));\n } else {\n values.push(serializePrimitiveParam(name, v, options));\n }\n }\n return options.style === \"label\" || options.style === \"matrix\"\n ? `${joiner}${values.join(joiner)}`\n : values.join(joiner);\n}\n\n/**\n * Serialize query params to string\n * @type {import(\"./index.js\").createQuerySerializer}\n */\nexport function createQuerySerializer(options) {\n return function querySerializer(queryParams) {\n const search = [];\n if (queryParams && typeof queryParams === \"object\") {\n for (const name in queryParams) {\n const value = queryParams[name];\n if (value === undefined || value === null) {\n continue;\n }\n if (Array.isArray(value)) {\n if (value.length === 0) {\n continue;\n }\n search.push(\n serializeArrayParam(name, value, {\n style: \"form\",\n explode: true,\n ...options?.array,\n allowReserved: options?.allowReserved || false,\n }),\n );\n continue;\n }\n if (typeof value === \"object\") {\n search.push(\n serializeObjectParam(name, value, {\n style: \"deepObject\",\n explode: true,\n ...options?.object,\n allowReserved: options?.allowReserved || false,\n }),\n );\n continue;\n }\n search.push(serializePrimitiveParam(name, value, options));\n }\n }\n return search.join(\"&\");\n };\n}\n\n/**\n * Handle different OpenAPI 3.x serialization styles\n * @type {import(\"./index.js\").defaultPathSerializer}\n * @see https://swagger.io/docs/specification/serialization/#path\n */\nexport function defaultPathSerializer(pathname, pathParams) {\n let nextURL = pathname;\n for (const match of pathname.match(PATH_PARAM_RE) ?? []) {\n let name = match.substring(1, match.length - 1);\n let explode = false;\n let style = \"simple\";\n if (name.endsWith(\"*\")) {\n explode = true;\n name = name.substring(0, name.length - 1);\n }\n if (name.startsWith(\".\")) {\n style = \"label\";\n name = name.substring(1);\n } else if (name.startsWith(\";\")) {\n style = \"matrix\";\n name = name.substring(1);\n }\n if (!pathParams || pathParams[name] === undefined || pathParams[name] === null) {\n continue;\n }\n const value = pathParams[name];\n if (Array.isArray(value)) {\n nextURL = nextURL.replace(match, serializeArrayParam(name, value, { style, explode }));\n continue;\n }\n if (typeof value === \"object\") {\n nextURL = nextURL.replace(match, serializeObjectParam(name, value, { style, explode }));\n continue;\n }\n if (style === \"matrix\") {\n nextURL = nextURL.replace(match, `;${serializePrimitiveParam(name, value)}`);\n continue;\n }\n nextURL = nextURL.replace(match, style === \"label\" ? `.${encodeURIComponent(value)}` : encodeURIComponent(value));\n }\n return nextURL;\n}\n\n/**\n * Serialize body object to string\n * @type {import(\"./index.js\").defaultBodySerializer}\n */\nexport function defaultBodySerializer(body, headers) {\n if (body instanceof FormData) {\n return body;\n }\n if (headers) {\n const contentType =\n headers.get instanceof Function\n ? (headers.get(\"Content-Type\") ?? headers.get(\"content-type\"))\n : (headers[\"Content-Type\"] ?? headers[\"content-type\"]);\n if (contentType === \"application/x-www-form-urlencoded\") {\n return new URLSearchParams(body).toString();\n }\n }\n return JSON.stringify(body);\n}\n\n/**\n * Construct URL string from baseUrl and handle path and query params\n * @type {import(\"./index.js\").createFinalURL}\n */\nexport function createFinalURL(pathname, options) {\n let finalURL = `${options.baseUrl}${pathname}`;\n if (options.params?.path) {\n finalURL = options.pathSerializer(finalURL, options.params.path);\n }\n let search = options.querySerializer(options.params.query ?? {});\n if (search.startsWith(\"?\")) {\n search = search.substring(1);\n }\n if (search) {\n finalURL += `?${search}`;\n }\n return finalURL;\n}\n\n/**\n * Merge headers a and b, with b taking priority\n * @type {import(\"./index.js\").mergeHeaders}\n */\nexport function mergeHeaders(...allHeaders) {\n const finalHeaders = new Headers();\n for (const h of allHeaders) {\n if (!h || typeof h !== \"object\") {\n continue;\n }\n const iterator = h instanceof Headers ? h.entries() : Object.entries(h);\n for (const [k, v] of iterator) {\n if (v === null) {\n finalHeaders.delete(k);\n } else if (Array.isArray(v)) {\n for (const v2 of v) {\n finalHeaders.append(k, v2);\n }\n } else if (v !== undefined) {\n finalHeaders.set(k, v);\n }\n }\n }\n return finalHeaders;\n}\n\n/**\n * Remove trailing slash from url\n * @type {import(\"./index.js\").removeTrailingSlash}\n */\nexport function removeTrailingSlash(url) {\n if (url.endsWith(\"/\")) {\n return url.substring(0, url.length - 1);\n }\n return url;\n}\n","const NAVIGATION_MENU_SLOT_CONFIG = {\n header: {\n title: 'Header',\n aliases: ['Header Menu'],\n },\n footer: {\n title: 'Footer',\n aliases: ['Footer Links', 'Legal Links'],\n },\n} as const;\n\nexport type NavigationMenuSlot = keyof typeof NAVIGATION_MENU_SLOT_CONFIG;\n\nfunction normalizeNavigationToken(value: string): string {\n return value.trim().toLowerCase().replace(/\\s+/g, ' ');\n}\n\nexport function getNavigationMenuCanonicalTitle(slot: NavigationMenuSlot): string {\n return NAVIGATION_MENU_SLOT_CONFIG[slot].title;\n}\n\nexport function getNavigationMenuTitles(slot: NavigationMenuSlot): string[] {\n const config = NAVIGATION_MENU_SLOT_CONFIG[slot];\n return [config.title, ...config.aliases];\n}\n\nexport function isNavigationMenuSlot(value: string): value is NavigationMenuSlot {\n return value in NAVIGATION_MENU_SLOT_CONFIG;\n}\n\nexport function resolveNavigationMenuSlot(value: string | null | undefined): NavigationMenuSlot | null {\n if (!value) return null;\n\n const normalizedValue = normalizeNavigationToken(value);\n for (const slot of Object.keys(NAVIGATION_MENU_SLOT_CONFIG) as NavigationMenuSlot[]) {\n const candidates = [slot, ...getNavigationMenuTitles(slot)];\n if (candidates.some((candidate) => normalizeNavigationToken(candidate) === normalizedValue)) {\n return slot;\n }\n }\n\n return null;\n}\n\nexport function isSystemNavigationMenuTitle(value: string | null | undefined): boolean {\n return resolveNavigationMenuSlot(value) !== null;\n}\n\nexport const NAVIGATION_MENU_SLOTS = Object.keys(NAVIGATION_MENU_SLOT_CONFIG) as NavigationMenuSlot[];\n","import * as z from 'zod/v4';\n\nexport const EmailMarketingConsentBasisSchema = z.enum(['CONSENT', 'SOFT_OPT_IN', 'TRANSACTIONAL_ONLY', 'UNKNOWN']);\nexport const EmailMarketingSuppressionReasonSchema = z.enum(['MANUAL_UNSUB', 'ONE_CLICK_UNSUB', 'HARD_BOUNCE', 'COMPLAINT', 'ADMIN_BLOCK']);\nexport const EmailMarketingCampaignTypeSchema = z.enum(['BROADCAST', 'AUTOMATION']);\nexport const EmailMarketingAutomationTriggerSchema = z.enum([\n 'ABANDONED_CART',\n 'POST_PURCHASE',\n 'WELCOME',\n 'WIN_BACK',\n 'RE_ENGAGEMENT',\n 'TAG_ADDED',\n]);\n\nexport const EmailMarketingContactCreateSchema = z.object({\n email: z.email(),\n name: z.string().trim().min(1).nullable().optional(),\n customer_id: z.string().uuid().nullable().optional(),\n tags: z.array(z.string().trim().min(1)).default([]),\n consent_basis: EmailMarketingConsentBasisSchema.default('UNKNOWN'),\n source: z.string().trim().min(1).default('dashboard'),\n});\n\nexport const EmailMarketingTemplateCreateSchema = z.object({\n name: z.string().trim().min(1),\n subject: z.string().trim().min(1),\n preheader: z.string().nullable().optional(),\n mjml_source: z.string().trim().min(1),\n builder_project_json: z.record(z.string(), z.unknown()).nullable().optional(),\n thumbnail_url: z.url().nullable().optional(),\n});\n\nexport const EmailMarketingTemplatePreviewSchema = z.object({\n mjml_source: z.string().trim().min(1),\n sample_variables: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport const EmailMarketingTemplateTestSendSchema = z.object({\n recipient_email: z.email(),\n sample_variables: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport const EmailMarketingSettingsUpdateSchema = z.object({\n marketing_enabled: z.boolean().optional(),\n default_from_name: z.string().trim().min(1).nullable().optional(),\n default_from_email: z.email().nullable().optional(),\n default_reply_to_email: z.email().nullable().optional(),\n physical_address: z.string().trim().min(1).nullable().optional(),\n physical_address_line2: z.string().trim().min(1).nullable().optional(),\n physical_city: z.string().trim().min(1).nullable().optional(),\n physical_postal_code: z.string().trim().min(1).nullable().optional(),\n physical_country: z.string().trim().length(2).nullable().optional(),\n daily_limit: z.number().int().positive().optional(),\n monthly_soft_cap: z.number().int().positive().optional(),\n});\n\nexport const EmailMarketingCampaignCreateSchema = z.object({\n type: EmailMarketingCampaignTypeSchema.default('BROADCAST'),\n name: z.string().trim().min(1),\n subject: z.string().trim().min(1),\n template_id: z.string().uuid(),\n list_id: z.string().uuid().nullable().optional(),\n segment_id: z.string().uuid().nullable().optional(),\n from_name: z.string().trim().min(1),\n from_email: z.email(),\n reply_to_email: z.email().nullable().optional(),\n schedule_at: z.string().datetime().nullable().optional(),\n target_emails: z.array(z.email()).max(0, 'Direct recipient entry is disabled. Use lists or segments built from Shoppex customers and paid order buyers.').default([]),\n idempotency_key: z.string().trim().min(1).nullable().optional(),\n});\n\nexport const EmailMarketingAutomationCreateSchema = z.object({\n name: z.string().trim().min(1),\n subject: z.string().trim().min(1),\n template_id: z.string().uuid(),\n from_name: z.string().trim().min(1),\n from_email: z.email(),\n reply_to_email: z.email().nullable().optional(),\n trigger: EmailMarketingAutomationTriggerSchema,\n delay_seconds: z.number().int().min(0).default(0),\n conditions: z.record(z.string(), z.unknown()).default({}),\n});\n\nexport const EmailMarketingAutomationTriggerEventSchema = z.object({\n trigger: EmailMarketingAutomationTriggerSchema,\n email: z.email(),\n customer_id: z.string().uuid().nullable().optional(),\n name: z.string().trim().min(1).nullable().optional(),\n consent_basis: EmailMarketingConsentBasisSchema.default('UNKNOWN'),\n variables: z.record(z.string(), z.unknown()).default({}),\n idempotency_key: z.string().trim().min(1).nullable().optional(),\n});\n\nexport const EmailMarketingSuppressionCreateSchema = z.object({\n email: z.email(),\n reason: EmailMarketingSuppressionReasonSchema.default('ADMIN_BLOCK'),\n notes: z.string().nullable().optional(),\n});\n\nexport type EmailMarketingContactCreate = z.infer<typeof EmailMarketingContactCreateSchema>;\nexport type EmailMarketingTemplateCreate = z.infer<typeof EmailMarketingTemplateCreateSchema>;\nexport type EmailMarketingTemplatePreview = z.infer<typeof EmailMarketingTemplatePreviewSchema>;\nexport type EmailMarketingTemplateTestSend = z.infer<typeof EmailMarketingTemplateTestSendSchema>;\nexport type EmailMarketingSettingsUpdate = z.infer<typeof EmailMarketingSettingsUpdateSchema>;\nexport type EmailMarketingCampaignCreate = z.infer<typeof EmailMarketingCampaignCreateSchema>;\nexport type EmailMarketingAutomationCreate = z.infer<typeof EmailMarketingAutomationCreateSchema>;\nexport type EmailMarketingAutomationTriggerEvent = z.infer<typeof EmailMarketingAutomationTriggerEventSchema>;\nexport type EmailMarketingSuppressionCreate = z.infer<typeof EmailMarketingSuppressionCreateSchema>;\n","import * as z from 'zod/v4';\n\n/**\n * External-adapter gateway-key helpers live here rather than in\n * external-payment-adapter.ts: this module is bundled into the checkout\n * client, and a relative import between the two breaks one of NodeNext tsc,\n * the tsup DTS build, or Turbopack depending on the specifier. The server-only\n * adapter module re-exports these for its consumers.\n */\nexport const EXTERNAL_PAYMENT_ADAPTER_GATEWAY_PREFIX = 'EXTERNAL:' as const;\n\nexport type ExternalPaymentAdapterGatewayKey =\n `${typeof EXTERNAL_PAYMENT_ADAPTER_GATEWAY_PREFIX}${string}`;\n\nconst EXTERNAL_ADAPTER_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n\nexport function buildExternalPaymentAdapterGatewayKey(\n adapterId: string,\n): ExternalPaymentAdapterGatewayKey | null {\n const normalizedId = adapterId.trim().toLowerCase();\n return EXTERNAL_ADAPTER_ID_PATTERN.test(normalizedId)\n ? `${EXTERNAL_PAYMENT_ADAPTER_GATEWAY_PREFIX}${normalizedId}`\n : null;\n}\n\nexport function parseExternalPaymentAdapterGatewayKey(gateway: string): string | null {\n const trimmed = gateway.trim();\n if (!/^external:/i.test(trimmed)) {\n return null;\n }\n\n const adapterId = trimmed.slice(trimmed.indexOf(':') + 1).trim().toLowerCase();\n return EXTERNAL_ADAPTER_ID_PATTERN.test(adapterId) ? adapterId : null;\n}\n\nexport function isExternalPaymentAdapterGatewayKey(\n gateway: string,\n): gateway is ExternalPaymentAdapterGatewayKey {\n return parseExternalPaymentAdapterGatewayKey(gateway) !== null;\n}\n\nexport const COIN_GATEWAY_KEYS = [\n 'BITCOIN',\n 'LITECOIN',\n 'ETHEREUM',\n 'BITCOIN_CASH',\n 'MONERO',\n 'RIPPLE',\n 'TRON',\n 'SOLANA',\n 'POLYGON',\n 'BINANCE_COIN',\n 'CRONOS',\n 'CONCORDIUM',\n 'NANO',\n 'DOGECOIN',\n 'DASH',\n] as const;\n\nexport const CRYPTO_PROVIDER_KEYS = [\n 'NOWPAYMENTS',\n 'CRYPTOMUS',\n 'OXAPAY',\n] as const;\n\nexport const MANAGED_CRYPTO_PROVIDER_KEYS = [\n 'NOWPAYMENTS_WHITELABEL',\n] as const;\n\nexport const GENERIC_STABLECOIN_GATEWAY_FAMILIES = {\n USDT: ['USDT_TRC20', 'USDT_ERC20', 'USDT_BEP20', 'USDT_POLYGON', 'USDT_SOL'],\n USDC: ['USDC_ERC20', 'USDC_TRC20', 'USDC_BEP20', 'USDC_POLYGON', 'USDC_SOL'],\n DAI: ['DAI_ERC20'],\n} as const;\n\nexport const GENERIC_STABLECOIN_GATEWAY_KEYS = Object.keys(\n GENERIC_STABLECOIN_GATEWAY_FAMILIES,\n) as Array<keyof typeof GENERIC_STABLECOIN_GATEWAY_FAMILIES>;\n\nexport const TOKEN_GATEWAY_KEYS = [\n ...GENERIC_STABLECOIN_GATEWAY_FAMILIES.USDT,\n ...GENERIC_STABLECOIN_GATEWAY_FAMILIES.USDC,\n ...GENERIC_STABLECOIN_GATEWAY_FAMILIES.DAI,\n] as const;\n\nexport const CRYPTO_GATEWAY_KEYS = [\n ...COIN_GATEWAY_KEYS,\n ...TOKEN_GATEWAY_KEYS,\n] as const;\n\nexport const LEGACY_CRYPTO_GATEWAY_KEYS = [\n 'BITCOIN_LN',\n] as const;\n\nexport const CRYPTO_PROVIDER_GATEWAY_KEYS = [\n ...CRYPTO_PROVIDER_KEYS,\n ...MANAGED_CRYPTO_PROVIDER_KEYS,\n] as const;\n\nexport const CONCRETE_CRYPTO_GATEWAY_KEYS = [\n ...CRYPTO_GATEWAY_KEYS,\n ...LEGACY_CRYPTO_GATEWAY_KEYS,\n] as const;\n\n// Embed v1 predates Concordium support. This list is frozen by design so new\n// shared-catalog coins cannot silently enter the embed-v1 session boundary.\nexport const EMBED_CRYPTO_GATEWAY_KEYS = [\n 'BITCOIN',\n 'LITECOIN',\n 'ETHEREUM',\n 'BITCOIN_CASH',\n 'MONERO',\n 'RIPPLE',\n 'TRON',\n 'SOLANA',\n 'POLYGON',\n 'BINANCE_COIN',\n 'CRONOS',\n 'NANO',\n 'DOGECOIN',\n 'DASH',\n 'USDT_TRC20',\n 'USDT_ERC20',\n 'USDT_BEP20',\n 'USDT_POLYGON',\n 'USDT_SOL',\n 'USDC_ERC20',\n 'USDC_TRC20',\n 'USDC_BEP20',\n 'USDC_POLYGON',\n 'USDC_SOL',\n 'DAI_ERC20',\n 'BITCOIN_LN',\n] as const;\n\nexport type CoinGatewayKey = typeof COIN_GATEWAY_KEYS[number];\nexport type TokenGatewayKey = typeof TOKEN_GATEWAY_KEYS[number];\nexport type CryptoGatewayKey = typeof CRYPTO_GATEWAY_KEYS[number];\nexport type LegacyCryptoGatewayKey = typeof LEGACY_CRYPTO_GATEWAY_KEYS[number];\nexport type CryptoProviderKey = typeof CRYPTO_PROVIDER_KEYS[number];\nexport type ManagedCryptoProviderKey = typeof MANAGED_CRYPTO_PROVIDER_KEYS[number];\nexport type CryptoProviderGatewayKey = typeof CRYPTO_PROVIDER_GATEWAY_KEYS[number];\n\nexport const NOWPAYMENTS_DYNAMIC_GATEWAY_PREFIX = 'NOWPAYMENTS:' as const;\nexport type NowPaymentsDynamicGatewayKey = `${typeof NOWPAYMENTS_DYNAMIC_GATEWAY_PREFIX}${string}`;\n\nconst NOWPAYMENTS_CURRENCY_CODE_PATTERN = /^[A-Z0-9]{2,12}$/;\n\nexport function buildNowPaymentsDynamicGatewayKey(\n currencyCode: string,\n): NowPaymentsDynamicGatewayKey | null {\n const normalizedCode = currencyCode.trim().toUpperCase();\n if (!NOWPAYMENTS_CURRENCY_CODE_PATTERN.test(normalizedCode)) {\n return null;\n }\n\n return `${NOWPAYMENTS_DYNAMIC_GATEWAY_PREFIX}${normalizedCode}`;\n}\n\nexport function parseNowPaymentsDynamicGatewayKey(gateway: string): string | null {\n const normalized = gateway.trim().toUpperCase();\n if (!normalized.startsWith(NOWPAYMENTS_DYNAMIC_GATEWAY_PREFIX)) {\n return null;\n }\n\n const code = normalized.slice(NOWPAYMENTS_DYNAMIC_GATEWAY_PREFIX.length);\n return NOWPAYMENTS_CURRENCY_CODE_PATTERN.test(code) ? code.toLowerCase() : null;\n}\n\nexport function isNowPaymentsDynamicGatewayKey(\n gateway: string,\n): gateway is NowPaymentsDynamicGatewayKey {\n return parseNowPaymentsDynamicGatewayKey(gateway) !== null;\n}\n\nexport const DEFAULT_NOWPAYMENTS_CRYPTO_GATEWAY_KEYS = CRYPTO_GATEWAY_KEYS;\n\nexport const DEFAULT_CRYPTOMUS_CRYPTO_GATEWAY_KEYS = [\n 'BITCOIN',\n 'LITECOIN',\n 'ETHEREUM',\n 'TRON',\n 'SOLANA',\n 'POLYGON',\n 'BINANCE_COIN',\n 'BITCOIN_CASH',\n 'MONERO',\n 'RIPPLE',\n 'DOGECOIN',\n 'USDT_TRC20',\n 'USDT_ERC20',\n 'USDT_BEP20',\n 'USDT_POLYGON',\n 'USDT_SOL',\n 'USDC_ERC20',\n 'USDC_BEP20',\n 'USDC_POLYGON',\n 'DAI_ERC20',\n] as const;\n\nexport const DEFAULT_OXAPAY_CRYPTO_GATEWAY_KEYS = [\n 'BITCOIN',\n 'LITECOIN',\n 'ETHEREUM',\n 'TRON',\n 'SOLANA',\n 'POLYGON',\n 'BINANCE_COIN',\n 'BITCOIN_CASH',\n 'MONERO',\n 'RIPPLE',\n 'DOGECOIN',\n 'USDT_TRC20',\n 'USDT_ERC20',\n 'USDT_BEP20',\n 'USDT_POLYGON',\n 'USDC_ERC20',\n] as const;\n\nexport const DEFAULT_PROVIDER_GATEWAY_SELECTIONS = {\n NOWPAYMENTS: DEFAULT_NOWPAYMENTS_CRYPTO_GATEWAY_KEYS,\n NOWPAYMENTS_WHITELABEL: DEFAULT_NOWPAYMENTS_CRYPTO_GATEWAY_KEYS,\n CRYPTOMUS: DEFAULT_CRYPTOMUS_CRYPTO_GATEWAY_KEYS,\n OXAPAY: DEFAULT_OXAPAY_CRYPTO_GATEWAY_KEYS,\n} as const;\n\nexport const POPULAR_PLATFORM_MANAGED_CRYPTO_GATEWAY_KEYS = [\n 'BITCOIN',\n 'LITECOIN',\n 'ETHEREUM',\n 'USDT_TRC20',\n 'USDT_ERC20',\n] as const;\n\nexport const CHECKOUT_METHOD_ORDER_KEYS = [\n 'STRIPE',\n 'PAYPAL',\n 'PAYPAL_FF',\n 'MOLLIE',\n 'AUTHORIZENET',\n 'NMI',\n 'SQUARE',\n 'SUMUP',\n 'SHOPIFY',\n 'PANDABASE',\n 'DEBLOMASSI',\n 'SHOPPEXPAY',\n 'MONEYMOTION',\n 'OVGC',\n 'WHOP',\n 'DODO',\n 'MAVERICK',\n 'CASHAPP',\n 'VENMO',\n 'CRYPTO',\n 'CUSTOMER_BALANCE',\n 'EXTERNAL',\n 'MANUAL',\n] as const;\n\n/**\n * Gateway implementations that remain in the codebase for historical payment\n * reads and webhook reconciliation, but cannot be configured or used for new\n * payments.\n */\nexport const DISABLED_PAYMENT_GATEWAY_KEYS = ['PANDABASE', 'STORRIK'] as const;\n\nconst DISABLED_PAYMENT_GATEWAY_KEY_SET = new Set<string>(\n DISABLED_PAYMENT_GATEWAY_KEYS,\n);\n\nexport function isDisabledPaymentGateway(gateway: string): boolean {\n return DISABLED_PAYMENT_GATEWAY_KEY_SET.has(gateway.trim().toUpperCase());\n}\n\n/**\n * Gateway implementations that remain in the codebase but must not be\n * advertised or selectable in merchant and buyer UI.\n */\nexport const RETIRED_UI_PAYMENT_GATEWAY_KEYS = [\n 'SHOPPEXPAY',\n ...DISABLED_PAYMENT_GATEWAY_KEYS,\n] as const;\n\nconst RETIRED_UI_PAYMENT_GATEWAY_KEY_SET = new Set<string>(\n RETIRED_UI_PAYMENT_GATEWAY_KEYS,\n);\n\nexport function isRetiredUiPaymentGateway(gateway: string): boolean {\n return RETIRED_UI_PAYMENT_GATEWAY_KEY_SET.has(gateway.trim().toUpperCase());\n}\n\nexport const DEFAULT_PAYPAL_FF_MANAGED_IPN_URL = 'https://paypal-ff.myshoppex.io';\n\nexport type CheckoutMethodOrderKey = typeof CHECKOUT_METHOD_ORDER_KEYS[number];\nexport type WritableCheckoutMethodOrderKey = Exclude<\n CheckoutMethodOrderKey,\n typeof DISABLED_PAYMENT_GATEWAY_KEYS[number]\n>;\n\nexport const WRITABLE_CHECKOUT_METHOD_ORDER_KEYS = CHECKOUT_METHOD_ORDER_KEYS.filter(\n (gateway): gateway is WritableCheckoutMethodOrderKey => !isDisabledPaymentGateway(gateway),\n);\n\nexport interface StoredPaymentGatewayRow {\n provider?: string | null;\n is_active?: boolean | number | string | null;\n isActive?: boolean | number | string | null;\n external_id?: string | null;\n externalId?: string | null;\n has_credentials?: boolean | number | string | null;\n hasCredentials?: boolean | number | string | null;\n has_settings?: boolean | number | string | null;\n hasSettings?: boolean | number | string | null;\n}\n\nexport interface OxapayCheckoutGatewayInfo {\n gateway_key?: string;\n gatewayKey?: string;\n display_name?: string;\n displayName?: string;\n symbol?: string;\n network?: string;\n network_name?: string | null;\n networkName?: string | null;\n required_confirmations?: number | null;\n requiredConfirmations?: number | null;\n deposit_min?: number | null;\n depositMin?: number | null;\n withdraw_min?: number | null;\n withdrawMin?: number | null;\n withdraw_fee?: number | null;\n withdrawFee?: number | null;\n}\n\nexport interface PaymentGatewaySecretRef {\n set: boolean;\n}\n\nexport interface PaymentGatewayHealth {\n status: 'READY' | 'NEEDS_ATTENTION';\n code?: string;\n message?: string;\n checked_at?: string;\n}\n\nexport interface PaymentGatewayState {\n provider: string;\n type: string;\n enabled: boolean;\n connected: boolean;\n credentials: Record<string, PaymentGatewaySecretRef>;\n public_config: Record<string, unknown>;\n webhook?: Record<string, unknown>;\n health?: PaymentGatewayHealth;\n}\n\nexport type GatewayIntegrationType =\n | 'OAUTH'\n | 'API_KEY'\n | 'SDK'\n | 'LEGACY'\n | 'DIRECT'\n | 'FORWARDING'\n | 'AGGREGATOR';\n\nexport interface NormalizedPaymentGatewayState {\n provider: string;\n id: string;\n type: string;\n name: string;\n enabled: boolean;\n connected: boolean;\n health_status?: 'READY' | 'NEEDS_ATTENTION';\n health_code?: string;\n health_message?: string;\n health_checked_at?: string;\n created_at: string;\n updated_at: string;\n integration_type?: 'SDK' | 'LEGACY';\n config?: Record<string, unknown>;\n}\n\nconst COIN_GATEWAY_KEY_SET = new Set<string>(COIN_GATEWAY_KEYS);\nconst TOKEN_GATEWAY_KEY_SET = new Set<string>(TOKEN_GATEWAY_KEYS);\nconst CRYPTO_GATEWAY_KEY_SET = new Set<string>(CRYPTO_GATEWAY_KEYS);\nconst LEGACY_CRYPTO_GATEWAY_KEY_SET = new Set<string>(LEGACY_CRYPTO_GATEWAY_KEYS);\nconst CRYPTO_PROVIDER_KEY_SET = new Set<string>(CRYPTO_PROVIDER_KEYS);\nconst MANAGED_CRYPTO_PROVIDER_KEY_SET = new Set<string>(MANAGED_CRYPTO_PROVIDER_KEYS);\nconst CRYPTO_PROVIDER_GATEWAY_KEY_SET = new Set<string>(CRYPTO_PROVIDER_GATEWAY_KEYS);\nconst CONCRETE_CRYPTO_GATEWAY_KEY_SET = new Set<string>(CONCRETE_CRYPTO_GATEWAY_KEYS);\nconst EMBED_CRYPTO_GATEWAY_KEY_SET = new Set<string>(EMBED_CRYPTO_GATEWAY_KEYS);\nconst GENERIC_STABLECOIN_GATEWAY_KEY_SET = new Set<string>(GENERIC_STABLECOIN_GATEWAY_KEYS);\nconst CHECKOUT_METHOD_ORDER_KEY_SET = new Set<string>(CHECKOUT_METHOD_ORDER_KEYS);\nconst CHECKOUT_METHOD_GROUP_BY_GATEWAY: Record<string, CheckoutMethodOrderKey> = {\n STRIPE: 'STRIPE',\n PAYPAL: 'PAYPAL',\n PAYPAL_FF: 'PAYPAL_FF',\n MOLLIE: 'MOLLIE',\n AUTHORIZENET: 'AUTHORIZENET',\n NMI: 'NMI',\n SQUARE: 'SQUARE',\n SUMUP: 'SUMUP',\n SHOPIFY: 'SHOPIFY',\n PANDABASE: 'PANDABASE',\n DEBLOMASSI: 'DEBLOMASSI',\n SHOPPEXPAY: 'SHOPPEXPAY',\n MONEYMOTION: 'MONEYMOTION',\n OVGC: 'OVGC',\n WHOP: 'WHOP',\n DODO: 'DODO',\n MAVERICK: 'MAVERICK',\n CASH_APP: 'CASHAPP',\n VENMO: 'VENMO',\n CUSTOMER_BALANCE: 'CUSTOMER_BALANCE',\n};\n\nconst LEGACY_GATEWAY_ALIASES: Record<string, string> = {\n CASHAPP: 'CASH_APP',\n PAYPAL_CREDIT_CARD: 'PAYPAL',\n EUTHEREUM: 'ETHEREUM',\n USDT_MATIC: 'USDT_POLYGON',\n USDC_MATIC: 'USDC_POLYGON',\n};\n\nfunction assertUniqueEntries(name: string, values: readonly string[]) {\n if (new Set(values).size !== values.length) {\n throw new Error(`${name} contains duplicate entries`);\n }\n}\n\nassertUniqueEntries('COIN_GATEWAY_KEYS', COIN_GATEWAY_KEYS);\nassertUniqueEntries('TOKEN_GATEWAY_KEYS', TOKEN_GATEWAY_KEYS);\nassertUniqueEntries('CRYPTO_GATEWAY_KEYS', CRYPTO_GATEWAY_KEYS);\nassertUniqueEntries('LEGACY_CRYPTO_GATEWAY_KEYS', LEGACY_CRYPTO_GATEWAY_KEYS);\nassertUniqueEntries('CRYPTO_PROVIDER_KEYS', CRYPTO_PROVIDER_KEYS);\nassertUniqueEntries('MANAGED_CRYPTO_PROVIDER_KEYS', MANAGED_CRYPTO_PROVIDER_KEYS);\nassertUniqueEntries('CRYPTO_PROVIDER_GATEWAY_KEYS', CRYPTO_PROVIDER_GATEWAY_KEYS);\nassertUniqueEntries('DEFAULT_NOWPAYMENTS_CRYPTO_GATEWAY_KEYS', DEFAULT_NOWPAYMENTS_CRYPTO_GATEWAY_KEYS);\nassertUniqueEntries('DEFAULT_CRYPTOMUS_CRYPTO_GATEWAY_KEYS', DEFAULT_CRYPTOMUS_CRYPTO_GATEWAY_KEYS);\nassertUniqueEntries('DEFAULT_OXAPAY_CRYPTO_GATEWAY_KEYS', DEFAULT_OXAPAY_CRYPTO_GATEWAY_KEYS);\n\nfor (const key of CRYPTO_GATEWAY_KEYS) {\n if (!COIN_GATEWAY_KEY_SET.has(key) && !TOKEN_GATEWAY_KEY_SET.has(key)) {\n throw new Error(`CRYPTO_GATEWAY_KEYS contains an unclassified gateway: ${key}`);\n }\n}\n\nexport function parseGatewayList(input: unknown): string[] {\n if (Array.isArray(input)) {\n return input.filter((entry): entry is string => typeof entry === 'string');\n }\n\n if (typeof input !== 'string') {\n return [];\n }\n\n const trimmed = input.trim();\n if (!trimmed) {\n return [];\n }\n\n if (trimmed.startsWith('[') && trimmed.endsWith(']')) {\n try {\n const parsed = JSON.parse(trimmed) as unknown;\n if (Array.isArray(parsed)) {\n return parsed.filter((entry): entry is string => typeof entry === 'string');\n }\n } catch {\n // Fallback to comma-separated parsing.\n }\n }\n\n return trimmed\n .split(',')\n .map((entry) => entry.trim())\n .filter(Boolean);\n}\n\nexport function normalizeGatewayKey(input: string): string {\n const trimmed = input.trim();\n if (!trimmed) {\n return '';\n }\n\n if (/^manual:/i.test(trimmed)) {\n const manualId = trimmed.slice(trimmed.indexOf(':') + 1).trim();\n return manualId ? `MANUAL:${manualId}` : 'MANUAL';\n }\n\n if (/^external:/i.test(trimmed)) {\n const adapterId = parseExternalPaymentAdapterGatewayKey(trimmed);\n return adapterId\n ? `${EXTERNAL_PAYMENT_ADAPTER_GATEWAY_PREFIX}${adapterId}`\n : trimmed.toUpperCase();\n }\n\n let normalized = trimmed.toUpperCase();\n\n const stablecoinNetworkMatch = normalized.match(/^(USDT|USDC|DAI):([A-Z0-9_]+)$/);\n if (stablecoinNetworkMatch) {\n const [, asset, rawNetwork] = stablecoinNetworkMatch;\n const network = rawNetwork === 'MATIC' ? 'POLYGON' : rawNetwork;\n normalized = `${asset}_${network}`;\n }\n\n return LEGACY_GATEWAY_ALIASES[normalized] ?? normalized;\n}\n\nexport function normalizeGatewayRestrictionValues(values: readonly string[]): string[] {\n const normalized = new Set<string>();\n\n for (const value of values) {\n const gateway = normalizeGatewayKey(value);\n if (gateway) {\n normalized.add(gateway);\n }\n }\n\n return [...normalized];\n}\n\nexport function normalizeGatewayRestrictionInput(input: unknown): string[] | null {\n const normalized = normalizeGatewayRestrictionValues(parseGatewayList(input));\n return normalized.length > 0 ? normalized : null;\n}\n\nexport function isValidProductGatewaySelection(input: string): boolean {\n const normalized = normalizeGatewayKey(input);\n if (\n !normalized\n || normalized === 'NULL'\n || normalized === 'UNDEFINED'\n || isDisabledPaymentGateway(normalized)\n ) {\n return false;\n }\n\n return normalized === 'CUSTOMER_BALANCE'\n || normalized === 'CRYPTO'\n || normalized === 'EXTERNAL'\n || parseExternalPaymentAdapterGatewayKey(normalized) !== null\n || isFinanceGateway(normalized)\n || isCryptoProviderGatewayKey(normalized)\n || isConcreteCryptoGatewayKey(normalized)\n || isGenericStablecoinGatewayKey(normalized);\n}\n\nexport function findInvalidProductGatewaySelections(input: unknown): string[] {\n return normalizeGatewayRestrictionValues(parseGatewayList(input))\n .filter((gateway) => !isValidProductGatewaySelection(gateway));\n}\n\n/**\n * Canonical persisted product restrictions. External write paths should reject\n * `invalid`; trusted repair/import paths may deliberately keep only `gateways`.\n */\nexport function partitionProductGatewaySelections(input: unknown): {\n gateways: string[];\n invalid: string[];\n} {\n const normalized = normalizeGatewayRestrictionValues(parseGatewayList(input));\n const gateways: string[] = [];\n const invalid: string[] = [];\n\n for (const gateway of normalized) {\n (isValidProductGatewaySelection(gateway) ? gateways : invalid).push(gateway);\n }\n\n return { gateways, invalid };\n}\n\nexport const FINANCE_GATEWAY_KEYS = [\n 'STRIPE', 'PAYPAL', 'PAYPAL_FF', 'SKRILL', 'CASHAPP', 'CASH_APP', 'PERFECT_MONEY',\n 'SQUARE', 'SUMUP', 'SHOPIFY', 'PANDABASE', 'DEBLOMASSI', 'SHOPPEXPAY', 'MONEYMOTION', 'OVGC', 'WHOP',\n 'DODO', 'MAVERICK', 'VENMO', 'MOLLIE', 'AUTHORIZENET', 'NMI',\n] as const;\n\nconst FINANCE_GATEWAY_KEY_SET = new Set<string>(\n FINANCE_GATEWAY_KEYS.map((gateway) => normalizeGatewayKey(gateway)),\n);\n\nexport function isFinanceGateway(gateway: string): boolean {\n const normalized = normalizeGatewayKey(gateway);\n return normalized === 'MANUAL'\n || normalized.startsWith('MANUAL:')\n || normalized === 'EXTERNAL'\n || parseExternalPaymentAdapterGatewayKey(normalized) !== null\n || FINANCE_GATEWAY_KEY_SET.has(normalized);\n}\n\nexport const VALID_PRODUCT_PAYMENT_GATEWAY_RESTRICTION_MODES = ['USE_STORE_DEFAULT', 'CUSTOM'] as const;\n\nexport type ProductPaymentGatewayRestrictionMode =\n (typeof VALID_PRODUCT_PAYMENT_GATEWAY_RESTRICTION_MODES)[number];\n\nexport function normalizeProductPaymentGatewayRestrictionMode(\n value: unknown,\n): ProductPaymentGatewayRestrictionMode {\n return value === 'CUSTOM' ? 'CUSTOM' : 'USE_STORE_DEFAULT';\n}\n\nexport function isProductGatewayRestrictionPublishable(\n mode: unknown,\n gateways: unknown,\n): boolean {\n return normalizeProductPaymentGatewayRestrictionMode(mode) !== 'CUSTOM'\n || normalizeGatewayRestrictionInput(gateways) !== null;\n}\n\nexport function isCoinGateway(gateway: string): gateway is CoinGatewayKey {\n return COIN_GATEWAY_KEY_SET.has(normalizeGatewayKey(gateway));\n}\n\nexport function isTokenGateway(gateway: string): gateway is TokenGatewayKey {\n return TOKEN_GATEWAY_KEY_SET.has(normalizeGatewayKey(gateway));\n}\n\nexport function isCryptoGateway(gateway: string): gateway is CryptoGatewayKey {\n return CRYPTO_GATEWAY_KEY_SET.has(normalizeGatewayKey(gateway));\n}\n\nexport function isProviderKey(gateway: string): gateway is CryptoProviderKey {\n return CRYPTO_PROVIDER_KEY_SET.has(normalizeGatewayKey(gateway));\n}\n\nexport function isManagedCryptoProviderKey(gateway: string): gateway is ManagedCryptoProviderKey {\n return MANAGED_CRYPTO_PROVIDER_KEY_SET.has(normalizeGatewayKey(gateway));\n}\n\nexport function isCryptoProviderGatewayKey(gateway: string): boolean {\n return CRYPTO_PROVIDER_GATEWAY_KEY_SET.has(normalizeGatewayKey(gateway));\n}\n\nexport function isGenericStablecoinGatewayKey(gateway: string): boolean {\n return GENERIC_STABLECOIN_GATEWAY_KEY_SET.has(normalizeGatewayKey(gateway));\n}\n\nexport function isConcreteCryptoGatewayKey(gateway: string): boolean {\n const normalizedGateway = normalizeGatewayKey(gateway);\n return isCryptoGateway(normalizedGateway)\n || LEGACY_CRYPTO_GATEWAY_KEY_SET.has(normalizedGateway)\n || CONCRETE_CRYPTO_GATEWAY_KEY_SET.has(normalizedGateway)\n || isNowPaymentsDynamicGatewayKey(normalizedGateway);\n}\n\nexport function isEmbedCryptoGatewayKey(gateway: string): boolean {\n // Exact-match on the frozen embed-v1 key set, NOT normalizeGatewayKey():\n // alias/colon rewriting (USDT:ERC20, USDT_MATIC, EUTHEREUM, …) would widen\n // the embed crypto boundary and auto-start crypto sessions for stored\n // gateway values the embed flow never accepted before.\n const exactGateway = gateway.trim().toUpperCase();\n return EMBED_CRYPTO_GATEWAY_KEY_SET.has(exactGateway)\n || isNowPaymentsDynamicGatewayKey(exactGateway);\n}\n\n/**\n * True for anything that resolves to a crypto payment, in every shape a gateway\n * key can take: a concrete coin (`BITCOIN`, `USDT:ERC20`), a generic stablecoin\n * whose chain the buyer still has to choose (`USDT`), and a provider key that\n * expands into a coin list (`OXAPAY`, `NOWPAYMENTS`, `CRYPTOMUS`).\n *\n * Use this — not `isConcreteCryptoGatewayKey` on its own — wherever the question\n * is \"may this be selected without the buyer choosing it?\". Selecting crypto\n * locks an exchange rate against a deposit address, so a caller that only\n * recognises concrete coins lets a provider key through and starts that session\n * anyway. Both halves of that mistake have been shipped before.\n */\nexport function isCryptoPaymentSelection(gateway: string): boolean {\n return isConcreteCryptoGatewayKey(gateway)\n || isGenericStablecoinGatewayKey(gateway)\n || isCryptoProviderGatewayKey(gateway);\n}\n\nexport function getConcreteCryptoGatewaySelections(gateways: Iterable<string>): string[] {\n const selected = new Set<string>();\n\n for (const gateway of gateways) {\n const normalized = normalizeGatewayKey(gateway);\n if (isConcreteCryptoGatewayKey(normalized)) {\n selected.add(normalized);\n }\n }\n\n return [...selected];\n}\n\n/**\n * External labels of crypto payment rails as emitted by the invoice read model\n * (resolveExternalCryptoRailLabel): WHITE_LABEL for managed provider rails and\n * NATIVE for self-hosted BTC/LTC nodes. These are rail labels, not gateway or\n * processor keys.\n */\nexport const CRYPTO_RAIL_GATEWAY_LABELS = ['WHITE_LABEL', 'NATIVE'] as const;\nexport type CryptoRailGatewayLabel = typeof CRYPTO_RAIL_GATEWAY_LABELS[number];\nconst CRYPTO_RAIL_GATEWAY_LABEL_SET = new Set<string>(CRYPTO_RAIL_GATEWAY_LABELS);\n\n/**\n * `PaymentProvider` enum value persisted for the self-hosted crypto rail. The\n * read model emits the 'NATIVE' rail label, while invoice and attempt rows carry\n * the provider value itself — both name the same rail.\n */\nexport const NATIVE_CRYPTO_PROVIDER_KEY = 'NATIVE_CRYPTO' as const;\n\n/** Processor keys persisted on crypto payment attempts (providers plus the NATIVE rail). */\nexport const CRYPTO_PAYMENT_PROCESSOR_KEYS = [...CRYPTO_PROVIDER_GATEWAY_KEYS, 'NATIVE'] as const;\nexport type CryptoPaymentProcessorKey = typeof CRYPTO_PAYMENT_PROCESSOR_KEYS[number];\nconst CRYPTO_PAYMENT_PROCESSOR_KEY_SET = new Set<string>(CRYPTO_PAYMENT_PROCESSOR_KEYS);\n\nexport function isCryptoRailGatewayLabel(value: string): value is CryptoRailGatewayLabel {\n return CRYPTO_RAIL_GATEWAY_LABEL_SET.has(normalizeGatewayKey(value));\n}\n\nexport function isCryptoPaymentProcessorKey(value: string): value is CryptoPaymentProcessorKey {\n return CRYPTO_PAYMENT_PROCESSOR_KEY_SET.has(normalizeGatewayKey(value));\n}\n\n/**\n * Single source of truth for \"does this invoice gateway value mean crypto\":\n * concrete coin/token keys (incl. legacy), generic stablecoin families,\n * provider gateway keys, and external rail labels. Consumers classifying\n * invoice rows by their public `gateway` value must use this instead of\n * maintaining local lists.\n */\nexport function isCryptoInvoiceGatewayLabel(value: string): boolean {\n const normalized = normalizeGatewayKey(value);\n return isConcreteCryptoGatewayKey(normalized)\n || GENERIC_STABLECOIN_GATEWAY_KEY_SET.has(normalized)\n || CRYPTO_PROVIDER_GATEWAY_KEY_SET.has(normalized)\n || CRYPTO_RAIL_GATEWAY_LABEL_SET.has(normalized)\n || normalized === NATIVE_CRYPTO_PROVIDER_KEY;\n}\n\nfunction getAvailableManualGatewaySelections(gateways: Iterable<string>): string[] {\n const selected = new Set<string>();\n\n for (const gateway of gateways) {\n const normalized = normalizeGatewayKey(gateway);\n if (normalized === 'MANUAL' || normalized.startsWith('MANUAL:')) {\n selected.add(normalized);\n }\n }\n\n return [...selected];\n}\n\nfunction getAvailableExternalAdapterSelections(gateways: Iterable<string>): string[] {\n const selected = new Set<string>();\n\n for (const gateway of gateways) {\n const normalized = normalizeGatewayKey(gateway);\n if (normalized === 'EXTERNAL' || parseExternalPaymentAdapterGatewayKey(normalized) !== null) {\n selected.add(normalized);\n }\n }\n\n return [...selected];\n}\n\nfunction getProviderScopedGatewaySelections(\n providerGateway: keyof typeof DEFAULT_PROVIDER_GATEWAY_SELECTIONS,\n availableGateways: string[],\n): string[] {\n const providerDefaults = DEFAULT_PROVIDER_GATEWAY_SELECTIONS[providerGateway];\n\n if (availableGateways.length === 0) {\n return [...providerDefaults];\n }\n\n const availableConcreteGateways = new Set(getConcreteCryptoGatewaySelections(availableGateways));\n return providerDefaults.filter((gateway) => availableConcreteGateways.has(gateway));\n}\n\nexport function expandGatewaySelection(\n gateway: string,\n options?: { availableGateways?: Iterable<string> },\n): string[] {\n const normalized = normalizeGatewayKey(gateway);\n if (!normalized) {\n return [];\n }\n\n const availableGateways = options?.availableGateways\n ? [...options.availableGateways].map((entry) => normalizeGatewayKey(entry)).filter(Boolean)\n : [];\n\n if (normalized === 'MANUAL') {\n return availableGateways.length > 0\n ? getAvailableManualGatewaySelections(availableGateways)\n : ['MANUAL'];\n }\n\n if (normalized.startsWith('MANUAL:')) {\n return [normalized];\n }\n\n if (normalized === 'EXTERNAL') {\n return availableGateways.length > 0\n ? getAvailableExternalAdapterSelections(availableGateways)\n : ['EXTERNAL'];\n }\n\n if (parseExternalPaymentAdapterGatewayKey(normalized) !== null) {\n return [normalized];\n }\n\n if (normalized.startsWith(EXTERNAL_PAYMENT_ADAPTER_GATEWAY_PREFIX)) {\n return [];\n }\n\n if (normalized === 'CRYPTO') {\n return availableGateways.length > 0\n ? getConcreteCryptoGatewaySelections(availableGateways)\n : [...CRYPTO_GATEWAY_KEYS];\n }\n\n if (isCryptoProviderGatewayKey(normalized)) {\n return getProviderScopedGatewaySelections(\n normalized as keyof typeof DEFAULT_PROVIDER_GATEWAY_SELECTIONS,\n availableGateways,\n );\n }\n\n if (isGenericStablecoinGatewayKey(normalized)) {\n const concreteGateways =\n GENERIC_STABLECOIN_GATEWAY_FAMILIES[\n normalized as keyof typeof GENERIC_STABLECOIN_GATEWAY_FAMILIES\n ];\n\n if (availableGateways.length > 0) {\n const availableSet = new Set(availableGateways);\n return concreteGateways.filter((entry) => availableSet.has(entry));\n }\n\n return [...concreteGateways];\n }\n\n return [normalized];\n}\n\nexport function resolveConcreteGatewaySelections(\n input: unknown,\n options?: { availableGateways?: Iterable<string> },\n): string[] | null {\n const normalized = normalizeGatewayRestrictionInput(input);\n if (!normalized) {\n return null;\n }\n\n const resolved = new Set<string>();\n for (const gateway of normalized) {\n for (const expanded of expandGatewaySelection(gateway, options)) {\n resolved.add(expanded);\n }\n }\n\n return [...resolved];\n}\n\nexport function normalizeCheckoutMethodOrder(\n input: Iterable<string> | null | undefined,\n): CheckoutMethodOrderKey[] {\n if (!input) {\n return [];\n }\n\n const normalized = new Set<CheckoutMethodOrderKey>();\n\n for (const entry of input) {\n if (typeof entry !== 'string') {\n continue;\n }\n\n const candidate = entry.trim().toUpperCase();\n if (CHECKOUT_METHOD_ORDER_KEY_SET.has(candidate)) {\n normalized.add(candidate as CheckoutMethodOrderKey);\n }\n }\n\n return [...normalized];\n}\n\nexport function resolveCheckoutMethodOrder(\n input: Iterable<string> | null | undefined,\n): CheckoutMethodOrderKey[] {\n const normalized = normalizeCheckoutMethodOrder(input);\n const resolved = [...normalized];\n\n for (const key of CHECKOUT_METHOD_ORDER_KEYS) {\n if (!resolved.includes(key)) {\n resolved.push(key);\n }\n }\n\n return resolved;\n}\n\nexport function getCheckoutMethodOrderGroup(\n gateway: string,\n): CheckoutMethodOrderKey | null {\n const normalized = normalizeGatewayKey(gateway);\n if (!normalized) {\n return null;\n }\n\n if (normalized === 'MANUAL' || normalized.startsWith('MANUAL:')) {\n return 'MANUAL';\n }\n\n if (normalized === 'EXTERNAL' || parseExternalPaymentAdapterGatewayKey(normalized) !== null) {\n return 'EXTERNAL';\n }\n\n if (isCryptoProviderGatewayKey(normalized) || isConcreteCryptoGatewayKey(normalized)) {\n return 'CRYPTO';\n }\n\n return CHECKOUT_METHOD_GROUP_BY_GATEWAY[normalized] ?? null;\n}\n\nexport function sortGatewaysByCheckoutMethodOrder(\n gateways: Iterable<string>,\n input: Iterable<string> | null | undefined,\n): string[] {\n const explicitOrder = normalizeCheckoutMethodOrder(input);\n if (explicitOrder.length === 0) {\n return [...gateways];\n }\n\n const resolvedOrder = resolveCheckoutMethodOrder(explicitOrder);\n const orderIndex = new Map(\n resolvedOrder.map((key, index) => [key, index] as const),\n );\n\n return [...gateways].sort((left, right) => {\n const leftGroup = getCheckoutMethodOrderGroup(left);\n const rightGroup = getCheckoutMethodOrderGroup(right);\n const leftIndex = leftGroup ? (orderIndex.get(leftGroup) ?? Number.MAX_SAFE_INTEGER) : Number.MAX_SAFE_INTEGER;\n const rightIndex = rightGroup ? (orderIndex.get(rightGroup) ?? Number.MAX_SAFE_INTEGER) : Number.MAX_SAFE_INTEGER;\n\n if (leftIndex !== rightIndex) {\n return leftIndex - rightIndex;\n }\n\n return 0;\n });\n}\n\nexport function getCheckoutMethodOrderKeysForGateways(\n gateways: Iterable<string>,\n input?: Iterable<string> | null,\n): CheckoutMethodOrderKey[] {\n const orderedGroups = new Set<CheckoutMethodOrderKey>();\n\n for (const gateway of sortGatewaysByCheckoutMethodOrder(gateways, input)) {\n const group = getCheckoutMethodOrderGroup(gateway);\n if (group) {\n orderedGroups.add(group);\n }\n }\n\n return [...orderedGroups];\n}\n\nexport function getCheckoutMethodOrderLabel(key: CheckoutMethodOrderKey): string {\n switch (key) {\n case 'STRIPE':\n return 'Credit / Debit Cards';\n case 'PAYPAL':\n return 'PayPal';\n case 'PAYPAL_FF':\n return 'PayPal F&F';\n case 'MOLLIE':\n return 'Mollie';\n case 'AUTHORIZENET':\n return 'Authorize.net';\n case 'NMI':\n return 'NMI';\n case 'SQUARE':\n return 'Square';\n case 'SUMUP':\n return 'SumUp';\n case 'SHOPIFY':\n return 'Shopify';\n case 'PANDABASE':\n return 'Pandabase';\n case 'DEBLOMASSI':\n return 'DebloMassi';\n case 'SHOPPEXPAY':\n return 'Card payment';\n case 'MONEYMOTION':\n return 'MoneyMotion';\n case 'OVGC':\n return 'OVGC Payments';\n case 'WHOP':\n return 'Whop';\n case 'DODO':\n return 'Dodo Payments';\n case 'MAVERICK':\n return 'Maverick Payments';\n case 'CASHAPP':\n return 'Cash App';\n case 'VENMO':\n return 'Venmo';\n case 'CRYPTO':\n return 'Crypto';\n case 'CUSTOMER_BALANCE':\n return 'Store Credit';\n case 'EXTERNAL':\n return 'External Providers';\n case 'MANUAL':\n return 'Manual Payment Methods';\n }\n}\n\nexport const SecretRefSchema = z.object({\n set: z.boolean(),\n});\n\nexport const PaymentGatewayHealthSchema = z.object({\n status: z.enum(['READY', 'NEEDS_ATTENTION']).optional(),\n code: z.string().optional(),\n message: z.string().optional(),\n checked_at: z.string().optional(),\n});\n\nexport const PaymentGatewayStateSchema = z.object({\n provider: z.string(),\n type: z.string(),\n enabled: z.boolean(),\n connected: z.boolean(),\n credentials: z.record(z.string(), SecretRefSchema),\n public_config: z.record(z.string(), z.unknown()),\n webhook: z.record(z.string(), z.unknown()).optional(),\n health: PaymentGatewayHealthSchema.optional(),\n});\n\nexport type PaymentGatewayStateFromSchema = z.infer<typeof PaymentGatewayStateSchema>;\n","import * as z from 'zod/v4';\n\n/** Canonical Shoppex hosted-checkout brand (matches `apps/checkout/app/globals.css` `--primary`). */\nexport const CHECKOUT_PLATFORM_BRAND_COLOR = '#7c3aed';\n\n/** Curated font label for Style Center controls (runtime loads Geist via `next/font`). */\nexport const CHECKOUT_PLATFORM_FONT_FAMILY = 'Geist';\n\n/** Stripe/PayPal appearance and CSS var() fallbacks when no merchant brand override exists. */\nexport const CHECKOUT_PLATFORM_BRAND_FALLBACK = CHECKOUT_PLATFORM_BRAND_COLOR;\n\n/** Runtime font stack when no merchant typography override exists. */\nexport const CHECKOUT_PLATFORM_FONT_STACK =\n 'var(--font-geist-sans, Geist), Geist, system-ui, sans-serif';\n\n/** Stripe appearance fontFamily (no CSS var() — provider SDK string). */\nexport const CHECKOUT_PLATFORM_STRIPE_FONT_FAMILY = 'Geist, system-ui, sans-serif';\n\nconst BRAND_DERIVED_TOKEN_KEYS: Partial<Record<string, string>> = {\n 'component.primaryButton.background': 'color.brand',\n 'component.radio.checkedFill': 'color.brand',\n};\n\n/**\n * Platform baseline values for unset checkout tokens.\n * Used by Style Center UI, validation, and documentation — not emitted to live CSS unless explicit.\n *\n * Every neutral below is a value from the hosted checkout's tonal ladder\n * (`apps/checkout/app/globals.css`, dark appearance). The zinc palette these\n * replace was a SECOND palette: the Style Center baseline painted `#18181b` /\n * `#27272a` / `#222222` over a checkout whose own surfaces are `--surface-0`\n * … `--surface-4`, so a shop that had never opened the Style Center saw the\n * old design repainted on top of the new one.\n *\n * They are also PURE neutrals — R = G = B — for the same reason the ladder is:\n * a baseline that carries a hue is a hue painted over every merchant's brand,\n * and this file is what an untouched shop actually renders. The white alphas\n * below follow the same rule; they used to be a warm `255,252,248`, which is\n * what turned every uncustomised chip and product plate a shade of brown.\n */\nexport const CHECKOUT_PLATFORM_BASELINE: Partial<Record<string, string | number>> = {\n 'color.brand': CHECKOUT_PLATFORM_BRAND_COLOR,\n 'color.brandContrast': '#ffffff',\n // `--surface-1`: the ground a column sits on.\n 'color.background': '#111111',\n // `--surface-0`: the working panel the buyer pays in.\n 'color.surface': '#1b1b1b',\n // `--card`: a panel raised above that ground.\n 'color.surfaceRaised': '#222222',\n 'color.text': '#f5f5f5',\n 'color.textMuted': '#a1a1a1',\n 'color.border': '#2c2c2c',\n 'color.focus': CHECKOUT_PLATFORM_BRAND_COLOR,\n 'color.success': '#22c55e',\n 'color.warning': '#f59e0b',\n 'color.error': '#ef4444',\n 'typography.fontFamily': CHECKOUT_PLATFORM_FONT_FAMILY,\n 'typography.baseSize': 14,\n // 10 across the board, and the same 10 the token definitions below carry:\n // this map is read by `resolveCheckoutStyleTokenValue` while the emitted CSS\n // reads `definition.default`, so a disagreement between them means the\n // Style Center shows one radius and the buyer sees another. The checkout has\n // TWO radii — 8 for marks under 16px, 10 for every control and surface — and\n // a button is a control.\n //\n // Down from 12 with `--radius-lg` in apps/checkout/app/globals.css, and the\n // two have to move together: the slot layer paints\n // `var(--spx-checkout-card-radius, var(--radius-lg))` with `!important`, so\n // THIS value is the one a hosted buyer actually sees.\n 'shape.buttonRadius': 10,\n 'shape.inputRadius': 10,\n 'shape.cardRadius': 10,\n 'spacing.density': 'comfortable',\n 'spacing.controlHeight': 48,\n 'component.primaryButton.text': '#ffffff',\n 'component.input.background': '#292929',\n 'component.input.border': '#2c2c2c',\n 'component.input.focusRing': 'rgba(124,58,237,0.35)',\n 'component.productCard.background': 'rgba(255,255,255,0.03)',\n 'component.productCard.border': 'rgba(255,255,255,0.06)',\n 'component.productCard.shadow': 'none',\n 'component.productImage.background': 'rgba(255,255,255,0.06)',\n 'component.productImage.border': 'rgba(255,255,255,0.04)',\n 'component.productImage.icon': 'rgba(250,250,250,0.4)',\n 'component.brandAvatar.background': 'rgba(255,255,255,0.06)',\n 'component.brandAvatar.text': '#ffffff',\n 'component.brandAvatar.border': 'rgba(255,255,255,0.1)',\n 'component.pill.background': 'rgba(255,255,255,0.04)',\n 'component.pill.border': 'rgba(255,255,255,0.08)',\n 'component.pill.text': '#a1a1a1',\n 'component.errorBanner.background': 'rgba(239,68,68,0.1)',\n 'component.errorBanner.border': 'rgba(239,68,68,0.2)',\n 'component.errorBanner.text': '#ef4444',\n 'component.radio.idleRing': 'rgba(161,161,161,0.5)',\n 'component.radio.checkedIcon': '#ffffff',\n 'component.divider.color': 'rgba(255,255,255,0.06)',\n};\n\nexport function isExplicitCheckoutStyleTokenValue(value: unknown): value is string | number {\n if (typeof value === 'number' && Number.isFinite(value)) return true;\n if (typeof value === 'string') return value.trim().length > 0;\n return false;\n}\n\nfunction resolveCheckoutStyleBrandDerivedTokenKey(key: string): string | undefined {\n return BRAND_DERIVED_TOKEN_KEYS[key];\n}\n\nexport const checkoutStyleSurfaceValues = ['checkout', 'payment_link', 'embed'] as const;\nexport const checkoutStyleDensityValues = ['comfortable', 'compact'] as const;\n\nexport const checkoutStyleModeValues = ['light', 'dark', 'system'] as const;\nexport const checkoutStylePaymentLinkHeroPositionValues = ['top', 'side', 'background'] as const;\nexport const embedCloseButtonStyleValues = ['ghost', 'outlined', 'filled'] as const;\nexport const embedMobileLayoutValues = ['sheet', 'fullscreen', 'center'] as const;\nexport const embedContentVisibilityValues = ['visible', 'hidden'] as const;\nexport const checkoutStyleManagedAssetHostValues = ['assets.shoppex.io', 'cdn.shoppex.io', 'imagedelivery.net'] as const;\n\nexport const CheckoutStyleSurfaceSchema = z.enum(checkoutStyleSurfaceValues);\nexport const CheckoutStyleDensitySchema = z.enum(checkoutStyleDensityValues);\nexport const CheckoutStyleModeSchema = z.enum(checkoutStyleModeValues);\nexport const CheckoutStylePaymentLinkHeroPositionSchema = z.enum(checkoutStylePaymentLinkHeroPositionValues);\nexport const EmbedCloseButtonStyleSchema = z.enum(embedCloseButtonStyleValues);\nexport const EmbedMobileLayoutSchema = z.enum(embedMobileLayoutValues);\nexport const EmbedContentVisibilitySchema = z.enum(embedContentVisibilityValues);\n\nexport type CheckoutStyleSurface = z.infer<typeof CheckoutStyleSurfaceSchema>;\nexport type CheckoutStyleDensity = z.infer<typeof CheckoutStyleDensitySchema>;\nexport type CheckoutStyleMode = z.infer<typeof CheckoutStyleModeSchema>;\nexport type CheckoutStylePaymentLinkHeroPosition = z.infer<typeof CheckoutStylePaymentLinkHeroPositionSchema>;\nexport type EmbedCloseButtonStyle = z.infer<typeof EmbedCloseButtonStyleSchema>;\nexport type EmbedMobileLayout = z.infer<typeof EmbedMobileLayoutSchema>;\nexport type EmbedContentVisibility = z.infer<typeof EmbedContentVisibilitySchema>;\n\nexport const CHECKOUT_STYLE_TOKEN_SCHEMA_VERSION = 1;\nexport const SHOPPEX_STYLE_THEME_EXPORT_FORMAT_VERSION = 2;\n\nexport type CheckoutStyleTokenType = 'asset_url' | 'color' | 'font' | 'number' | 'select' | 'shadow';\nexport type CheckoutStyleTokenGroup = 'asset' | 'brand' | 'color' | 'typography' | 'shape' | 'spacing' | 'component' | 'embed';\n\nexport type CheckoutStyleCssTokenDefinition = {\n key: string;\n cssVar: `--spx-checkout-${string}` | `--spx-embed-${string}`;\n group: Exclude<CheckoutStyleTokenGroup, 'asset'>;\n type: Exclude<CheckoutStyleTokenType, 'asset_url'>;\n default: string | number;\n min?: number;\n max?: number;\n step?: number;\n unit?: 'px' | 'rem';\n allowedValues?: readonly string[];\n protected?: boolean;\n};\n\nexport type CheckoutStyleAssetTokenDefinition = {\n key: string;\n group: 'asset';\n type: 'asset_url' | 'number' | 'select';\n default: string | number | null;\n accept?: readonly string[];\n maxBytes?: number;\n min?: number;\n max?: number;\n step?: number;\n unit?: 'px';\n allowedValues?: readonly string[];\n surface?: CheckoutStyleSurface;\n};\n\nexport type CheckoutStyleTokenDefinition = CheckoutStyleCssTokenDefinition | CheckoutStyleAssetTokenDefinition;\n\nexport const checkoutStyleTokenDefinitions = [\n { key: 'color.brand', cssVar: '--spx-checkout-brand', group: 'brand', type: 'color', default: CHECKOUT_PLATFORM_BRAND_COLOR },\n { key: 'color.brandContrast', cssVar: '--spx-checkout-brand-contrast', group: 'brand', type: 'color', default: '#ffffff', protected: true },\n // Empty default → CSS variable is omitted by createCheckoutStyleCssVariables,\n // so the layout's `var(--spx-checkout-bg, fallback)` resolves to the original\n // Tailwind/ambient-gradient fallback for shops that haven't customised the\n // background. Setting an explicit hex would clobber the ambient gradient and\n // the right-panel `--surface-2` accent for every default-theme checkout.\n { key: 'color.background', cssVar: '--spx-checkout-bg', group: 'color', type: 'color', default: '' },\n // The four neutrals below are the DARK appearance of the hosted checkout's\n // tonal ladder (`apps/checkout/app/globals.css`); the light values sit in\n // CHECKOUT_PLATFORM_BASELINE_LIGHT_DEFAULTS. They are materialised into the\n // live checkout root, so they are what a shop with no Style Center theme\n // actually renders — which is why each one has to name the SAME rung the\n // component paints, not a palette of its own.\n // surface → `--surface-0`, the working panel the buyer pays in\n // surfaceRaised → `--card`, a panel raised above that panel\n // (the provider widget frame and its loading skeleton)\n // text → `--foreground`\n // textMuted → `--muted-foreground`\n // border → `--border`\n { key: 'color.surface', cssVar: '--spx-checkout-surface', group: 'color', type: 'color', default: '#1b1b1b' },\n { key: 'color.surfaceRaised', cssVar: '--spx-checkout-surface-raised', group: 'color', type: 'color', default: '#222222' },\n { key: 'color.text', cssVar: '--spx-checkout-text', group: 'color', type: 'color', default: '#f5f5f5', protected: true },\n { key: 'color.textMuted', cssVar: '--spx-checkout-text-muted', group: 'color', type: 'color', default: '#a1a1a1' },\n // Never '': the border token feeds runtime-style fallbacks for inputs,\n // provider widgets and buttons, and an unset value turns those slots'\n // `var(--spx-checkout-border, …)` chains loose. The hosted checkout draws\n // almost no hairlines any more — the slots that still do read this, the rest\n // resolve their border to `transparent` in the system CSS.\n { key: 'color.border', cssVar: '--spx-checkout-border', group: 'color', type: 'color', default: '#2c2c2c' },\n { key: 'color.focus', cssVar: '--spx-checkout-focus', group: 'color', type: 'color', default: CHECKOUT_PLATFORM_BRAND_COLOR, protected: true },\n { key: 'color.success', cssVar: '--spx-checkout-success', group: 'color', type: 'color', default: '#22c55e', protected: true },\n { key: 'color.warning', cssVar: '--spx-checkout-warning', group: 'color', type: 'color', default: '#f59e0b', protected: true },\n { key: 'color.error', cssVar: '--spx-checkout-error', group: 'color', type: 'color', default: '#ef4444', protected: true },\n { key: 'typography.fontFamily', cssVar: '--spx-checkout-font', group: 'typography', type: 'font', default: CHECKOUT_PLATFORM_FONT_FAMILY },\n // Optional Google Fonts family. Empty default → CSS variable is omitted\n // so the curated fontFamily wins. When set, the storefront also injects\n // a <link rel=\"stylesheet\"> to fonts.googleapis.com so the family is\n // actually loaded.\n { key: 'typography.googleFontFamily', cssVar: '--spx-checkout-google-font', group: 'typography', type: 'font', default: '' },\n { key: 'typography.baseSize', cssVar: '--spx-checkout-font-size', group: 'typography', type: 'number', default: 14, min: 12, max: 18, step: 1, unit: 'px' },\n // 12px, not 8, for the same reason as the input below: the hosted pay CTA is\n // `rounded-xl` and this token is materialised over every slotted button. At 8\n // the store-credit and manual actions rendered one step tighter than the\n // field directly above them and than the CTA they stand in for.\n { key: 'shape.buttonRadius', cssVar: '--spx-checkout-button-radius', group: 'shape', type: 'number', default: 10, min: 0, max: 24, step: 1, unit: 'px' },\n // 12px, not 8: the hosted `Input` primitive is `rounded-lg`, and this token is\n // materialised over it. At 8 the system CSS rounded every field one step\n // tighter than the component that drew it.\n { key: 'shape.inputRadius', cssVar: '--spx-checkout-input-radius', group: 'shape', type: 'number', default: 10, min: 0, max: 24, step: 1, unit: 'px' },\n { key: 'shape.cardRadius', cssVar: '--spx-checkout-card-radius', group: 'shape', type: 'number', default: 10, min: 0, max: 28, step: 1, unit: 'px' },\n {\n key: 'spacing.density',\n cssVar: '--spx-checkout-density',\n group: 'spacing',\n type: 'select',\n default: 'comfortable',\n allowedValues: checkoutStyleDensityValues,\n },\n { key: 'spacing.controlHeight', cssVar: '--spx-checkout-control-height', group: 'spacing', type: 'number', default: 48, min: 36, max: 56, step: 2, unit: 'px' },\n { key: 'component.primaryButton.background', cssVar: '--spx-checkout-button-bg', group: 'component', type: 'color', default: '', protected: true },\n { key: 'component.primaryButton.text', cssVar: '--spx-checkout-button-text', group: 'component', type: 'color', default: '#ffffff', protected: true },\n { key: 'component.input.background', cssVar: '--spx-checkout-input-bg', group: 'component', type: 'color', default: '#292929' },\n { key: 'component.input.border', cssVar: '--spx-checkout-input-border', group: 'component', type: 'color', default: '#2c2c2c' },\n { key: 'component.input.focusRing', cssVar: '--spx-checkout-input-focus-ring', group: 'component', type: 'color', default: '' },\n // Default '' is filtered out by the preview-iframe normaliser, so the\n // CSS fallback chain on [data-spx-slot=\"summary.panel\"] resolves to\n // --spx-checkout-bg when no merchant override is set. A merchant who\n // only edits color.background therefore sees the aside follow that\n // change without an explicit summary override.\n { key: 'component.summary.background', cssVar: '--spx-checkout-summary-bg', group: 'component', type: 'color', default: '' },\n { key: 'component.paymentMethod.background', cssVar: '--spx-checkout-payment-method-bg', group: 'component', type: 'color', default: '' },\n { key: 'component.paymentMethod.cardBackground', cssVar: '--spx-checkout-payment-method-card-bg', group: 'component', type: 'color', default: '' },\n { key: 'component.paymentMethod.border', cssVar: '--spx-checkout-payment-method-border', group: 'component', type: 'color', default: '' },\n { key: 'component.paymentMethod.selectedBackground', cssVar: '--spx-checkout-payment-method-selected-bg', group: 'component', type: 'color', default: '' },\n { key: 'component.checkoutHeader.background', cssVar: '--spx-checkout-embed-header-bg', group: 'component', type: 'color', default: '' },\n { key: 'component.checkoutHeader.text', cssVar: '--spx-checkout-embed-header-text', group: 'component', type: 'color', default: '' },\n { key: 'component.productCard.background', cssVar: '--spx-checkout-product-card-bg', group: 'component', type: 'color', default: 'rgba(255,255,255,0.03)' },\n { key: 'component.productCard.border', cssVar: '--spx-checkout-product-card-border', group: 'component', type: 'color', default: 'rgba(255,255,255,0.06)' },\n { key: 'component.productCard.shadow', cssVar: '--spx-checkout-product-card-shadow', group: 'component', type: 'shadow', default: 'none' },\n { key: 'component.productImage.background', cssVar: '--spx-checkout-product-image-bg', group: 'component', type: 'color', default: 'rgba(255,255,255,0.06)' },\n { key: 'component.productImage.border', cssVar: '--spx-checkout-product-image-border', group: 'component', type: 'color', default: 'rgba(255,255,255,0.04)' },\n { key: 'component.productImage.icon', cssVar: '--spx-checkout-product-image-icon', group: 'component', type: 'color', default: 'rgba(250,250,250,0.4)' },\n { key: 'component.brandAvatar.background', cssVar: '--spx-checkout-brand-avatar-bg', group: 'component', type: 'color', default: 'rgba(255,255,255,0.06)' },\n { key: 'component.brandAvatar.text', cssVar: '--spx-checkout-brand-avatar-text', group: 'component', type: 'color', default: '#ffffff' },\n { key: 'component.brandAvatar.border', cssVar: '--spx-checkout-brand-avatar-border', group: 'component', type: 'color', default: 'rgba(255,255,255,0.1)' },\n { key: 'component.pill.background', cssVar: '--spx-checkout-pill-bg', group: 'component', type: 'color', default: 'rgba(255,255,255,0.04)' },\n { key: 'component.pill.border', cssVar: '--spx-checkout-pill-border', group: 'component', type: 'color', default: 'rgba(255,255,255,0.08)' },\n { key: 'component.pill.text', cssVar: '--spx-checkout-pill-text', group: 'component', type: 'color', default: '#a1a1a1' },\n { key: 'component.errorBanner.background', cssVar: '--spx-checkout-error-bg', group: 'component', type: 'color', default: 'rgba(239,68,68,0.1)' },\n { key: 'component.errorBanner.border', cssVar: '--spx-checkout-error-border', group: 'component', type: 'color', default: 'rgba(239,68,68,0.2)' },\n { key: 'component.errorBanner.text', cssVar: '--spx-checkout-error-text', group: 'component', type: 'color', default: '#ef4444' },\n { key: 'component.warningBanner.background', cssVar: '--spx-checkout-warning-bg', group: 'component', type: 'color', default: '' },\n { key: 'component.warningBanner.border', cssVar: '--spx-checkout-warning-border', group: 'component', type: 'color', default: '' },\n { key: 'component.warningBanner.text', cssVar: '--spx-checkout-warning-text', group: 'component', type: 'color', default: '' },\n { key: 'component.radio.idleRing', cssVar: '--spx-checkout-radio-idle-ring', group: 'component', type: 'color', default: 'rgba(161,161,161,0.5)' },\n { key: 'component.radio.checkedFill', cssVar: '--spx-checkout-radio-checked-fill', group: 'component', type: 'color', default: '' },\n { key: 'component.radio.checkedIcon', cssVar: '--spx-checkout-radio-checked-icon', group: 'component', type: 'color', default: '#ffffff' },\n { key: 'component.divider.color', cssVar: '--spx-checkout-divider', group: 'component', type: 'color', default: 'rgba(255,255,255,0.06)' },\n] as const satisfies readonly CheckoutStyleCssTokenDefinition[];\n\nexport const checkoutStyleAssetTokenDefinitions = [\n {\n key: 'brand.logoUrl',\n group: 'asset',\n type: 'asset_url',\n default: null,\n accept: ['image/png', 'image/jpeg', 'image/svg+xml', 'image/webp'],\n maxBytes: 512_000,\n },\n {\n key: 'brand.logoDarkUrl',\n group: 'asset',\n type: 'asset_url',\n default: null,\n accept: ['image/png', 'image/jpeg', 'image/svg+xml', 'image/webp'],\n maxBytes: 512_000,\n },\n {\n key: 'brand.logoMaxHeight',\n group: 'asset',\n type: 'number',\n default: 32,\n min: 16,\n max: 80,\n step: 2,\n unit: 'px',\n },\n {\n key: 'brand.faviconUrl',\n group: 'asset',\n type: 'asset_url',\n default: null,\n accept: ['image/png', 'image/x-icon', 'image/svg+xml'],\n maxBytes: 64_000,\n },\n {\n key: 'paymentLink.heroImageUrl',\n group: 'asset',\n type: 'asset_url',\n default: null,\n accept: ['image/png', 'image/jpeg', 'image/webp'],\n maxBytes: 1_048_576,\n surface: 'payment_link',\n },\n {\n key: 'paymentLink.heroPosition',\n group: 'asset',\n type: 'select',\n default: 'top',\n allowedValues: checkoutStylePaymentLinkHeroPositionValues,\n surface: 'payment_link',\n },\n] as const satisfies readonly CheckoutStyleAssetTokenDefinition[];\n\nexport const checkoutStyleControlTokenDefinitions = [\n ...checkoutStyleTokenDefinitions,\n ...checkoutStyleAssetTokenDefinitions,\n] as const satisfies readonly CheckoutStyleTokenDefinition[];\n\nexport type CheckoutStyleTokenKey = typeof checkoutStyleTokenDefinitions[number]['key'];\nexport type CheckoutStyleControlTokenKey = typeof checkoutStyleControlTokenDefinitions[number]['key'];\nexport type CheckoutStyleCssVariable = typeof checkoutStyleTokenDefinitions[number]['cssVar'];\n\nexport const embedStyleTokenDefinitions = [\n { key: 'embed.launcher.background', cssVar: '--spx-embed-launcher-background', group: 'embed', type: 'color', default: '#7c5cff' },\n { key: 'embed.launcher.text', cssVar: '--spx-embed-launcher-text', group: 'embed', type: 'color', default: '#ffffff', protected: true },\n { key: 'embed.launcher.radius', cssVar: '--spx-embed-launcher-radius', group: 'embed', type: 'number', default: 10, min: 0, max: 28, step: 1, unit: 'px' },\n { key: 'embed.launcher.paddingX', cssVar: '--spx-embed-launcher-padding-x', group: 'embed', type: 'number', default: 18, min: 8, max: 32, step: 1, unit: 'px' },\n { key: 'embed.launcher.paddingY', cssVar: '--spx-embed-launcher-padding-y', group: 'embed', type: 'number', default: 12, min: 6, max: 24, step: 1, unit: 'px' },\n { key: 'embed.launcher.shadow', cssVar: '--spx-embed-launcher-shadow', group: 'embed', type: 'shadow', default: '0 12px 32px rgba(0,0,0,0.18)' },\n { key: 'embed.productCard.background', cssVar: '--spx-embed-product-card-background', group: 'embed', type: 'color', default: '#ffffff' },\n { key: 'embed.productCard.border', cssVar: '--spx-embed-product-card-border', group: 'embed', type: 'color', default: 'rgba(24,24,27,0.12)' },\n { key: 'embed.productCard.imageRadius', cssVar: '--spx-embed-product-card-image-radius', group: 'embed', type: 'number', default: 8, min: 0, max: 24, step: 1, unit: 'px' },\n { key: 'embed.productCard.padding', cssVar: '--spx-embed-product-card-padding', group: 'embed', type: 'number', default: 16, min: 8, max: 32, step: 1, unit: 'px' },\n { key: 'embed.cart.background', cssVar: '--spx-embed-cart-background', group: 'embed', type: 'color', default: '#ffffff' },\n { key: 'embed.cart.rowBorder', cssVar: '--spx-embed-cart-row-border', group: 'embed', type: 'color', default: 'rgba(24,24,27,0.1)' },\n { key: 'embed.cart.itemSpacing', cssVar: '--spx-embed-cart-item-spacing', group: 'embed', type: 'number', default: 12, min: 4, max: 28, step: 1, unit: 'px' },\n { key: 'embed.modal.background', cssVar: '--spx-embed-modal-background', group: 'embed', type: 'color', default: '#ffffff' },\n { key: 'embed.modal.radius', cssVar: '--spx-embed-modal-radius', group: 'embed', type: 'number', default: 16, min: 0, max: 32, step: 1, unit: 'px' },\n { key: 'embed.modal.maxWidth', cssVar: '--spx-embed-modal-max-width', group: 'embed', type: 'number', default: 560, min: 360, max: 960, step: 20, unit: 'px' },\n { key: 'embed.modal.shadow', cssVar: '--spx-embed-modal-shadow', group: 'embed', type: 'shadow', default: '0 20px 60px rgba(0,0,0,0.2)' },\n { key: 'embed.backdrop.color', cssVar: '--spx-embed-backdrop-color', group: 'embed', type: 'color', default: 'rgba(0,0,0,0.6)' },\n { key: 'embed.backdrop.blur', cssVar: '--spx-embed-backdrop-blur', group: 'embed', type: 'number', default: 4, min: 0, max: 24, step: 1, unit: 'px' },\n { key: 'embed.backdrop.opacity', cssVar: '--spx-embed-backdrop-opacity', group: 'embed', type: 'number', default: 1, min: 0, max: 1, step: 0.05 },\n { key: 'embed.skeleton.background', cssVar: '--spx-embed-skeleton-background', group: 'embed', type: 'color', default: '#f4f4f5' },\n { key: 'embed.skeleton.shimmer', cssVar: '--spx-embed-skeleton-shimmer', group: 'embed', type: 'color', default: '#e8e8ec' },\n { key: 'embed.spinner.color', cssVar: '--spx-embed-spinner-color', group: 'embed', type: 'color', default: '#7c5cff' },\n {\n key: 'embed.closeButton.style',\n cssVar: '--spx-embed-close-button-style',\n group: 'embed',\n type: 'select',\n default: 'ghost',\n allowedValues: embedCloseButtonStyleValues,\n },\n {\n key: 'embed.mobile.layout',\n cssVar: '--spx-embed-mobile-layout',\n group: 'embed',\n type: 'select',\n default: 'sheet',\n allowedValues: embedMobileLayoutValues,\n },\n {\n key: 'embed.content.productDescription',\n cssVar: '--spx-embed-product-description-visibility',\n group: 'embed',\n type: 'select',\n default: 'visible',\n allowedValues: embedContentVisibilityValues,\n },\n {\n key: 'embed.content.termsShortcut',\n cssVar: '--spx-embed-terms-shortcut-visibility',\n group: 'embed',\n type: 'select',\n default: 'visible',\n allowedValues: embedContentVisibilityValues,\n },\n] as const satisfies readonly CheckoutStyleCssTokenDefinition[];\n\nexport type EmbedStyleTokenKey = typeof embedStyleTokenDefinitions[number]['key'];\nexport type EmbedStyleCssVariable = typeof embedStyleTokenDefinitions[number]['cssVar'];\n\nexport type EmbedStyleCssVariableOptions = {\n mode?: CheckoutStyleMode;\n};\n\nexport const checkoutStyleSlotValues = [\n 'checkout.shell',\n 'checkout.panel',\n 'checkout.header',\n 'brand.logo',\n 'product.card',\n 'product.image',\n 'product.title',\n 'product.description',\n 'product.price',\n 'product.quantity',\n 'product.addon',\n 'paymentLink.hero',\n 'summary.panel',\n 'summary.line',\n 'summary.total',\n 'form.field',\n 'form.label',\n 'form.help',\n 'coupon.input',\n 'input.base',\n 'input.error',\n 'button.primary',\n 'button.secondary',\n 'payment.methods',\n 'payment.method',\n 'payment.method.icon',\n 'payment.method.label',\n 'payment.method.meta',\n 'payment.method.fee',\n 'payment.method.indicator',\n 'payment.provider_widget',\n 'payment.loading',\n 'payment.error',\n 'payment.warning',\n 'legal.terms',\n 'status.success',\n 'status.processing',\n 'embed.launcher',\n 'embed.launcher.icon',\n 'embed.productCard',\n 'embed.productCard.image',\n 'embed.productCard.title',\n 'embed.productCard.price',\n 'embed.cart',\n 'embed.cart.row',\n 'embed.cart.summary',\n 'embed.modal',\n 'embed.modal.header',\n 'embed.modal.close',\n 'embed.skeleton',\n 'embed.loader',\n 'embed.branding',\n] as const;\n\nexport const checkoutStyleProtectedSlotValues = [\n 'product.title',\n 'product.price',\n 'summary.total',\n 'payment.method.label',\n 'payment.provider_widget',\n 'payment.loading',\n 'payment.error',\n 'payment.warning',\n 'legal.terms',\n 'status.success',\n 'status.processing',\n 'embed.modal.close',\n 'embed.branding',\n] as const;\n\nexport const CheckoutStyleSlotSchema = z.enum(checkoutStyleSlotValues);\nexport const CheckoutStyleProtectedSlotSchema = z.enum(checkoutStyleProtectedSlotValues);\n\nexport type CheckoutStyleSlot = z.infer<typeof CheckoutStyleSlotSchema>;\nexport type CheckoutStyleProtectedSlot = z.infer<typeof CheckoutStyleProtectedSlotSchema>;\n\nconst HexColorSchema = z.string().regex(/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/, 'Use a valid hex color');\n// Permissive color schema for composite values (rgba, gradients, color-mix)\n// used by token slots that aren't simple solid color picks. The CSS pipeline\n// is the consumer; we just guard against unbounded length and obviously\n// suspicious payloads (no semicolons, no curly braces, no @-rules).\nconst ExtendedColorSchema = z.string().trim().min(1).max(200).refine(\n (value) => !/[;{}]|@import|expression\\s*\\(/i.test(value),\n 'Use a valid CSS color or gradient',\n);\nconst ShadowSchema = z.string().trim().min(1).max(400).refine(\n (value) => !/[;{}]|@import|expression\\s*\\(/i.test(value),\n 'Use a valid CSS box-shadow value',\n);\n// Curated font list — the families the Style Center dropdown offers. Every\n// value here is served without a third-party request: the nine web families are\n// bundled by `next/font/google` in `apps/checkout/app/layout.tsx`, and \"Arial\" /\n// \"System UI\" come from the OS. A payment page must not hand the buyer's IP to\n// fonts.googleapis.com, so a family added here MUST also be added to\n// `app/layout.tsx` and to both maps in `apps/checkout/lib/checkout-style.tsx`\n// (LOCALLY_LOADED_FONTS + LOCAL_FONT_FAMILY_TOKENS); the checkout font-stack\n// test fails otherwise. Order matters: it drives both the dropdown in the\n// editor and the type-checked union here.\nexport const curatedFontValues = [\n 'Inter',\n 'Geist',\n 'Manrope',\n 'Plus Jakarta Sans',\n 'DM Sans',\n 'Space Grotesk',\n 'Sora',\n 'IBM Plex Sans',\n 'JetBrains Mono',\n 'Arial',\n 'System UI',\n] as const;\nconst CuratedFontSchema = z.enum(curatedFontValues);\n\n// Google Fonts family schema — accepts a single Google-hosted family name\n// like \"Source Serif 4\" or \"Crimson Pro\". Restricted to the character set\n// Google Fonts permits in family names (alphanumerics, spaces, +, -, _,\n// digits) and capped at 60 chars to avoid abuse via giant CSS imports.\nconst GoogleFontFamilySchema = z\n .string()\n .trim()\n .min(1)\n .max(60)\n .regex(/^[A-Za-z0-9 +\\-_]+$/, 'Use a Google Fonts family name');\nconst AssetUrlSchema = z.string().url();\n\nexport function isCheckoutStyleManagedAssetUrl(value: string): boolean {\n try {\n const url = new URL(value);\n return url.protocol === 'https:' && checkoutStyleManagedAssetHostValues.includes(\n url.hostname as typeof checkoutStyleManagedAssetHostValues[number],\n );\n } catch {\n return false;\n }\n}\n\nexport const CheckoutStyleTokensSchema = z.object({\n brand: z.object({\n logoUrl: AssetUrlSchema.optional().nullable(),\n logoDarkUrl: AssetUrlSchema.optional().nullable(),\n logoMaxHeight: z.number().int().min(16).max(80).optional(),\n faviconUrl: AssetUrlSchema.optional().nullable(),\n }).strict().optional(),\n color: z.object({\n brand: HexColorSchema.optional(),\n brandContrast: HexColorSchema.optional(),\n background: HexColorSchema.optional(),\n surface: HexColorSchema.optional(),\n surfaceRaised: HexColorSchema.optional(),\n text: HexColorSchema.optional(),\n textMuted: HexColorSchema.optional(),\n border: HexColorSchema.optional(),\n focus: HexColorSchema.optional(),\n success: HexColorSchema.optional(),\n warning: HexColorSchema.optional(),\n error: HexColorSchema.optional(),\n }).strict().optional(),\n typography: z.object({\n fontFamily: CuratedFontSchema.optional(),\n // Optional Google Fonts override. When set, the storefront injects the\n // fonts.googleapis.com stylesheet and uses this family in addition to\n // (or instead of) the curated fontFamily as the leftmost name in the\n // CSS font stack.\n googleFontFamily: GoogleFontFamilySchema.optional(),\n baseSize: z.number().int().min(12).max(18).optional(),\n }).strict().optional(),\n shape: z.object({\n buttonRadius: z.number().int().min(0).max(24).optional(),\n inputRadius: z.number().int().min(0).max(24).optional(),\n cardRadius: z.number().int().min(0).max(28).optional(),\n }).strict().optional(),\n spacing: z.object({\n density: CheckoutStyleDensitySchema.optional(),\n controlHeight: z.number().int().min(36).max(56).optional(),\n }).strict().optional(),\n component: z.object({\n primaryButton: z.object({\n background: HexColorSchema.optional(),\n text: HexColorSchema.optional(),\n }).strict().optional(),\n input: z.object({\n background: HexColorSchema.optional(),\n border: HexColorSchema.optional(),\n focusRing: ExtendedColorSchema.optional(),\n }).strict().optional(),\n summary: z.object({\n background: HexColorSchema.optional(),\n }).strict().optional(),\n paymentMethod: z.object({\n background: ExtendedColorSchema.optional(),\n cardBackground: ExtendedColorSchema.optional(),\n border: ExtendedColorSchema.optional(),\n selectedBackground: ExtendedColorSchema.optional(),\n }).strict().optional(),\n productCard: z.object({\n background: ExtendedColorSchema.optional(),\n border: ExtendedColorSchema.optional(),\n shadow: ShadowSchema.optional(),\n }).strict().optional(),\n productImage: z.object({\n background: ExtendedColorSchema.optional(),\n border: ExtendedColorSchema.optional(),\n icon: ExtendedColorSchema.optional(),\n }).strict().optional(),\n brandAvatar: z.object({\n background: ExtendedColorSchema.optional(),\n text: HexColorSchema.optional(),\n border: ExtendedColorSchema.optional(),\n }).strict().optional(),\n pill: z.object({\n background: ExtendedColorSchema.optional(),\n border: ExtendedColorSchema.optional(),\n text: HexColorSchema.optional(),\n }).strict().optional(),\n errorBanner: z.object({\n background: ExtendedColorSchema.optional(),\n border: ExtendedColorSchema.optional(),\n text: HexColorSchema.optional(),\n }).strict().optional(),\n warningBanner: z.object({\n background: ExtendedColorSchema.optional(),\n border: ExtendedColorSchema.optional(),\n text: HexColorSchema.optional(),\n }).strict().optional(),\n radio: z.object({\n idleRing: ExtendedColorSchema.optional(),\n checkedFill: HexColorSchema.optional(),\n checkedIcon: HexColorSchema.optional(),\n }).strict().optional(),\n divider: z.object({\n color: ExtendedColorSchema.optional(),\n }).strict().optional(),\n }).strict().optional(),\n paymentLink: z.object({\n heroImageUrl: AssetUrlSchema.optional().nullable(),\n heroPosition: CheckoutStylePaymentLinkHeroPositionSchema.optional(),\n }).strict().optional(),\n embed: z.object({\n launcher: z.object({\n background: ExtendedColorSchema.optional(),\n text: HexColorSchema.optional(),\n radius: z.number().int().min(0).max(28).optional(),\n paddingX: z.number().int().min(8).max(32).optional(),\n paddingY: z.number().int().min(6).max(24).optional(),\n shadow: ShadowSchema.optional(),\n }).strict().optional(),\n productCard: z.object({\n background: ExtendedColorSchema.optional(),\n border: ExtendedColorSchema.optional(),\n imageRadius: z.number().int().min(0).max(24).optional(),\n padding: z.number().int().min(8).max(32).optional(),\n }).strict().optional(),\n cart: z.object({\n background: ExtendedColorSchema.optional(),\n rowBorder: ExtendedColorSchema.optional(),\n itemSpacing: z.number().int().min(4).max(28).optional(),\n }).strict().optional(),\n modal: z.object({\n background: ExtendedColorSchema.optional(),\n radius: z.number().int().min(0).max(32).optional(),\n maxWidth: z.number().int().min(360).max(960).optional(),\n shadow: ShadowSchema.optional(),\n }).strict().optional(),\n backdrop: z.object({\n color: ExtendedColorSchema.optional(),\n blur: z.number().int().min(0).max(24).optional(),\n opacity: z.number().min(0).max(1).optional(),\n }).strict().optional(),\n skeleton: z.object({\n background: ExtendedColorSchema.optional(),\n shimmer: ExtendedColorSchema.optional(),\n }).strict().optional(),\n spinner: z.object({\n color: ExtendedColorSchema.optional(),\n }).strict().optional(),\n closeButton: z.object({\n style: EmbedCloseButtonStyleSchema.optional(),\n }).strict().optional(),\n mobile: z.object({\n layout: EmbedMobileLayoutSchema.optional(),\n }).strict().optional(),\n content: z.object({\n productDescription: EmbedContentVisibilitySchema.optional(),\n termsShortcut: EmbedContentVisibilitySchema.optional(),\n }).strict().optional(),\n }).strict().optional(),\n}).strict();\n\nexport type CheckoutStyleTokens = z.infer<typeof CheckoutStyleTokensSchema>;\n\nexport const CheckoutStyleSettingsSchema = z.object({\n mode: CheckoutStyleModeSchema.default('system'),\n fontSource: z.enum(['curated']).default('curated'),\n}).strict();\n\nexport type CheckoutStyleSettings = z.infer<typeof CheckoutStyleSettingsSchema>;\n\nexport const StyleThemeShareModeSchema = z.enum(['standalone', 'bundle', 'pointer']);\nexport type StyleThemeShareMode = z.infer<typeof StyleThemeShareModeSchema>;\n\nexport const StyleThemeParentHintSchema = z.object({\n name: z.string().trim().min(1).max(80),\n fingerprint: z.string().trim().min(1).max(128),\n}).strict();\n\n/**\n * Historic-data tolerance. Theme export codes are copy-pasted strings that live\n * outside this system — in merchant notes, Discord messages, and the\n * `style_theme_shares` table — so codes minted before the embed surface\n * collapsed to a single design still carry a top-level `embed_design` key (and\n * one inside `bundled_parent`). The export schemas are `.strict()`, so without\n * this strip every one of those codes would fail to import.\n *\n * Accept and ignore: the key is dropped before validation and never re-emitted.\n * Remove this once codes minted before the single-design release are no longer\n * expected to import (they carry no other retired field, so the strip can go\n * away wholesale).\n *\n * OBSERVABILITY LIVES ELSEWHERE, ON PURPOSE. This module is isomorphic — the\n * dashboard's import dialog parses the same code in the browser before the\n * backend ever sees it — so there is no logger to reach for here, and adding\n * one would put a server sink in a bundle that ships to merchants. The signal\n * that says whether the retirement has completed is the backend's\n * `retired_embed_design_key` warn line in\n * `apps/backend/src/services/style-center/embed-runtime.ts`, which watches the\n * same key on the transports and Redis sessions minted by the same release.\n * Those age out no earlier than a copy-pasted export code does, so a quiet\n * runtime is the precondition for dropping THIS strip too — never the proof on\n * its own. The removal plan for all three is one list:\n * `docs/architecture/domains/style-center.md` — Release 2.\n */\nconst RETIRED_EXPORT_FIELDS = ['embed_design'] as const;\n\nfunction stripRetiredExportFields(value: unknown): unknown {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n return value;\n }\n\n const record = value as Record<string, unknown>;\n if (!RETIRED_EXPORT_FIELDS.some((field) => field in record)) {\n return value;\n }\n\n const cleaned = { ...record };\n for (const field of RETIRED_EXPORT_FIELDS) {\n delete cleaned[field];\n }\n return cleaned;\n}\n\nexport const CheckoutStyleBundledParentThemeExportSchema = z.preprocess(\n stripRetiredExportFields,\n z.object({\n type: z.literal('shoppex.style_theme'),\n surface: z.literal('checkout'),\n format_version: z.union([\n z.literal(1),\n z.literal(SHOPPEX_STYLE_THEME_EXPORT_FORMAT_VERSION),\n ]),\n name: z.string().trim().min(1).max(80),\n description: z.string().trim().max(240).optional(),\n token_schema_version: z.literal(CHECKOUT_STYLE_TOKEN_SCHEMA_VERSION),\n tokens: CheckoutStyleTokensSchema.default({}),\n custom_css: z.string().max(20_000).default(''),\n settings: CheckoutStyleSettingsSchema.default({ mode: 'system', fontSource: 'curated' }),\n _meta: z.record(z.string(), z.unknown()).optional(),\n }).strict(),\n);\n\nexport const CheckoutStyleThemeExportSchema = z.preprocess(\n stripRetiredExportFields,\n z.object({\n type: z.literal('shoppex.style_theme'),\n surface: CheckoutStyleSurfaceSchema,\n format_version: z.union([\n z.literal(1),\n z.literal(SHOPPEX_STYLE_THEME_EXPORT_FORMAT_VERSION),\n ]),\n name: z.string().trim().min(1).max(80),\n description: z.string().trim().max(240).optional(),\n token_schema_version: z.literal(CHECKOUT_STYLE_TOKEN_SCHEMA_VERSION),\n tokens: CheckoutStyleTokensSchema.default({}),\n custom_css: z.string().max(20_000).default(''),\n settings: CheckoutStyleSettingsSchema.default({ mode: 'system', fontSource: 'curated' }),\n share_mode: StyleThemeShareModeSchema.default('standalone'),\n parent_hint: StyleThemeParentHintSchema.optional(),\n bundled_parent: CheckoutStyleBundledParentThemeExportSchema.optional(),\n _meta: z.record(z.string(), z.unknown()).optional(),\n }).strict(),\n);\n\nexport type CheckoutStyleThemeExport = z.infer<typeof CheckoutStyleThemeExportSchema>;\n\nexport const ResolvedCheckoutStyleSchema = z.object({\n theme_id: z.string().uuid().nullable(),\n surface: CheckoutStyleSurfaceSchema,\n token_schema_version: z.literal(CHECKOUT_STYLE_TOKEN_SCHEMA_VERSION),\n revision: z.number().int().min(1),\n tokens: CheckoutStyleTokensSchema,\n custom_css: z.string(),\n css_variables: z.record(z.string(), z.string()),\n}).strict();\n\nexport type ResolvedCheckoutStyle = z.infer<typeof ResolvedCheckoutStyleSchema>;\n\nexport const ResolvedEmbedStyleSchema = z.object({\n theme_id: z.string().uuid().nullable(),\n parent_theme_id: z.string().uuid().nullable(),\n surface: z.literal('embed'),\n token_schema_version: z.literal(CHECKOUT_STYLE_TOKEN_SCHEMA_VERSION),\n revision: z.number().int().min(1),\n parent_revision: z.number().int().min(1).nullable(),\n tokens: CheckoutStyleTokensSchema,\n custom_css: z.string(),\n css_variables: z.record(z.string(), z.string()),\n}).strict();\n\nexport type ResolvedEmbedStyle = z.infer<typeof ResolvedEmbedStyleSchema>;\n\n/** Canonical embed runtime contract shared by SDK shell and checkout iframe. */\nexport const EmbedRuntimeStyleSchema = ResolvedEmbedStyleSchema;\nexport type EmbedRuntimeStyle = ResolvedEmbedStyle;\n\nexport const EmbedRuntimeSessionContextSchema = z.object({\n shop_id: z.string().uuid(),\n product_id: z.string().uuid().nullable(),\n product_group_id: z.string().uuid().nullable(),\n payment_link_id: z.string().uuid().nullable(),\n invoice_id: z.string().nullable(),\n}).strict();\n\nexport type EmbedRuntimeSessionContext = z.infer<typeof EmbedRuntimeSessionContextSchema>;\n\nexport const EmbedRuntimeThemeResponseSchema = z.object({\n embed_runtime: z.string().min(16).max(128),\n revision: z.number().int().min(1),\n parent_revision: z.number().int().min(1).nullable(),\n theme_id: z.string().uuid().nullable(),\n css_variables: z.record(z.string(), z.string()),\n custom_css: z.string(),\n}).strict();\n\nexport type EmbedRuntimeThemeResponse = z.infer<typeof EmbedRuntimeThemeResponseSchema>;\n\nexport const EmbedRuntimeTransportSchema = z.object({\n embed_style_revision: z.coerce.number().int().min(1).optional(),\n embed_runtime: z.string().min(16).max(128).optional(),\n preview: z.boolean().optional(),\n}).strict();\n\nexport type EmbedRuntimeTransport = z.infer<typeof EmbedRuntimeTransportSchema>;\n\nfunction readPath(input: unknown, path: string): unknown {\n return path.split('.').reduce<unknown>((current, segment) => {\n if (!current || typeof current !== 'object' || Array.isArray(current)) return undefined;\n return (current as Record<string, unknown>)[segment];\n }, input);\n}\n\nfunction formatCssValue(definition: CheckoutStyleTokenDefinition, value: string | number): string {\n if (definition.type === 'number' && definition.unit) {\n return `${value}${definition.unit}`;\n }\n\n // Multi-word font family names must be quoted so they survive var()\n // substitution into a font-family list. Single-word names like \"Inter\"\n // or generic keywords are left bare so they keep their generic-family\n // semantics.\n if (definition.type === 'font' && typeof value === 'string') {\n const trimmed = value.trim();\n if (trimmed.length === 0) return '';\n if (/\\s/.test(trimmed) && !/^['\"]/.test(trimmed)) {\n return `\"${trimmed.replace(/\"/g, '\\\\\"')}\"`;\n }\n return trimmed;\n }\n\n return String(value);\n}\n\nexport function resolveCheckoutStyleTokenValue(\n tokens: CheckoutStyleTokens,\n key: CheckoutStyleTokenKey,\n options: { parentTokens?: CheckoutStyleTokens } = {},\n): string | number | undefined {\n const own = readPath(tokens, key);\n if (isExplicitCheckoutStyleTokenValue(own)) {\n return own as string | number;\n }\n\n const parent = options.parentTokens ? readPath(options.parentTokens, key) : undefined;\n if (isExplicitCheckoutStyleTokenValue(parent)) {\n return parent as string | number;\n }\n\n const brandDerivedKey = resolveCheckoutStyleBrandDerivedTokenKey(key);\n if (brandDerivedKey) {\n const brand = resolveCheckoutStyleTokenValue(tokens, brandDerivedKey as CheckoutStyleTokenKey, options);\n if (isExplicitCheckoutStyleTokenValue(brand)) {\n return brand;\n }\n }\n\n const definition = checkoutStyleTokenDefinitions.find((entry) => entry.key === key);\n if (definition && isExplicitCheckoutStyleTokenValue(definition.default)) {\n return definition.default;\n }\n\n const baseline = CHECKOUT_PLATFORM_BASELINE[key];\n return baseline !== undefined ? baseline : undefined;\n}\n\nexport function createCheckoutStyleCssVariables(tokens: CheckoutStyleTokens): Record<CheckoutStyleCssVariable, string> {\n const variables = {} as Record<CheckoutStyleCssVariable, string>;\n\n for (const definition of checkoutStyleTokenDefinitions) {\n const value = readPath(tokens, definition.key);\n if (!isExplicitCheckoutStyleTokenValue(value)) {\n continue;\n }\n variables[definition.cssVar] = formatCssValue(definition, value);\n }\n\n return variables;\n}\n\n/**\n * Token groups whose defaults are safe to materialise into the live checkout\n * root. These are the \"foundation\" tokens (brand, base colors, shape, spacing)\n * that sit at the INNER end of the system-CSS `var()` fallback chains —\n * e.g. `var(--spx-checkout-product-card-border, var(--spx-checkout-border, …))`.\n * Materialising them kills the white-`currentColor` fallback bug without\n * touching the cascade.\n *\n * The `component` group is deliberately excluded: those tokens are the OUTER\n * end of the chains, so emitting their defaults (e.g. `--spx-checkout-product-card-bg`)\n * would shadow base-token edits — a merchant who only customises `color.surfaceRaised`\n * would no longer see it cascade into product cards. Their defaults stay inline\n * in the system CSS as the final hex fallback instead.\n *\n * The `typography` group is also excluded: `typography.fontFamily` resolves to a\n * bare family name (\"Geist\") that no `@font-face` declares — the checkout loads\n * Geist via `next/font` as `--font-geist-sans`. Materialising `--spx-checkout-font`\n * as \"Geist\" would make the font-family rule bypass the Next webfont and fall\n * back to system sans. The system CSS keeps CHECKOUT_PLATFORM_FONT_STACK (which\n * references `--font-geist-sans`) as its inline default instead.\n */\nconst CHECKOUT_BASELINE_TOKEN_GROUPS = new Set(['brand', 'color', 'shape', 'spacing']);\n\n/**\n * Like {@link createCheckoutStyleCssVariables}, but materialises each foundation\n * token's SSOT default when the merchant hasn't set an explicit value. The live\n * hosted checkout renders this so the base `--spx-checkout-*` variables are\n * always present in the DOM, which means the system CSS never falls back to\n * `currentColor` (that fallback resolved to the white text colour → white\n * borders/buttons for any merchant who never opened the Style Center).\n *\n * Rules:\n * - Explicit merchant values are always emitted (any group, including component\n * overrides), so partial Style Center themes keep working.\n * - Unset tokens only get their default emitted when they belong to a foundation\n * group (see {@link CHECKOUT_BASELINE_TOKEN_GROUPS}); component defaults are\n * left to the inline system-CSS fallbacks so base-token edits cascade.\n * - Empty defaults (`''`) are skipped so the value stays unset — most importantly\n * `color.background` (`--spx-checkout-bg`), which must remain absent so the\n * two hosted columns keep their own rungs of the ladder (`--surface-0` for the\n * working panel, `--surface-1` for the summary ground). A materialised\n * background paints BOTH and the column split disappears. This resolves only\n * to `definition.default`, NOT through `resolveCheckoutStyleTokenValue`,\n * because that resolver would fall through to the opaque\n * `CHECKOUT_PLATFORM_BASELINE` background.\n */\n/**\n * Light-appearance defaults for the baseline foundation tokens. Keys not listed\n * here keep their (appearance-neutral) definition default. `color.background`\n * stays absent in both appearances so the column split and the summary column's\n * own ground survive.\n *\n * Same rule as the dark defaults above: every value is the LIGHT rung of the\n * ladder in `apps/checkout/app/globals.css` — `--surface-0`, `--card`,\n * `--foreground`, `--muted-foreground`, `--border` — so that a shop with no\n * theme renders exactly what the components paint.\n */\nexport const CHECKOUT_PLATFORM_BASELINE_LIGHT_DEFAULTS: Partial<Record<string, string>> = {\n // `--surface-0`: the working panel, PURE WHITE. It is the form half of the\n // page, and a form's structure comes from the edge of each field and tile,\n // not from the tone of the sheet they sit on. Two tinted panels shipped here\n // before this one (#f7f7f7, then a #f0f0f0 \"well\") and both made the middle\n // of the page read as a tonal step rather than as a join.\n 'color.surface': '#ffffff',\n // `--surface-2`: a card resting on that panel — the SAME white, on purpose.\n // Light separates a card from its panel by `--card-hairline` (#e8e8e8) and a\n // whisper of `--card-shadow`, never by a step of fill. That these two are\n // equal is the model, not a missing value: the summary column (#fafafa) is\n // the only tonal step the light theme spends anywhere.\n 'color.surfaceRaised': '#ffffff',\n 'color.text': '#101010',\n 'color.textMuted': '#636363',\n // `--border`. It is the pair that matters, not either value: a shop on the\n // platform baseline has to get the same relation between a field edge and a\n // card edge that the checkout paints for everyone else. Both halves moved up\n // together to Stripe Checkout's measured pair (card edge #e8e8e8, input ring\n // #e0e0e0) when the working panel's white-on-white cards turned out to have\n // nothing but this line holding them off the sheet.\n 'color.border': '#e0e0e0',\n 'color.success': '#16a34a',\n 'color.warning': '#ca8a04',\n 'color.error': '#dc2626',\n};\n\nexport type CheckoutStyleAppearance = 'dark' | 'light';\n\nexport function createCheckoutStyleBaselineCssVariables(\n tokens: CheckoutStyleTokens,\n appearance: CheckoutStyleAppearance = 'dark',\n): Record<CheckoutStyleCssVariable, string> {\n const variables = {} as Record<CheckoutStyleCssVariable, string>;\n\n for (const definition of checkoutStyleTokenDefinitions) {\n const own = readPath(tokens, definition.key);\n if (isExplicitCheckoutStyleTokenValue(own)) {\n variables[definition.cssVar] = formatCssValue(definition, own);\n continue;\n }\n if (!CHECKOUT_BASELINE_TOKEN_GROUPS.has(definition.group)) {\n continue;\n }\n const baselineDefault = appearance === 'light'\n ? CHECKOUT_PLATFORM_BASELINE_LIGHT_DEFAULTS[definition.key] ?? definition.default\n : definition.default;\n if (!isExplicitCheckoutStyleTokenValue(baselineDefault)) {\n continue;\n }\n variables[definition.cssVar] = formatCssValue(definition, baselineDefault);\n }\n\n return variables;\n}\n\n/**\n * Dark-appearance defaults for the embed chrome tokens. The `definition.default`\n * of every embed token is the LIGHT value, so only the keys that actually differ\n * in dark are listed here. Emitted only when the theme's mode is explicitly\n * 'dark' — never inferred from anything else.\n */\nconst EMBED_STYLE_DARK_DEFAULTS: Partial<Record<EmbedStyleTokenKey, string>> = {\n 'embed.productCard.background': '#09090b',\n 'embed.productCard.border': 'rgba(255,255,255,0.08)',\n 'embed.cart.background': '#09090b',\n 'embed.cart.rowBorder': '#27272a',\n 'embed.modal.background': '#0a0a0c',\n 'embed.modal.shadow': '0 20px 60px rgba(0,0,0,0.45)',\n 'embed.skeleton.background': '#1a1a1e',\n 'embed.skeleton.shimmer': '#2a2a2f',\n};\n\n/**\n * Emits the `--spx-embed-*` variables for a resolved embed style.\n *\n * Rules:\n * - An explicit merchant token always wins and is always emitted.\n * - An unset token gets a baked default ONLY when the theme picked an\n * appearance explicitly (`settings.mode` of 'dark' or 'light').\n * - Mode 'system' (and an unset mode) bakes nothing. The embed SDK stylesheet\n * reads every one of these through `var(--spx-embed-*, <fallback>)` and pairs\n * that with its own `prefers-color-scheme` handling (see\n * `shouldUseDarkShell` in apps/checkout/src/embed/modal.ts, which reads\n * `--spx-checkout-color-mode` first and falls back to the media query).\n * Baking an appearance here would pin a merchant who asked for \"follow the\n * visitor's system setting\" to one of the two.\n */\nexport function createEmbedStyleCssVariables(\n tokens: CheckoutStyleTokens,\n options: EmbedStyleCssVariableOptions = {},\n): Record<EmbedStyleCssVariable, string> {\n const variables = {} as Record<EmbedStyleCssVariable, string>;\n const bakeDefaults = options.mode === 'dark' || options.mode === 'light';\n\n for (const definition of embedStyleTokenDefinitions) {\n const value = readPath(tokens, definition.key);\n\n if (typeof value === 'string' || typeof value === 'number') {\n if (typeof value === 'string' && value.length === 0) {\n continue;\n }\n variables[definition.cssVar] = formatCssValue(definition, value);\n continue;\n }\n\n if (!bakeDefaults) {\n continue;\n }\n\n const resolvedDefault = options.mode === 'dark'\n ? EMBED_STYLE_DARK_DEFAULTS[definition.key] ?? definition.default\n : definition.default;\n if (typeof resolvedDefault === 'string' && resolvedDefault.length === 0) {\n continue;\n }\n variables[definition.cssVar] = formatCssValue(definition, resolvedDefault);\n }\n\n return variables;\n}\n","import * as z from 'zod/v4';\n\nexport const storefrontAddonTypeValues = [\n 'announcement_bar',\n 'countdown_bar',\n 'promo_info_card',\n 'recent_purchase_popup',\n 'coupon_popup_modal',\n 'live_chat',\n] as const;\n\nexport const storefrontAddonSlotValues = [\n 'layout.header.before',\n 'layout.header.after',\n 'layout.overlay',\n 'home.hero.after',\n 'home.grid.before',\n 'product.buybox.after',\n 'layout.footer.before',\n 'floating.bottom_right',\n] as const;\n\nexport const storefrontAddonComponentValues = [\n 'announcement_bar',\n 'countdown_bar',\n 'promo_info_card',\n 'recent_purchase_popup',\n 'coupon_popup_modal',\n 'live_chat',\n] as const;\n\nexport const StorefrontAddonTypeSchema = z.enum(storefrontAddonTypeValues);\nexport const StorefrontAddonSlotSchema = z.enum(storefrontAddonSlotValues);\nexport const StorefrontAddonComponentSchema = z.enum(storefrontAddonComponentValues);\n\nexport type StorefrontAddonType = z.infer<typeof StorefrontAddonTypeSchema>;\nexport type StorefrontAddonSlot = z.infer<typeof StorefrontAddonSlotSchema>;\nexport type StorefrontAddonComponent = z.infer<typeof StorefrontAddonComponentSchema>;\n\nconst HexColorSchema = z.string().regex(/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/, 'Use a valid hex color');\n\nexport const announcementBarDisplayModeValues = [\n 'static',\n 'marquee',\n] as const;\n\nexport const announcementBarThemePresetValues = [\n 'brand_blue',\n 'emerald',\n 'sunset',\n 'rose',\n 'charcoal',\n 'custom',\n] as const;\n\nexport const DEFAULT_ANNOUNCEMENT_BAR_ANIMATION_SPEED_SECONDS = 30;\n\nexport const AnnouncementBarDisplayModeSchema = z.enum(announcementBarDisplayModeValues);\nexport const AnnouncementBarThemePresetSchema = z.enum(announcementBarThemePresetValues);\n\nexport const countdownBarExpiryBehaviorValues = [\n 'hide',\n 'message',\n] as const;\n\nexport const countdownBarDensityValues = [\n 'compact',\n 'comfortable',\n] as const;\n\nexport const countdownBarCtaStyleValues = [\n 'subtle',\n 'outline',\n 'solid',\n] as const;\n\nexport const countdownBarTimerStyleValues = [\n 'minimal',\n 'boxed',\n] as const;\n\nexport const promoInfoCardThemePresetValues = [\n 'indigo',\n 'emerald',\n 'amber',\n 'rose',\n 'slate',\n 'custom',\n] as const;\n\nexport const promoInfoCardLayoutStyleValues = [\n 'compact',\n 'feature',\n 'alert',\n] as const;\n\nexport const promoInfoCardDensityValues = [\n 'compact',\n 'comfortable',\n] as const;\n\nexport const promoInfoCardCtaStyleValues = [\n 'subtle',\n 'outline',\n 'solid',\n] as const;\n\nexport const promoInfoCardIconVisibilityValues = [\n 'show',\n 'hide',\n] as const;\n\nexport const promoInfoCardIconValues = [\n 'sparkles',\n 'megaphone',\n 'gift',\n 'truck',\n 'shield',\n 'support',\n 'none',\n] as const;\n\nexport const CountdownBarExpiryBehaviorSchema = z.enum(countdownBarExpiryBehaviorValues);\nexport const CountdownBarDensitySchema = z.enum(countdownBarDensityValues);\nexport const CountdownBarCtaStyleSchema = z.enum(countdownBarCtaStyleValues);\nexport const CountdownBarTimerStyleSchema = z.enum(countdownBarTimerStyleValues);\nexport const PromoInfoCardThemePresetSchema = z.enum(promoInfoCardThemePresetValues);\nexport const PromoInfoCardLayoutStyleSchema = z.enum(promoInfoCardLayoutStyleValues);\nexport const PromoInfoCardDensitySchema = z.enum(promoInfoCardDensityValues);\nexport const PromoInfoCardCtaStyleSchema = z.enum(promoInfoCardCtaStyleValues);\nexport const PromoInfoCardIconSchema = z.enum(promoInfoCardIconValues);\nexport const PromoInfoCardIconVisibilitySchema = z.enum(promoInfoCardIconVisibilityValues);\n\nexport const couponPopupModalThemePresetValues = [\n 'midnight',\n 'ocean',\n 'ember',\n 'forest',\n 'custom',\n] as const;\n\nexport const couponPopupModalTriggerValues = [\n 'delay',\n 'exit_intent',\n] as const;\n\nexport const CouponPopupModalThemePresetSchema = z.enum(couponPopupModalThemePresetValues);\nexport const CouponPopupModalTriggerSchema = z.enum(couponPopupModalTriggerValues);\n\nconst RelativeOrAbsoluteUrlSchema = z.string().trim().refine((value) => {\n if (value.startsWith('/')) {\n return true;\n }\n\n try {\n const parsed = new URL(value);\n return parsed.protocol === 'http:' || parsed.protocol === 'https:';\n } catch {\n return false;\n }\n}, 'Use a valid absolute URL or a path starting with \"/\"');\n\nconst DatetimeStringSchema = z.string().trim().refine((value) => {\n const parsed = new Date(value);\n return !Number.isNaN(parsed.getTime());\n}, 'Use a valid date and time');\n\nexport const AnnouncementBarConfigSchema = z.object({\n text: z.string().trim().min(1, 'Text is required').max(160, 'Text must be 160 characters or fewer'),\n linkLabel: z.string().trim().max(32, 'Link label must be 32 characters or fewer').optional().nullable(),\n linkUrl: RelativeOrAbsoluteUrlSchema.optional().nullable(),\n dismissible: z.boolean().default(false),\n displayMode: AnnouncementBarDisplayModeSchema.default('marquee'),\n themePreset: AnnouncementBarThemePresetSchema.default('custom'),\n animationSpeedSeconds: z.number().int().min(8).max(40).default(DEFAULT_ANNOUNCEMENT_BAR_ANIMATION_SPEED_SECONDS),\n backgroundColor: HexColorSchema.default('#111827'),\n textColor: HexColorSchema.default('#f9fafb'),\n});\n\nexport const CountdownBarConfigSchema = z.object({\n text: z.string().trim().min(1, 'Text is required').max(120, 'Text must be 120 characters or fewer'),\n endAt: DatetimeStringSchema,\n linkLabel: z.string().trim().max(32, 'Link label must be 32 characters or fewer').optional().nullable(),\n linkUrl: RelativeOrAbsoluteUrlSchema.optional().nullable(),\n dismissible: z.boolean().default(false),\n themePreset: AnnouncementBarThemePresetSchema.default('brand_blue'),\n expiredBehavior: CountdownBarExpiryBehaviorSchema.default('hide'),\n expiredMessage: z.string().trim().max(120, 'Expired message must be 120 characters or fewer').optional().nullable(),\n density: CountdownBarDensitySchema.default('compact'),\n ctaStyle: CountdownBarCtaStyleSchema.default('subtle'),\n timerStyle: CountdownBarTimerStyleSchema.default('boxed'),\n backgroundColor: HexColorSchema.default('#111827'),\n textColor: HexColorSchema.default('#f9fafb'),\n});\n\nexport const PromoInfoCardConfigSchema = z.object({\n eyebrow: z.string().trim().max(32, 'Eyebrow must be 32 characters or fewer').optional().nullable(),\n title: z.string().trim().min(1, 'Title is required').max(80, 'Title must be 80 characters or fewer'),\n body: z.string().trim().min(1, 'Body is required').max(240, 'Body must be 240 characters or fewer'),\n linkLabel: z.string().trim().max(32, 'Link label must be 32 characters or fewer').optional().nullable(),\n linkUrl: RelativeOrAbsoluteUrlSchema.optional().nullable(),\n themePreset: PromoInfoCardThemePresetSchema.default('indigo'),\n layoutStyle: PromoInfoCardLayoutStyleSchema.default('feature'),\n density: PromoInfoCardDensitySchema.default('comfortable'),\n ctaStyle: PromoInfoCardCtaStyleSchema.default('outline'),\n icon: PromoInfoCardIconSchema.default('sparkles'),\n iconVisibility: PromoInfoCardIconVisibilitySchema.default('show'),\n backgroundColor: HexColorSchema.default('#111827'),\n textColor: HexColorSchema.default('#f9fafb'),\n accentColor: HexColorSchema.default('#818cf8'),\n});\n\nexport const RecentPurchasePopupConfigSchema = z.object({\n title: z.string().trim().min(1, 'Title is required').max(80, 'Title must be 80 characters or fewer').default('Recent purchases'),\n lookbackHours: z.number().int().min(1).max(168).default(24),\n cooldownSeconds: z.number().int().min(5).max(300).default(20),\n maxItems: z.number().int().min(1).max(20).default(8),\n anonymizeMode: z.enum([\n 'first_name_city',\n 'first_name_country',\n 'initial_country',\n 'anonymous',\n ]).default('first_name_city'),\n includedProductIds: z.array(z.string().min(1)).max(50).default([]),\n});\n\nexport const CouponPopupModalConfigSchema = z.object({\n eyebrow: z.string().trim().max(32, 'Eyebrow must be 32 characters or fewer').optional().nullable(),\n title: z.string().trim().min(1, 'Title is required').max(80, 'Title must be 80 characters or fewer'),\n body: z.string().trim().min(1, 'Body is required').max(240, 'Body must be 240 characters or fewer'),\n couponCode: z.string().trim().min(2, 'Coupon code is required').max(40, 'Coupon code must be 40 characters or fewer'),\n primaryButtonLabel: z.string().trim().min(1, 'Primary button label is required').max(24, 'Primary button label must be 24 characters or fewer').default('Copy code'),\n secondaryButtonLabel: z.string().trim().min(1, 'Secondary button label is required').max(24, 'Secondary button label must be 24 characters or fewer').default('Maybe later'),\n disclaimer: z.string().trim().max(100, 'Disclaimer must be 100 characters or fewer').optional().nullable(),\n themePreset: CouponPopupModalThemePresetSchema.default('midnight'),\n trigger: CouponPopupModalTriggerSchema.default('delay'),\n delaySeconds: z.number().int().min(0).max(60).default(6),\n showOncePerSession: z.boolean().default(true),\n reminderHours: z.number().int().min(1).max(720).default(24),\n backgroundColor: HexColorSchema.default('#111827'),\n textColor: HexColorSchema.default('#f8fafc'),\n accentColor: HexColorSchema.default('#7c9cff'),\n heroImageUrl: RelativeOrAbsoluteUrlSchema.optional().nullable(),\n discountDisplay: z.string().trim().max(24, 'Discount display must be 24 characters or fewer').optional().nullable(),\n expiresAt: DatetimeStringSchema.optional().nullable(),\n});\n\nexport const liveChatContactFieldsValues = [\n 'hidden',\n 'optional',\n] as const;\n\nexport const LiveChatContactFieldsSchema = z.enum(liveChatContactFieldsValues);\n\nexport const LiveChatConfigSchema = z.object({\n headline: z.string().trim().min(1, 'Headline is required').max(60, 'Headline must be 60 characters or fewer').default('Chat with us'),\n greeting: z.string().trim().min(1, 'Greeting is required').max(240, 'Greeting must be 240 characters or fewer').default('Hi! Send us a message and we will reply as soon as possible.'),\n inputPlaceholder: z.string().trim().min(1, 'Placeholder is required').max(80, 'Placeholder must be 80 characters or fewer').default('Type your message…'),\n contactFields: LiveChatContactFieldsSchema.default('optional'),\n accentColor: HexColorSchema.default('#111827'),\n launcherIconColor: HexColorSchema.default('#f9fafb'),\n});\n\nexport type LiveChatConfig = z.infer<typeof LiveChatConfigSchema>;\n\nexport type AnnouncementBarConfig = z.infer<typeof AnnouncementBarConfigSchema>;\nexport type CountdownBarConfig = z.infer<typeof CountdownBarConfigSchema>;\nexport type PromoInfoCardConfig = z.infer<typeof PromoInfoCardConfigSchema>;\nexport type RecentPurchasePopupConfig = z.infer<typeof RecentPurchasePopupConfigSchema>;\nexport type CouponPopupModalConfig = z.infer<typeof CouponPopupModalConfigSchema>;\n\nexport type StorefrontAddonConfigByType = {\n announcement_bar: AnnouncementBarConfig;\n countdown_bar: CountdownBarConfig;\n promo_info_card: PromoInfoCardConfig;\n recent_purchase_popup: RecentPurchasePopupConfig;\n coupon_popup_modal: CouponPopupModalConfig;\n live_chat: LiveChatConfig;\n};\n\nexport const StorefrontAddonConfigSchemaByType = {\n announcement_bar: AnnouncementBarConfigSchema,\n countdown_bar: CountdownBarConfigSchema,\n promo_info_card: PromoInfoCardConfigSchema,\n recent_purchase_popup: RecentPurchasePopupConfigSchema,\n coupon_popup_modal: CouponPopupModalConfigSchema,\n live_chat: LiveChatConfigSchema,\n} as const satisfies Record<StorefrontAddonType, z.ZodTypeAny>;\n\nconst AnnouncementBarDraftSchema = z.object({\n type: z.literal('announcement_bar'),\n slot: StorefrontAddonSlotSchema,\n enabled: z.boolean().default(true),\n sortOrder: z.number().int().min(0).max(999).default(0),\n config: AnnouncementBarConfigSchema,\n});\n\nconst RecentPurchasePopupDraftSchema = z.object({\n type: z.literal('recent_purchase_popup'),\n slot: StorefrontAddonSlotSchema,\n enabled: z.boolean().default(true),\n sortOrder: z.number().int().min(0).max(999).default(0),\n config: RecentPurchasePopupConfigSchema,\n});\n\nconst CountdownBarDraftSchema = z.object({\n type: z.literal('countdown_bar'),\n slot: StorefrontAddonSlotSchema,\n enabled: z.boolean().default(true),\n sortOrder: z.number().int().min(0).max(999).default(0),\n config: CountdownBarConfigSchema,\n});\n\nconst PromoInfoCardDraftSchema = z.object({\n type: z.literal('promo_info_card'),\n slot: StorefrontAddonSlotSchema,\n enabled: z.boolean().default(true),\n sortOrder: z.number().int().min(0).max(999).default(0),\n config: PromoInfoCardConfigSchema,\n});\n\nconst CouponPopupModalDraftSchema = z.object({\n type: z.literal('coupon_popup_modal'),\n slot: StorefrontAddonSlotSchema,\n enabled: z.boolean().default(true),\n sortOrder: z.number().int().min(0).max(999).default(0),\n config: CouponPopupModalConfigSchema,\n});\n\nconst LiveChatDraftSchema = z.object({\n type: z.literal('live_chat'),\n slot: StorefrontAddonSlotSchema,\n enabled: z.boolean().default(true),\n sortOrder: z.number().int().min(0).max(999).default(0),\n config: LiveChatConfigSchema,\n});\n\nexport const StorefrontAddonCreateSchema = z.discriminatedUnion('type', [\n AnnouncementBarDraftSchema,\n CountdownBarDraftSchema,\n PromoInfoCardDraftSchema,\n RecentPurchasePopupDraftSchema,\n CouponPopupModalDraftSchema,\n LiveChatDraftSchema,\n]);\n\nexport const StorefrontAddonUpdateSchema = z.discriminatedUnion('type', [\n AnnouncementBarDraftSchema.extend({\n id: z.string().min(1),\n }),\n CountdownBarDraftSchema.extend({\n id: z.string().min(1),\n }),\n PromoInfoCardDraftSchema.extend({\n id: z.string().min(1),\n }),\n RecentPurchasePopupDraftSchema.extend({\n id: z.string().min(1),\n }),\n CouponPopupModalDraftSchema.extend({\n id: z.string().min(1),\n }),\n LiveChatDraftSchema.extend({\n id: z.string().min(1),\n }),\n]);\n\nexport type StorefrontAddonCreateInput = z.infer<typeof StorefrontAddonCreateSchema>;\nexport type StorefrontAddonUpdateInput = z.infer<typeof StorefrontAddonUpdateSchema>;\n\nexport interface StorefrontAddonInstanceBase {\n id: string;\n shopId: string;\n type: StorefrontAddonType;\n slot: StorefrontAddonSlot;\n enabled: boolean;\n sortOrder: number;\n createdAt: string;\n updatedAt: string;\n}\n\nexport type StorefrontAddonInstance =\n | (StorefrontAddonInstanceBase & {\n type: 'announcement_bar';\n config: AnnouncementBarConfig;\n })\n | (StorefrontAddonInstanceBase & {\n type: 'countdown_bar';\n config: CountdownBarConfig;\n })\n | (StorefrontAddonInstanceBase & {\n type: 'promo_info_card';\n config: PromoInfoCardConfig;\n })\n | (StorefrontAddonInstanceBase & {\n type: 'recent_purchase_popup';\n config: RecentPurchasePopupConfig;\n })\n | (StorefrontAddonInstanceBase & {\n type: 'coupon_popup_modal';\n config: CouponPopupModalConfig;\n })\n | (StorefrontAddonInstanceBase & {\n type: 'live_chat';\n config: LiveChatConfig;\n });\n\nexport interface StorefrontAddonCatalogItem {\n type: StorefrontAddonType;\n title: string;\n description: string;\n slots: StorefrontAddonSlot[];\n supportsMultiple: boolean;\n features: string[];\n defaults: StorefrontAddonCreateInput;\n}\n\nexport interface AnnouncementBarResolvedProps extends AnnouncementBarConfig {\n addonId: string;\n}\n\nexport interface CountdownBarResolvedProps extends CountdownBarConfig {\n addonId: string;\n}\n\nexport interface PromoInfoCardResolvedProps extends PromoInfoCardConfig {\n addonId: string;\n}\n\nexport interface RecentPurchasePopupItem {\n customerLabel: string;\n productTitle: string;\n createdAt: string;\n}\n\nexport interface RecentPurchasePopupResolvedProps {\n addonId: string;\n title: string;\n cooldownSeconds: number;\n items: RecentPurchasePopupItem[];\n}\n\nexport interface CouponPopupModalResolvedProps extends CouponPopupModalConfig {\n addonId: string;\n}\n\nexport interface LiveChatResolvedProps extends LiveChatConfig {\n addonId: string;\n}\n\nexport type ResolvedStorefrontAddon =\n | {\n id: string;\n type: 'announcement_bar';\n slot: StorefrontAddonSlot;\n component: 'announcement_bar';\n sortOrder: number;\n props: AnnouncementBarResolvedProps;\n }\n | {\n id: string;\n type: 'countdown_bar';\n slot: StorefrontAddonSlot;\n component: 'countdown_bar';\n sortOrder: number;\n props: CountdownBarResolvedProps;\n }\n | {\n id: string;\n type: 'promo_info_card';\n slot: StorefrontAddonSlot;\n component: 'promo_info_card';\n sortOrder: number;\n props: PromoInfoCardResolvedProps;\n }\n | {\n id: string;\n type: 'recent_purchase_popup';\n slot: StorefrontAddonSlot;\n component: 'recent_purchase_popup';\n sortOrder: number;\n props: RecentPurchasePopupResolvedProps;\n }\n | {\n id: string;\n type: 'coupon_popup_modal';\n slot: StorefrontAddonSlot;\n component: 'coupon_popup_modal';\n sortOrder: number;\n props: CouponPopupModalResolvedProps;\n }\n | {\n id: string;\n type: 'live_chat';\n slot: StorefrontAddonSlot;\n component: 'live_chat';\n sortOrder: number;\n props: LiveChatResolvedProps;\n };\n\nexport interface StorefrontAddonBootstrap {\n items: ResolvedStorefrontAddon[];\n}\n","export const MANUAL_GATEWAY_TEMPLATE_VARIABLES = [\n 'amount',\n 'currency',\n 'invoice_id',\n 'customer_email',\n 'id',\n 'email',\n 'price',\n 'price_usd',\n 'product_name',\n 'quantity',\n] as const;\n\nexport type ManualGatewayTemplateVariable = typeof MANUAL_GATEWAY_TEMPLATE_VARIABLES[number];\nexport type ManualGatewayTemplateVars = Record<string, string>;\n\nexport const MANUAL_GATEWAY_TEMPLATE_VARIABLE_EXAMPLES = [\n '{{amount}}',\n '{{currency}}',\n '{{invoice_id}}',\n '{{customer_email}}',\n '{id}',\n '{email}',\n '{price}',\n '{currency}',\n '{price_usd}',\n '{product_name}',\n '{quantity}',\n] as const;\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nfunction buildVariablePattern(key: string, style: 'double' | 'single'): RegExp {\n const escapedKey = escapeRegExp(key);\n if (style === 'double') {\n return new RegExp(`\\\\{\\\\{\\\\s*${escapedKey}\\\\s*\\\\}\\\\}`, 'gi');\n }\n\n return new RegExp(`(?<!\\\\{)\\\\{\\\\s*${escapedKey}\\\\s*\\\\}(?!\\\\})`, 'gi');\n}\n\nexport function renderManualGatewayTemplate(\n template: string,\n vars: ManualGatewayTemplateVars,\n options: { encodeValues?: boolean } = {},\n): string {\n let rendered = template;\n for (const [key, value] of Object.entries(vars)) {\n const replacement = options.encodeValues ? encodeURIComponent(value) : value;\n rendered = rendered.replace(buildVariablePattern(key, 'double'), replacement);\n rendered = rendered.replace(buildVariablePattern(key, 'single'), replacement);\n }\n return rendered;\n}\n\nconst PLACEHOLDER_SCAN_PATTERNS = [\n /\\{\\{\\s*([a-zA-Z][a-zA-Z0-9_]*)\\s*\\}\\}/g,\n /(?<!\\{)\\{\\s*([a-zA-Z][a-zA-Z0-9_]*)\\s*\\}(?!\\})/g,\n] as const;\n\nconst REMAINING_PLACEHOLDER_PATTERNS = [\n /\\{\\{[\\s\\S]*?\\}\\}/g,\n /(?<!\\{)\\{[^{}]+\\}(?!\\})/g,\n] as const;\n\nexport const MANUAL_GATEWAY_CUSTOM_FIELD_NAME_PATTERN = /^[a-zA-Z][a-zA-Z0-9_]*$/;\n\nexport function isValidManualGatewayCustomFieldName(name: string): boolean {\n return MANUAL_GATEWAY_CUSTOM_FIELD_NAME_PATTERN.test(name.trim());\n}\n\nexport function findUnsupportedManualGatewayPlaceholders(\n template: string,\n additionalVariables: Iterable<string> = [],\n): string[] {\n if (!template.trim()) {\n return [];\n }\n\n const allowedVariables = new Set<string>(MANUAL_GATEWAY_TEMPLATE_VARIABLES);\n for (const variable of additionalVariables) {\n const normalized = variable.trim().toLowerCase();\n if (normalized) {\n allowedVariables.add(normalized);\n }\n }\n\n const unsupported = new Set<string>();\n // Track the raw spans of syntactically-valid placeholders that ARE allowed, so\n // we don't double-flag them when sweeping for malformed syntax below.\n const allowedRawSpans = new Set<string>();\n for (const pattern of PLACEHOLDER_SCAN_PATTERNS) {\n for (const match of template.matchAll(pattern)) {\n const raw = match[0];\n const name = match[1]?.toLowerCase();\n if (name && !allowedVariables.has(name)) {\n unsupported.add(raw);\n } else if (name) {\n allowedRawSpans.add(raw);\n }\n }\n }\n\n // Also reject ANY remaining {{...}}/{...} placeholder syntax that is not an\n // allowed variable — a mistyped or filtered token such as `{{order-id}}` or\n // `{{ amount | money }}` is not caught by the strict name patterns above, so\n // it would survive save and only fail at checkout (session 400 / raw token in\n // instructions). Flag it at save time instead.\n for (const pattern of REMAINING_PLACEHOLDER_PATTERNS) {\n for (const match of template.matchAll(pattern)) {\n const raw = match[0];\n if (!allowedRawSpans.has(raw)) {\n unsupported.add(raw);\n }\n }\n }\n\n return [...unsupported];\n}\n\nexport function collectUnsupportedManualGatewayPlaceholders(\n ...templates: Array<string | null | undefined>\n): string[] {\n const unsupported = new Set<string>();\n for (const template of templates) {\n for (const placeholder of findUnsupportedManualGatewayPlaceholders(template ?? '')) {\n unsupported.add(placeholder);\n }\n }\n return [...unsupported];\n}\n\nexport function collectUnsupportedManualGatewayPlaceholdersWithExtras(\n additionalVariables: Iterable<string>,\n ...templates: Array<string | null | undefined>\n): string[] {\n const unsupported = new Set<string>();\n for (const template of templates) {\n for (const placeholder of findUnsupportedManualGatewayPlaceholders(template ?? '', additionalVariables)) {\n unsupported.add(placeholder);\n }\n }\n return [...unsupported];\n}\n\nconst RESERVED_MANUAL_GATEWAY_FIELD_NAMES = new Set<string>(\n MANUAL_GATEWAY_TEMPLATE_VARIABLES.map((name) => name.toLowerCase()),\n);\n\nexport function isReservedManualGatewayFieldName(name: string): boolean {\n const normalized = name.trim().toLowerCase();\n return normalized.length > 0 && RESERVED_MANUAL_GATEWAY_FIELD_NAMES.has(normalized);\n}\n\nexport function findRemainingManualGatewayPlaceholders(template: string): string[] {\n if (!template.trim()) {\n return [];\n }\n\n const remaining = new Set<string>();\n for (const pattern of REMAINING_PLACEHOLDER_PATTERNS) {\n for (const match of template.matchAll(pattern)) {\n remaining.add(match[0]);\n }\n }\n\n return [...remaining];\n}\n\nexport function stableGatewayFieldValuesKey(fields: Record<string, string> | null | undefined): string {\n if (!fields) {\n return '{}';\n }\n\n const sortedEntries = Object.keys(fields)\n .sort((left, right) => left.localeCompare(right))\n .map((key) => [key, fields[key]] as const);\n\n return JSON.stringify(sortedEntries);\n}\n\nexport function isSafeManualGatewayRedirectUrl(url: string): boolean {\n const trimmed = url.trim();\n if (!trimmed) {\n return false;\n }\n\n try {\n const parsed = new URL(trimmed);\n return parsed.protocol === 'http:' || parsed.protocol === 'https:';\n } catch {\n return false;\n }\n}\n\nexport function mergeManualGatewayTemplateVars(\n trustedVars: ManualGatewayTemplateVars,\n gatewayFieldVars: Record<string, string> = {},\n): ManualGatewayTemplateVars {\n return {\n ...gatewayFieldVars,\n ...trustedVars,\n };\n}\n","import { z } from 'zod';\n\n/**\n * Versioned wire contract between Shoppex and a merchant-owned payment adapter.\n * A literal version makes breaking changes fail closed instead of being guessed.\n */\nexport const EXTERNAL_PAYMENT_ADAPTER_CONTRACT_VERSION = '2026-08-14' as const;\nexport { EXTERNAL_PAYMENT_ADAPTER_GATEWAY_PREFIX } from './payment-gateways.js';\nexport const EXTERNAL_PAYMENT_ADAPTER_TRUST_LEVEL = 'MERCHANT_ATTESTED' as const;\nexport const EXTERNAL_PAYMENT_ADAPTER_CONFORMANCE_PATH = '/.well-known/shoppex-payment-adapter' as const;\n\n/**\n * Maximum non-archived adapters per shop, matching the manual-gateway cap.\n * Enforced in ExternalPaymentAdapterService.create; the dashboard reads the\n * same constant for its usage badge so the two cannot drift.\n */\nexport const MAX_EXTERNAL_PAYMENT_ADAPTERS = 10;\n\nconst currencySchema = z.string().regex(/^[A-Z]{3}$/, 'Currency must be a three-letter uppercase code.');\nconst absoluteHttpsUrlSchema = z.string().url().refine(\n (value) => new URL(value).protocol === 'https:',\n 'URL must use HTTPS.',\n);\n\nconst externalPaymentAdapterBaseSchema = z.object({\n version: z.literal(EXTERNAL_PAYMENT_ADAPTER_CONTRACT_VERSION),\n});\n\nexport const externalPaymentAdapterSessionRequestSchema = externalPaymentAdapterBaseSchema.extend({\n type: z.literal('payment.session.create'),\n data: z.object({\n attempt_id: z.string().uuid(),\n invoice_id: z.string().uuid(),\n amount_minor: z.number().int().safe().positive(),\n currency: currencySchema,\n customer_email: z.string().email().nullable(),\n description: z.string().min(1).max(500),\n success_url: absoluteHttpsUrlSchema,\n cancel_url: absoluteHttpsUrlSchema,\n event_url: absoluteHttpsUrlSchema,\n }),\n});\n\nexport const externalPaymentAdapterSessionResponseSchema = externalPaymentAdapterBaseSchema.extend({\n provider_reference: z.string().trim().min(1).max(255),\n checkout_url: absoluteHttpsUrlSchema,\n expires_at: z.iso.datetime({ offset: true }).nullable().optional(),\n});\n\nexport const externalPaymentAdapterEventSchema = externalPaymentAdapterBaseSchema.extend({\n type: z.enum([\n 'payment.processing',\n 'payment.succeeded',\n 'payment.failed',\n ]),\n data: z.object({\n attempt_id: z.string().uuid(),\n provider_reference: z.string().trim().min(1).max(255),\n amount_minor: z.number().int().safe().positive(),\n currency: currencySchema,\n occurred_at: z.iso.datetime({ offset: true }).nullable().optional(),\n }),\n});\n\nexport const externalPaymentAdapterConformanceRequestSchema = externalPaymentAdapterBaseSchema.extend({\n type: z.literal('adapter.conformance.run'),\n data: z.object({\n challenge_id: z.string().uuid(),\n mode: z.enum(['standard', 'timeout']),\n expected_event: z.object({\n attempt_id: z.string().uuid(),\n provider_reference: z.string().trim().min(1).max(255),\n amount_minor: z.number().int().safe().positive(),\n currency: currencySchema,\n }),\n }),\n});\n\nexport const externalPaymentAdapterConformanceSampleSchema = z.object({\n scenario: z.enum([\n 'valid_event',\n 'amount_mismatch',\n 'duplicate_event_first',\n 'duplicate_event_retry',\n ]),\n webhook_id: z.string().trim().min(1).max(255),\n webhook_timestamp: z.string().trim().min(1).max(32),\n webhook_signature: z.string().trim().min(1).max(1024),\n raw_body: z.string().min(1).max(4096),\n});\n\nexport const externalPaymentAdapterConformanceResponseSchema = externalPaymentAdapterBaseSchema.extend({\n type: z.literal('adapter.conformance.result'),\n data: z.object({\n challenge_id: z.string().uuid(),\n samples: z.array(externalPaymentAdapterConformanceSampleSchema).length(4),\n }),\n});\n\nexport type ExternalPaymentAdapterSessionRequest = z.infer<\n typeof externalPaymentAdapterSessionRequestSchema\n>;\nexport type ExternalPaymentAdapterSessionResponse = z.infer<\n typeof externalPaymentAdapterSessionResponseSchema\n>;\nexport type ExternalPaymentAdapterEvent = z.infer<typeof externalPaymentAdapterEventSchema>;\nexport type ExternalPaymentAdapterConformanceRequest = z.infer<\n typeof externalPaymentAdapterConformanceRequestSchema\n>;\nexport type ExternalPaymentAdapterConformanceSample = z.infer<\n typeof externalPaymentAdapterConformanceSampleSchema\n>;\nexport type ExternalPaymentAdapterConformanceResponse = z.infer<\n typeof externalPaymentAdapterConformanceResponseSchema\n>;\n\nexport function buildExternalPaymentAdapterConformanceUrl(sessionEndpoint: string): string | null {\n try {\n const url = new URL(sessionEndpoint);\n if (url.protocol !== 'https:') return null;\n url.pathname = EXTERNAL_PAYMENT_ADAPTER_CONFORMANCE_PATH;\n url.search = '';\n url.hash = '';\n return url.toString();\n } catch {\n return null;\n }\n}\n\n// The gateway-key helpers live in payment-gateways.ts: that module is part of\n// the checkout client bundle and must not import this one (its relative\n// specifier breaks either NodeNext tsc, the tsup DTS build, or Turbopack,\n// depending on how it is written). This module is server-only, so re-exporting\n// from there is safe.\nexport {\n buildExternalPaymentAdapterGatewayKey,\n isExternalPaymentAdapterGatewayKey,\n parseExternalPaymentAdapterGatewayKey,\n type ExternalPaymentAdapterGatewayKey,\n} from './payment-gateways.js';\n","// Standalone product-redirect placeholder engine. Intentionally does NOT import from\n// manual-gateway-template.ts: that file is consumed via its own package subpath export\n// (@shoppex/contracts/manual-gateway-template), and a cross-subpath relative import here\n// breaks Next.js/Turbopack module resolution for client components that only depend on\n// this subpath. The scan/render logic is small enough to duplicate safely.\n\nexport const PRODUCT_REDIRECT_TEMPLATE_VARIABLES = ['product_id', 'order_id'] as const;\n\nexport type ProductRedirectTemplateVariable = typeof PRODUCT_REDIRECT_TEMPLATE_VARIABLES[number];\nexport type ProductRedirectTemplateVars = Record<ProductRedirectTemplateVariable, string>;\n\nexport const PRODUCT_REDIRECT_TEMPLATE_VARIABLE_EXAMPLES = [\n '{{product_id}}',\n '{{order_id}}',\n] as const;\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nfunction buildVariablePattern(key: string, style: 'double' | 'single'): RegExp {\n const escapedKey = escapeRegExp(key);\n if (style === 'double') {\n return new RegExp(`\\\\{\\\\{\\\\s*${escapedKey}\\\\s*\\\\}\\\\}`, 'gi');\n }\n\n return new RegExp(`(?<!\\\\{)\\\\{\\\\s*${escapedKey}\\\\s*\\\\}(?!\\\\})`, 'gi');\n}\n\n// Accepts a partial var map: only the keys present (and non-empty) are\n// substituted. A variable the caller cannot supply is left as a raw placeholder\n// so downstream fail-closed checks (findRemainingProductRedirectPlaceholders)\n// reject the URL instead of emitting an encoded \"\" / \"null\".\nexport function renderProductRedirectTemplate(\n template: string,\n vars: Partial<ProductRedirectTemplateVars>,\n): string {\n let rendered = template;\n for (const [key, value] of Object.entries(vars)) {\n if (typeof value !== 'string' || value.length === 0) continue;\n const replacement = encodeURIComponent(value);\n rendered = rendered.replace(buildVariablePattern(key, 'double'), replacement);\n rendered = rendered.replace(buildVariablePattern(key, 'single'), replacement);\n }\n return rendered;\n}\n\nconst PLACEHOLDER_SCAN_PATTERNS = [\n /\\{\\{\\s*([a-zA-Z][a-zA-Z0-9_]*)\\s*\\}\\}/g,\n /(?<!\\{)\\{\\s*([a-zA-Z][a-zA-Z0-9_]*)\\s*\\}(?!\\})/g,\n] as const;\n\nconst REMAINING_PLACEHOLDER_PATTERNS = [\n /\\{\\{[\\s\\S]*?\\}\\}/g,\n /(?<!\\{)\\{[^{}]+\\}(?!\\})/g,\n] as const;\n\n// A fully rendered redirect URL never contains a literal curly brace — any `{`\n// or `}` left after substitution is a malformed/unrendered placeholder fragment\n// (e.g. the unbalanced `{{product_id` or trailing `}` in `{{product_id}}}`).\n// The balanced-span patterns above miss these, so scan for any brace that\n// survives once the balanced spans are stripped out.\nfunction findDanglingBraceFragments(template: string): string[] {\n let stripped = template;\n for (const pattern of REMAINING_PLACEHOLDER_PATTERNS) {\n stripped = stripped.replace(pattern, '');\n }\n return /[{}]/.test(stripped) ? [...new Set(stripped.match(/[{}]+/g) ?? [])] : [];\n}\n\nexport function findUnsupportedProductRedirectPlaceholders(template: string): string[] {\n if (!template.trim()) {\n return [];\n }\n\n const allowedVariables = new Set<string>(PRODUCT_REDIRECT_TEMPLATE_VARIABLES);\n const unsupported = new Set<string>();\n const allowedRawSpans = new Set<string>();\n\n for (const pattern of PLACEHOLDER_SCAN_PATTERNS) {\n for (const match of template.matchAll(pattern)) {\n const raw = match[0];\n const name = match[1]?.toLowerCase();\n if (name && !allowedVariables.has(name)) {\n unsupported.add(raw);\n } else if (name) {\n allowedRawSpans.add(raw);\n }\n }\n }\n\n // Also reject malformed placeholder syntax (e.g. {{order-id}}, {{ product_id | x }}) that the\n // strict name patterns above don't match — same rationale as the manual-gateway scanner: catch\n // it at save time instead of letting a raw token survive to checkout.\n for (const pattern of REMAINING_PLACEHOLDER_PATTERNS) {\n for (const match of template.matchAll(pattern)) {\n const raw = match[0];\n if (!allowedRawSpans.has(raw)) {\n unsupported.add(raw);\n }\n }\n }\n\n // Reject unbalanced braces (e.g. `{{product_id` or `{{product_id}}}`) that the\n // balanced-span patterns never see — fail closed at save time rather than\n // letting a malformed token reach checkout.\n for (const fragment of findDanglingBraceFragments(template)) {\n unsupported.add(fragment);\n }\n\n return [...unsupported];\n}\n\nexport function findRemainingProductRedirectPlaceholders(template: string): string[] {\n if (!template.trim()) {\n return [];\n }\n\n const remaining = new Set<string>();\n for (const pattern of REMAINING_PLACEHOLDER_PATTERNS) {\n for (const match of template.matchAll(pattern)) {\n remaining.add(match[0]);\n }\n }\n\n // A rendered URL must not carry any leftover brace — including unbalanced ones\n // the balanced-span patterns miss — or checkout would redirect to a literal\n // malformed token instead of failing closed.\n for (const fragment of findDanglingBraceFragments(template)) {\n remaining.add(fragment);\n }\n\n return [...remaining];\n}\n\nexport function isSafeHttpsRedirectTemplateUrl(url: string): boolean {\n const trimmed = url.trim();\n if (!trimmed) {\n return false;\n }\n\n try {\n const parsed = new URL(trimmed);\n return parsed.protocol === 'https:';\n } catch {\n return false;\n }\n}\n","import { z } from 'zod';\n\nconst unknownRecordSchema = z.record(z.string(), z.unknown());\nconst stringOrNumberSchema = z.union([z.string(), z.number()]);\n\nexport const embedPaymentSessionWireSchema = z.object({\n kind: z.enum(['address', 'redirect', 'embed_pending']),\n gateway: z.string(),\n checkout_url: z.string().nullable().optional(),\n address: z.string().optional(),\n amount: z.string().optional(),\n qr_code: z.string().optional(),\n expires_at: z.string().optional(),\n payment_id: z.string().optional(),\n confirmations_needed: z.number().optional(),\n}).passthrough();\n\nconst publicInvoiceWireCustomFieldDefinitionSchema = z.object({\n default_value: z.string().optional(),\n min_length: z.number().optional(),\n name: z.string(),\n placeholder: z.string().optional(),\n regex: z.string().optional(),\n required: z.boolean(),\n type: z.string(),\n});\n\nconst publicInvoiceWireProductAddonSchema = z.object({\n id: z.string(),\n price: z.number(),\n quantity: z.number(),\n title: z.string(),\n});\n\nconst publicInvoiceWireAvailableAddonSchema = z.object({\n currency: z.string(),\n description: z.string(),\n id: z.string(),\n price: z.number(),\n title: z.string(),\n uniqid: z.string(),\n});\n\n/**\n * A null display price is only a legal wire state for PWYW products; a\n * fixed-price producer omitting it is a broken contract and must keep\n * failing fast (AGENTS.md forward-only rule).\n */\nfunction requirePriceDisplayUnlessPayWhatYouWant(\n product: { price_display: string | number | null; pay_what_you_want?: boolean },\n ctx: z.RefinementCtx,\n): void {\n if (product.price_display === null && product.pay_what_you_want !== true) {\n ctx.addIssue({\n code: 'custom',\n path: ['price_display'],\n message: 'price_display may only be null for pay_what_you_want products.',\n });\n }\n}\n\nconst publicInvoiceWireProductSchema = z.object({\n addons: z.array(publicInvoiceWireProductAddonSchema).optional(),\n /** Per-line cart-edit capability from the enricher; the checkout renders no\n * control without an explicit true. */\n quantity_editable: z.boolean().optional(),\n addons_editable: z.boolean().optional(),\n removable: z.boolean().optional(),\n available_addons: z.array(z.unknown()).optional(),\n cloudflare_image_id: z.string().nullable(),\n created_at: z.string().optional(),\n currency: z.string(),\n custom_fields: unknownRecordSchema.nullable().optional(),\n custom_fields_config: z.array(publicInvoiceWireCustomFieldDefinitionSchema).nullable().optional(),\n delivery_instruction: z.unknown().optional(),\n delivery_instruction_config: z.unknown().optional(),\n delivery_instruction_label: z.unknown().optional(),\n delivery_text: z.string().nullable().optional(),\n // Delivery wait as a bare COUNT. `0` and `null` both mean instant (the\n // digital-goods default); a positive value is a \"within N <unit>\" promise.\n delivery_time: z.number().nullable().optional(),\n // The unit `delivery_time` is counted in. The column is NOT NULL with a\n // `days` default — which is what every row meant before the unit existed — so\n // a live producer always sends one. It stays optional here because this\n // schema also describes payment-link and other synthesized products that\n // carry no catalog row, and those quote no wait at all.\n delivery_time_unit: z.enum(['minutes', 'hours', 'days']).nullable().optional(),\n description: z.string().nullable(),\n discount_percent: z.number().optional(),\n discount_display: z.number().optional(),\n discounted_total_display: z.number().optional(),\n gateways: z.array(z.string()).nullable().optional(),\n id: z.string().optional(),\n image_name: z.string().nullable(),\n image_storage: z.string().nullable().optional(),\n line_item_id: z.string().nullable().optional(),\n pay_what_you_want: z.boolean().optional(),\n price: z.string().optional(),\n // Nullable ONLY for PWYW products (no fixed catalog price until the buyer\n // chooses one) — enforced by requirePriceDisplayUnlessPayWhatYouWant below,\n // so a fixed-price producer dropping the field still fails fast.\n price_display: stringOrNumberSchema.nullable(),\n quantity: z.number(),\n quantity_max: z.number().optional(),\n quantity_min: z.number().optional(),\n recurring_interval: z.string().nullable().optional(),\n recurring_interval_count: z.number().nullable().optional(),\n redirect_link: z.string().nullable().optional(),\n redirect_time: z.number().nullable().optional(),\n service_text: z.string().nullable().optional(),\n setup_cost: z.string().optional(),\n slug: z.string().nullable().optional(),\n storefront_url: z.string().nullable().optional(),\n status: z.string().nullable().optional(),\n subtype: z.string().nullable().optional(),\n terms_of_service: z.string().nullable().optional(),\n title: z.string(),\n total: z.number(),\n trial_period: z.number().nullable().optional(),\n type: z.string().nullable().optional(),\n uniqid: z.string().nullable(),\n unit_price: z.number().optional(),\n unit_price_display: stringOrNumberSchema.optional(),\n unit_quantity: z.number(),\n updated_at: z.string().optional(),\n variant_title: z.string().nullable().optional(),\n video_link: z.string().nullable().optional(),\n volume_discounts: z.unknown().optional(),\n /** The SHORT replacement/refund eligibility window, in SECONDS. */\n warranty_days: z.number().nullable().optional(),\n warranty_text: z.string().nullable().optional(),\n /**\n * Long-term per-purchase coverage in DAYS, or null/absent for none.\n *\n * Deliberately a second field beside `warranty_days` rather than a rename:\n * they are different features that a similar name keeps conflating.\n * `warranty_days` is the seconds-long refund window; this is\n * Before payment this is the current `products.warranty_period_days` value.\n * After completion it is the invoice line's activated\n * `order_item_warranties.period_days` snapshot, so later product edits cannot\n * rewrite the buyer's receipt. Buyer surfaces read THIS one — reading\n * `warranty_days` would print a seconds count as a day count.\n */\n warranty_period_days: z.number().nullable().optional(),\n});\n\nconst gatewayFeePreviewSchema = z.object({\n amount: z.number(),\n gateway: z.string(),\n});\n\nconst checkoutTippingSchema = z.object({\n custom_tip_enabled: z.boolean().optional(),\n enabled: z.boolean(),\n preset_percentages: z.array(z.number()).optional(),\n});\n\nconst customerBalanceSchema = z.object({\n allow_partial_payment: z.boolean().optional(),\n auto_apply: z.boolean().optional(),\n available: z.string(),\n currency: z.string(),\n});\n\nconst pricingBreakdownSchema = z.object({\n affiliate_code: z.string().nullable().optional(),\n already_paid: stringOrNumberSchema.nullable().optional(),\n amount_due: stringOrNumberSchema.nullable().optional(),\n currency: z.string().nullable().optional(),\n discount: stringOrNumberSchema.nullable().optional(),\n volume_discount: stringOrNumberSchema.nullable().optional(),\n discount_label: z.string().nullable().optional(),\n gateway_fee: stringOrNumberSchema.nullable().optional(),\n platform_fee: stringOrNumberSchema.nullable().optional(),\n processing_fee: stringOrNumberSchema.nullable().optional(),\n subtotal: stringOrNumberSchema.nullable().optional(),\n tip: stringOrNumberSchema.nullable().optional(),\n total: stringOrNumberSchema.nullable().optional(),\n});\n\nconst pollingSchema = z.object({\n active: z.boolean(),\n expires_at: z.string(),\n});\n\nconst supportSchema = z.object({\n faq_url: z.string().nullable(),\n support_email: z.string().nullable(),\n support_url: z.string().nullable(),\n telegram_invite: z.string().nullable(),\n /** shop_social_links.discord — the checkout renders an optional join row from it. */\n discord_invite_url: z.string().nullable(),\n});\n\nconst gatewayEligibilityStateSchema = z.object({\n currency: z.string().nullable().optional(),\n enabled: z.boolean(),\n max_amount: z.number().nullable().optional(),\n min_amount: z.number().nullable().optional(),\n reason: z.enum(['BELOW_MIN_AMOUNT', 'ABOVE_MAX_AMOUNT']).nullable().optional(),\n});\n\nconst deliverySchema = z.object({\n delivered_items: z.array(z.unknown()),\n downloads: z.array(z.unknown()),\n external_urls: z.array(z.unknown()),\n license_keys: z.array(z.unknown()),\n tracking_codes: z.array(z.unknown()),\n});\n\nconst underpaymentSchema = z.object({\n active: z.boolean().optional(),\n attempt_id: z.string().optional(),\n buyer_actionable: z.boolean().nullable().optional(),\n crypto_currency: z.string().nullable().optional(),\n currency: z.string().optional(),\n expected_amount: z.string().nullable().optional(),\n expected_crypto_amount: z.string().nullable().optional(),\n last_checked_at: z.string().optional(),\n missing_amount: z.string().nullable().optional(),\n missing_crypto_amount: z.string().nullable().optional(),\n // InvoiceEnricher.applyUnderpayment serializes providerReference ?? null —\n // an active underpayment without a provider reference is a valid payload.\n provider_reference: z.string().nullable().optional(),\n provider_status: z.string().nullable().optional(),\n received_amount: z.string().nullable().optional(),\n /** Display-only fiat estimate for the crypto amount observed on-chain. */\n received_fiat_estimate: z.string().nullable().optional(),\n received_crypto_amount: z.string().nullable().optional(),\n shortfall_percent: z.string().nullable().optional(),\n buyer_action_reason: z.enum([\n 'BELOW_MINIMUM_COLLECTIBLE',\n 'PROVIDER_SESSION_CLOSED',\n 'PROVIDER_TOP_UP_UNSUPPORTED',\n 'MERCHANT_REVIEW_REQUIRED',\n ]).nullable().optional(),\n});\n\nconst statusHistoryEntrySchema = z.object({\n created_at: z.string().nullable(),\n details: z.string().nullable(),\n id: z.string(),\n invoice_id: z.string(),\n status: z.string().nullable(),\n});\n\nconst paymentMethodOverrideSchema = z.object({\n billing_address_mode: z.enum(['INHERIT', 'REQUIRED', 'DISABLED']).optional(),\n button_label: z.string().nullable().optional(),\n display_name: z.string().nullable().optional(),\n gateway: z.string(),\n hide_provider_attribution: z.boolean().optional(),\n icon_url: z.string().nullable().optional(),\n terms_mode: z.enum(['INHERIT', 'REQUIRED', 'DISABLED']).optional(),\n});\n\nconst customGatewaySchema = z.object({\n custom_fields: z.array(z.unknown()).optional(),\n description: z.string().nullable(),\n display_order: z.number(),\n icon_preset: z.string().nullable(),\n icon_url: z.string().nullable(),\n id: z.string(),\n instructions: z.string().nullable(),\n is_active: z.boolean().optional(),\n name: z.string(),\n payment_type: z.enum(['INSTRUCTIONS', 'REDIRECT']),\n redirect_url: z.string().nullable(),\n require_proof: z.boolean(),\n // Which fields the buyer has to fill in when proof is required. Optional so\n // an older cached payload stays parseable; the checkout falls back to BOTH.\n proof_type: z.enum(['TEXT', 'IMAGE', 'BOTH']).optional(),\n void_after_hours: z.number(),\n});\n\nconst externalPaymentAdapterSchema = z.object({\n description: z.string().nullable(),\n display_order: z.number(),\n icon_url: z.string().nullable(),\n id: z.string(),\n name: z.string(),\n});\n\nconst buyerIdentitySchema = z.object({\n email: z.object({\n masked: z.string().nullable(),\n persisted: z.boolean(),\n required_for_provider_session: z.boolean().optional(),\n }),\n});\n\nconst cryptoTransactionSchema = z.object({\n amount: z.string().nullable(),\n confirmations: z.number().nullable(),\n created_at: z.number().optional(),\n hash: z.string().nullable(),\n status: z.string().optional(),\n});\n\nconst voidTimeSchema = z.object({\n conf: z.object({\n partial: z.number().optional(),\n void: z.number(),\n waiting_for_confirmations: z.number().optional(),\n }),\n gateways: z.array(z.string()),\n});\n\nconst invoicePaymentSessionStateSchema = z.object({\n invoice_payable: z.boolean(),\n resumable: z.boolean(),\n resumable_gateway: z.string().nullable(),\n gateway: z.string().nullable().optional(),\n crypto_gateway: z.string().nullable().optional(),\n processor: z.string().nullable().optional(),\n flow_type: z.string().nullable().optional(),\n status: z.string().nullable().optional(),\n provider_reference: z.string().nullable().optional(),\n provider_reference_type: z.string().nullable().optional(),\n capture_id: z.string().nullable().optional(),\n manual_confirmation_pending: z.boolean().optional(),\n payment_method_switch_locked: z.boolean().optional(),\n awaiting_payment_method: z.boolean().optional(),\n started_at: z.number().nullable().optional(),\n completed_at: z.number().nullable().optional(),\n});\n\nconst embedInvoicePaymentSessionStateSchema = invoicePaymentSessionStateSchema.extend({\n gateway: z.string().nullable(),\n flow_type: z.string().nullable(),\n status: z.string().nullable(),\n manual_confirmation_pending: z.boolean(),\n payment_method_switch_locked: z.boolean(),\n});\n\n// Historic-data tolerance: invoices created before the embed surface collapsed\n// to a single design froze an `embed_design` key into\n// `invoices.checkout_style_snapshot`, and the API still serves those rows. This\n// object is non-strict, so the retired key is accepted and stripped rather than\n// rejected. Nothing reads it.\n//\n// The tolerance is deliberate but NOT self-evident — a non-strict object looks\n// like an oversight next to the `.strict()` schemas around it — so the\n// behaviour is pinned by\n// `apps/backend/tests/unit/style-center/invoice-wire-embed-design-tolerance.test.ts`\n// and listed for deletion in `docs/architecture/domains/style-center.md`,\n// Release 2. Unlike the transport and session shims this one has no runtime\n// signal to watch: the retired key is frozen into already-written invoice rows\n// rather than arriving from a client, so its removal condition is a data\n// question (are there pre-release invoices still being served?), answered\n// against `invoices.checkout_style_snapshot`, not a log line.\nconst checkoutStyleStateSchema = z.object({\n theme_id: z.string().nullable(),\n surface: z.enum(['checkout', 'payment_link', 'embed']),\n token_schema_version: z.literal(1),\n revision: z.number(),\n tokens: unknownRecordSchema,\n custom_css: z.string(),\n css_variables: z.record(z.string(), z.string()),\n});\n\nconst paymentRescueSchema = z.object({\n link_id: z.string(),\n source_gateway: z.string().nullable(),\n invoice_uniqid: z.string(),\n deprioritize_source_gateway: z.boolean().optional(),\n});\n\nconst discordIntegrationStateSchema = z.object({\n enabled: z.boolean(),\n required: z.boolean(),\n connected: z.boolean(),\n});\n\nconst shopPaymentGatewayFeeSchema = z.object({\n gateway: z.string().nullable().optional(),\n active_type: z.string().nullable().optional(),\n percent_amount: stringOrNumberSchema.nullable().optional(),\n fixed_amount: stringOrNumberSchema.nullable().optional(),\n fixed_currency: z.string().nullable().optional(),\n});\n\nconst invoiceRewardItemSchema = z.object({\n id: z.string(),\n type: z.enum(['WALLET_CREDIT', 'COUPON']),\n status: z.enum(['PENDING', 'FULFILLED', 'FAILED', 'REVOKED']),\n amount: z.string().nullable(),\n currency: z.string().nullable(),\n coupon_code: z.string().nullable(),\n reason: z.enum([\n 'ORDER_COMPLETED',\n 'ORDER_COUNT_REACHED',\n 'SPEND_AMOUNT_REACHED',\n 'POSITIVE_REVIEW_LEFT',\n 'FIRST_PURCHASE_COMPLETED',\n ]),\n trigger_reference_type: z.string(),\n trigger_reference_id: z.string(),\n created_at: z.number(),\n fulfilled_at: z.number().nullable(),\n expires_at: z.number().nullable(),\n});\n\nconst invoiceRewardsSchema = z.object({\n summary: z.object({\n available: z.string(),\n pending: z.string(),\n lifetime_earned: z.string(),\n redeemed: z.string().nullable(),\n currency: z.string(),\n }),\n activity: z.array(invoiceRewardItemSchema),\n earned_after_invoice: z.array(invoiceRewardItemSchema),\n pending_after_invoice: z.array(invoiceRewardItemSchema),\n});\n\n/**\n * Public invoice JSON after `toInvoiceTransportSnakeCase`.\n *\n * Gateway-specific invoice row fields can still pass the backend allowlist.\n * Unknown top-level keys are therefore preserved, while every known key is\n * validated whenever it is present.\n */\nexport const publicInvoiceWireSchema = z.object({\n already_paid_amount: stringOrNumberSchema.nullable().optional(),\n apm_method: z.string().nullable().optional(),\n blockchain: z.string().nullable(),\n buyer_identity: buyerIdentitySchema.nullable().optional(),\n checkout_tipping: checkoutTippingSchema.nullable().optional(),\n country_regulations: z.string().nullable().optional(),\n coupon_applied: z.boolean().optional(),\n crypto_mode: z.string().nullable().optional(),\n crypto_transactions: z.array(cryptoTransactionSchema).optional(),\n currency: z.string().nullable(),\n custom_fields: unknownRecordSchema.nullable().optional(),\n custom_gateways: z.array(customGatewaySchema).optional(),\n external_payment_adapters: z.array(externalPaymentAdapterSchema).optional(),\n customer_balance: customerBalanceSchema.nullable().optional(),\n customer_email_masked: z.string().nullable().optional(),\n dark_mode: z.union([z.literal(0), z.literal(1)]).optional(),\n delivery: deliverySchema.optional(),\n delivery_info: deliverySchema.optional(),\n discount: z.number().optional(),\n discount_display: stringOrNumberSchema.optional(),\n eligible_gateways: z.array(z.string()).optional(),\n environment: z.string().optional(),\n fee_breakdown: unknownRecordSchema.nullable().optional(),\n gateway: z.string().nullable(),\n gateway_data: unknownRecordSchema.nullable().optional(),\n gateway_eligibility: z.record(z.string(), gatewayEligibilityStateSchema).optional(),\n gateway_fee_previews: z.array(gatewayFeePreviewSchema).optional(),\n gateways_available: z.array(z.string()),\n license: z.union([unknownRecordSchema, z.literal(false)]).optional(),\n name: z.string().nullable(),\n paddle_token: z.string().nullable().optional(),\n paddle_transaction_id: z.unknown().optional(),\n payment_link_id: z.string().nullable().optional(),\n payment_method_overrides: z.array(paymentMethodOverrideSchema).optional(),\n payment_session_state: invoicePaymentSessionStateSchema.nullable().optional(),\n polling: pollingSchema,\n pricing_breakdown: pricingBreakdownSchema.nullable().optional(),\n product: z.array(\n publicInvoiceWireProductSchema.superRefine(requirePriceDisplayUnlessPayWhatYouWant),\n ).optional(),\n quantity: z.number().nullable(),\n rates_snapshot: z.record(z.string(), z.number()).optional(),\n remaining_amount: stringOrNumberSchema.nullable().optional(),\n selected_gateway: z.string().nullable().optional(),\n shop_checkout_ambient_color: z.string().nullable().optional(),\n shop_cloudflare_image_id: z.string().nullable(),\n shop_domain: z.string().nullable().optional(),\n shop_force_paypal_email_delivery: z.union([z.literal(0), z.literal(1)]).optional(),\n shop_image_name: z.string().nullable(),\n shop_image_storage: z.string().nullable().optional(),\n shop_payment_gateways_fees: z.array(unknownRecordSchema).optional(),\n shop_paypal_credit_card: z.union([z.literal(0), z.literal(1)]).optional(),\n shop_return_url: z.string().nullable().optional(),\n shop_slug: z.string().nullable().optional(),\n shop_terms_enabled: z.boolean().optional(),\n shop_terms_of_service: z.string().nullable().optional(),\n shop_terms_url: z.string().nullable().optional(),\n shop_privacy_policy_url: z.string().nullable().optional(),\n shop_refund_policy_url: z.string().nullable().optional(),\n shop_walletconnect_id: z.string().nullable().optional(),\n status: z.string().nullable(),\n status_history: z.array(statusHistoryEntrySchema).optional(),\n status_history_legacy: z.array(statusHistoryEntrySchema).optional(),\n status_history_raw: z.array(statusHistoryEntrySchema).optional(),\n stripe_publishable_key: z.string().nullable().optional(),\n stripe_user_id: z.string().nullable().optional(),\n subtotal: z.number().optional(),\n subtype: z.string().nullable().optional(),\n support: supportSchema.optional(),\n theme: z.string().optional(),\n tip_amount: stringOrNumberSchema.nullable().optional(),\n tip_amount_display: stringOrNumberSchema.nullable().optional(),\n tip_metadata: z.unknown().optional(),\n total: stringOrNumberSchema,\n total_conversions: unknownRecordSchema.optional(),\n total_display: stringOrNumberSchema,\n type: z.string().nullable(),\n underpayment: underpaymentSchema.nullable().optional(),\n underpayment_status: z.string().nullable().optional(),\n uniqid: z.string(),\n void_times: z.array(voidTimeSchema).optional(),\n\n // PUBLIC_INVOICE_FIELDS entries not exercised by the golden fixtures.\n addons: z.unknown().optional(),\n affiliate_data: z.unknown().optional(),\n affiliate_revenue_customer_id: z.string().nullable().optional(),\n bill_info: z.unknown().optional(),\n binance_checkout_url: z.string().nullable().optional(),\n binance_invoice_id: z.string().nullable().optional(),\n binance_qrcode: z.string().nullable().optional(),\n bundle_config: z.unknown().optional(),\n bundles: z.unknown().optional(),\n cashapp_cashtag: z.string().nullable().optional(),\n cashapp_note: z.string().nullable().optional(),\n cashapp_qrcode: z.string().nullable().optional(),\n created_at: z.string().optional(),\n crypto_address: z.string().nullable().optional(),\n crypto_amount: stringOrNumberSchema.optional(),\n crypto_confirmations_needed: z.number().nullable().optional(),\n crypto_exchange_rate: stringOrNumberSchema.nullable().optional(),\n crypto_received: stringOrNumberSchema.optional(),\n crypto_uri: z.string().nullable().optional(),\n developer_invoice: z.unknown().optional(),\n developer_return_url: z.string().nullable().optional(),\n developer_title: z.string().nullable().optional(),\n exchange_rate: stringOrNumberSchema.nullable().optional(),\n external_order_id: z.string().nullable().optional(),\n lex_order_id: z.string().nullable().optional(),\n lex_payment_method: z.string().nullable().optional(),\n paydash_payment_id: z.string().nullable().optional(),\n paypal_apm: z.string().nullable().optional(),\n paypal_email_delivery: z.boolean().optional(),\n paypal_fee: stringOrNumberSchema.nullable().optional(),\n paypal_order_id: z.string().nullable().optional(),\n paypal_payer_email: z.string().nullable().optional(),\n paypal_subscription_id: z.string().nullable().optional(),\n paypal_subscription_link: z.string().nullable().optional(),\n perfectmoney_id: z.string().nullable().optional(),\n product_addons: z.unknown().optional(),\n product_id: z.string().nullable().optional(),\n product_title: z.string().nullable().optional(),\n product_type: z.string().nullable().optional(),\n product_variants: z.unknown().optional(),\n recurring_billing_id: z.string().nullable().optional(),\n skrill_link: z.string().nullable().optional(),\n skrill_sid: z.string().nullable().optional(),\n status_details: z.unknown().optional(),\n stripe_apm: z.string().nullable().optional(),\n stripe_client_secret: z.string().nullable().optional(),\n stripe_id: z.string().nullable().optional(),\n stripe_price_id: z.string().nullable().optional(),\n subscription: z.unknown().optional(),\n subscription_id: z.string().nullable().optional(),\n sumup_id: z.string().nullable().optional(),\n telegram_stars_payment_link: z.string().nullable().optional(),\n telegram_stars_payment_note: z.string().nullable().optional(),\n updated_at: z.string().optional(),\n virtual_payments_id: z.string().nullable().optional(),\n void_details: z.unknown().optional(),\n}).catchall(z.unknown());\n\nexport type PublicInvoiceWire = z.infer<typeof publicInvoiceWireSchema>;\n\nexport const embedCheckoutProductWireSchema = publicInvoiceWireProductSchema.extend({\n available_addons: z.array(publicInvoiceWireAvailableAddonSchema).optional(),\n delivery_instructions: z.string().nullable().optional(),\n delivery_instructions_config: z.object({\n enabled: z.literal(true),\n required: z.boolean(),\n label: z.string(),\n placeholder: z.string().nullable().optional(),\n help_text: z.string().nullable().optional(),\n max_length: z.number(),\n }).nullable().optional(),\n delivery_instructions_label: z.string().nullable().optional(),\n image_url: z.string().nullable().optional(),\n redirectLink: z.string().nullable().optional(),\n redirectTime: z.number().nullable().optional(),\n serviceText: z.string().nullable().optional(),\n}).superRefine(requirePriceDisplayUnlessPayWhatYouWant);\n\nexport type EmbedCheckoutProductWire = z.infer<typeof embedCheckoutProductWireSchema>;\n\n/**\n * Invoice carried by the embed-start response.\n *\n * The public invoice contract validates the shared wire. These additions pin\n * fields that the checkout consumes directly and the legacy `products` alias\n * accepted by embedded clients.\n */\nexport const embedCheckoutInvoiceWireSchema = publicInvoiceWireSchema.extend({\n uniqid: z.string().uuid(),\n shop_id: z.union([z.string(), z.number()]).nullable(),\n customer_email: z.string().nullable(),\n checkout_style: checkoutStyleStateSchema.nullable().optional(),\n coupon_id: z.string().nullable().optional(),\n discount_breakdown: unknownRecordSchema.nullable().optional(),\n affiliate_code: z.string().nullable().optional(),\n country: z.string().nullable().optional(),\n paypal_email: z.string().nullable().optional(),\n pandabase_available_payment_methods: z.array(z.string()).optional(),\n payment_rescue: paymentRescueSchema.nullable().optional(),\n discord_integration: discordIntegrationStateSchema.nullable().optional(),\n payment_session_state: embedInvoicePaymentSessionStateSchema.nullable().optional(),\n shop_payment_gateways_fees: z.array(shopPaymentGatewayFeeSchema).optional(),\n product: z.array(embedCheckoutProductWireSchema).optional(),\n products: z.array(embedCheckoutProductWireSchema).optional(),\n rewards: invoiceRewardsSchema.nullable().optional(),\n}).superRefine((invoice, context) => {\n if (invoice.product === undefined && invoice.products === undefined) {\n context.addIssue({\n code: 'custom',\n message: 'Embed checkout invoice must include product or products.',\n path: ['product'],\n });\n }\n});\n\nexport type EmbedCheckoutInvoiceWire = z.infer<typeof embedCheckoutInvoiceWireSchema>;\n\n/** Critical runtime boundary for the public embed-start response. */\nexport const embedCheckoutStartWireSchema = z.object({\n data: z.object({\n invoice: embedCheckoutInvoiceWireSchema,\n invoice_url: z.string().nullable(),\n checkout_url: z.string().nullable(),\n selected_gateway: z.string().nullable(),\n session_started: z.boolean(),\n payment_session: embedPaymentSessionWireSchema.nullable(),\n completion_access_grant: z.string().nullable(),\n }).passthrough(),\n}).passthrough();\n\nexport type EmbedCheckoutStartWire = z.infer<typeof embedCheckoutStartWireSchema>;\n","/**\n * Catalog unit prices support mills (one thousandth of a currency unit).\n *\n * This is intentionally separate from invoice and payment totals. A unit can\n * cost $0.012, while the payable line total is still rounded to the currency's\n * minor unit after `unit price × quantity`.\n */\nexport const CATALOG_UNIT_PRICE_DECIMAL_PLACES = 3;\n\n/**\n * Payable line amounts and invoice totals remain cent amounts. This is a\n * separate boundary from catalog unit prices: multiply the mill-priced unit by\n * quantity first, then round the resulting line amount to this precision.\n */\nexport const PAYABLE_AMOUNT_DECIMAL_PLACES = 2;\n\nexport const CATALOG_UNIT_PRICE_FORMAT_OPTIONS = {\n maximumFractionDigits: CATALOG_UNIT_PRICE_DECIMAL_PLACES,\n} as const;\n\n/**\n * Browser-safe half-up rounding for non-negative payable amounts.\n *\n * The exponent shift avoids the common `1.005 * 100` binary-float trap and\n * mirrors the backend's decimal.js ROUND_HALF_UP policy. Negative values are\n * handled symmetrically so the helper remains safe for display calculations.\n */\nexport function roundPayableAmount(value: number): number {\n if (!Number.isFinite(value)) return value;\n\n const sign = value < 0 ? -1 : 1;\n const shifted = shiftDecimal(Math.abs(value), PAYABLE_AMOUNT_DECIMAL_PLACES);\n const rounded = Math.round(shifted);\n if (rounded === 0) return 0;\n return sign * shiftDecimal(rounded, -PAYABLE_AMOUNT_DECIMAL_PLACES);\n}\n\nfunction shiftDecimal(value: number, places: number): number {\n const [coefficient, currentExponent = '0'] = String(value).split('e');\n return Number(`${coefficient}e${Number(currentExponent) + places}`);\n}\n\nfunction countSignificantDecimalPlaces(value: string | number): number | null {\n const source = String(value).trim();\n const match = source.match(/^[-+]?(\\d+)(?:\\.(\\d*))?(?:e([-+]?\\d+))?$/i)\n ?? source.match(/^[-+]?\\.(\\d+)(?:e([-+]?\\d+))?$/i);\n if (!match) return null;\n\n const startsWithDecimalPoint = /^[-+]?\\./.test(source);\n const integerPart = startsWithDecimalPoint ? '0' : match[1];\n const fractionPart = startsWithDecimalPoint ? match[1] : (match[2] ?? '');\n const exponentText = startsWithDecimalPoint ? match[2] : match[3];\n const exponent = Number(exponentText ?? 0);\n if (!Number.isInteger(exponent)) return null;\n\n const digitsWithoutInsignificantZeros = `${integerPart}${fractionPart}`.replace(/0+$/, '');\n if (digitsWithoutInsignificantZeros.length === 0) return 0;\n\n const decimalPoint = integerPart.length + exponent;\n return Math.max(0, digitsWithoutInsignificantZeros.length - decimalPoint);\n}\n\nexport function hasCatalogUnitPricePrecision(value: string | number): boolean {\n const decimalPlaces = countSignificantDecimalPlaces(value);\n return decimalPlaces !== null && decimalPlaces <= CATALOG_UNIT_PRICE_DECIMAL_PLACES;\n}\n\nexport function getCatalogUnitPricePrecisionMessage(value: string | number): string {\n return `Price supports at most ${CATALOG_UNIT_PRICE_DECIMAL_PLACES} decimal places; received ${String(value)}.`;\n}\n","/**\n * @shoppex/contracts\n *\n * Shared TypeScript types generated from OpenAPI spec.\n * These types ensure type-safety between the Elysia API runtime and frontend apps.\n *\n * Usage:\n * import { paths, components } from '@shoppex/contracts/api-types';\n * import { createApiClient } from '@shoppex/contracts';\n */\n\nimport createClient from 'openapi-fetch';\nimport type { paths } from './api-types.js';\n\n// Re-export generated types\nexport * from './api-types.js';\nexport * from './navigation.js';\nexport * from './observability.js';\nexport * from './email-marketing.js';\nexport * from './payment-gateways.js';\nexport * from './platform-billing.js';\nexport * from './style-center.js';\nexport * from './style-center/presets.js';\nexport * from './storefront-addons.js';\nexport * from './api-error-codes.js';\nexport * from './merchant-safe-errors.js';\nexport * from './manual-gateway-template.js';\nexport * from './external-payment-adapter.js';\nexport * from './redirect-link-template.js';\nexport * from './checkout-api.js';\nexport * from './invoice-wire.js';\nexport * from './developer-webhook.js';\nexport * from './catalog-unit-price.js';\nexport * from './customer-portal-wire.js';\nexport * from './type-assertions.js';\nexport * from './theme-ai-handoff.js';\n\n/**\n * Create a type-safe API client\n *\n * @example\n * const client = createApiClient('https://api.shoppex.io/v1');\n *\n * // Fully typed request and response\n * const { data, error } = await client.GET('/products', {\n * params: { query: { page: 1, limit: 25 } }\n * });\n */\nexport function createApiClient(baseUrl: string, token?: string) {\n return createClient<paths>({\n baseUrl,\n headers: token ? { Authorization: `Bearer ${token}` } : undefined,\n });\n}\n\n// Common response types used across the app\nexport interface ApiResponse<T> {\n status: number;\n data: T | null;\n error: string | null;\n message: string | null;\n env: string;\n}\n\nexport interface PaginatedResponse<T> {\n data: T[];\n meta: {\n total: number;\n page: number;\n perPage: number;\n totalPages: number;\n };\n}\n\nexport interface ApiError {\n status: number;\n error: string;\n message: string;\n}\n","/**\n * Typed OpenAPI client factory.\n *\n * Surfaces the generated `createApiClient` from `@shoppex/contracts` with the\n * SDK's configured `apiBaseUrl`. This lets consumers of `@shoppexio/storefront`\n * call any public Dev API endpoint with full end-to-end types without\n * rebuilding a client from scratch.\n *\n * Prefer the high-level modules (`shoppex.getProducts()` etc.) for common\n * read flows — they handle caching, pagination defaults, and storefront\n * scoping. Drop down to `shoppex.client()` only when you need an endpoint\n * the high-level API does not cover yet.\n */\n\nimport { createApiClient } from '@shoppex/contracts';\nimport { DEFAULT_API_BASE_URL, getConfig } from './config';\n\ntype ApiClient = ReturnType<typeof createApiClient>;\n\nlet cachedClient: ApiClient | null = null;\nlet cachedBaseUrl: string | null = null;\n\n/**\n * Return a typed OpenAPI client bound to the SDK's configured API base URL.\n * The client is cached per base URL and recreated when the SDK is re-initialized\n * against a different host.\n */\nexport function getTypedClient(token?: string): ApiClient {\n const config = getConfig();\n const baseUrl = config.apiBaseUrl ?? DEFAULT_API_BASE_URL;\n\n if (cachedClient && cachedBaseUrl === baseUrl && !token) {\n return cachedClient;\n }\n\n const client = createApiClient(baseUrl, token);\n\n if (!token) {\n cachedClient = client;\n cachedBaseUrl = baseUrl;\n }\n\n return client;\n}\n\n/**\n * Reset the cached client. Called when the SDK is re-initialized so that a new\n * `apiBaseUrl` takes effect immediately on the next `client()` call.\n */\nexport function resetTypedClient(): void {\n cachedClient = null;\n cachedBaseUrl = null;\n}\n","/**\n * SDK Configuration Management\n */\n\nimport type { ShoppexConfig, ShoppexInitOptions } from '../types';\nimport { clearCache } from './cache';\nimport { NotInitializedError } from './errors';\nimport { resetTypedClient } from './typed-client';\n\nexport const DEFAULT_API_BASE_URL = 'https://api.shoppex.io';\n\nlet currentConfig: ShoppexConfig | null = null;\nlet cachedShopId: string | null = null;\n\nexport const DEFAULT_CHECKOUT_BASE_URL = 'https://checkout.shoppex.io';\n\nexport function initConfig(\n storeSlug: string,\n options?: ShoppexInitOptions\n): ShoppexConfig {\n const normalizedShopId = options?.shopId?.trim();\n\n // Reset cached shop id on every init to avoid cross-store leakage\n // when the SDK is re-initialized with a different slug.\n cachedShopId = normalizedShopId ? normalizedShopId : null;\n\n const previousLocale = currentConfig?.locale;\n currentConfig = {\n storeSlug,\n locale: options?.locale,\n currency: options?.currency,\n apiBaseUrl: options?.apiBaseUrl ?? DEFAULT_API_BASE_URL,\n checkoutBaseUrl: options?.checkoutBaseUrl ?? DEFAULT_CHECKOUT_BASE_URL,\n };\n // Response cache keys are locale-agnostic (products:slug, product:id, …) —\n // a locale switch across re-inits must not serve the previous locale's\n // payloads for up to the cache TTL (Codex P2).\n if (previousLocale !== currentConfig.locale) {\n clearCache();\n }\n resetTypedClient();\n return currentConfig;\n}\n\nexport function getConfig(): ShoppexConfig {\n if (!currentConfig) {\n throw new NotInitializedError();\n }\n return currentConfig;\n}\n\nexport function isInitialized(): boolean {\n return currentConfig !== null;\n}\n\nexport function resetConfig(): void {\n currentConfig = null;\n cachedShopId = null;\n resetTypedClient();\n}\n\nexport function setShopId(shopId: string): void {\n cachedShopId = shopId;\n}\n\nexport function getShopId(): string | null {\n return cachedShopId;\n}\n","export interface StorefrontCustomField {\n name: string;\n type: string;\n required: boolean;\n defaultValue: string;\n placeholder: string;\n regex?: string;\n}\n\nfunction parseCustomFieldsSource(raw: unknown): unknown[] {\n if (Array.isArray(raw)) return raw;\n\n if (typeof raw === 'string') {\n try {\n const parsed = JSON.parse(raw) as unknown;\n if (Array.isArray(parsed)) return parsed;\n if (parsed && typeof parsed === 'object') {\n const fields = (parsed as { custom_fields?: unknown[]; customFields?: unknown[] }).custom_fields\n ?? (parsed as { custom_fields?: unknown[]; customFields?: unknown[] }).customFields;\n return Array.isArray(fields) ? fields : [];\n }\n } catch {\n return [];\n }\n\n return [];\n }\n\n if (raw && typeof raw === 'object') {\n const fields = (raw as { custom_fields?: unknown[]; customFields?: unknown[] }).custom_fields\n ?? (raw as { custom_fields?: unknown[]; customFields?: unknown[] }).customFields;\n return Array.isArray(fields) ? fields : [];\n }\n\n return [];\n}\n\nexport function normalizeStorefrontCustomFields(raw: unknown): StorefrontCustomField[] {\n return parseCustomFieldsSource(raw)\n .filter((field): field is Record<string, unknown> => !!field && typeof field === 'object' && !Array.isArray(field))\n .map((field) => {\n const rawType = typeof field.type === 'string' ? field.type.trim().toLowerCase() : 'text';\n const type = rawType.length > 0 ? rawType : 'text';\n const defaultValue = [\n field.default_value,\n field.default,\n field.value,\n ].find((candidate) => typeof candidate === 'string' && candidate.trim().length > 0);\n\n return {\n name: typeof field.name === 'string' ? field.name.trim() : '',\n type,\n required: field.required === true || field.required === 'true' || field.required === 1 || field.required === '1',\n defaultValue: typeof defaultValue === 'string' ? defaultValue : '',\n placeholder: typeof field.placeholder === 'string' ? field.placeholder : '',\n regex: typeof field.regex === 'string' ? field.regex : undefined,\n };\n })\n .filter((field) => field.name.length > 0 && field.type !== 'hidden');\n}\n\nexport function isStorefrontCheckboxCustomFieldValueChecked(value: string | undefined): boolean {\n const normalized = value?.trim().toLowerCase() ?? '';\n return normalized === 'true' || normalized === '1' || normalized === 'yes' || normalized === 'on';\n}\n\nexport function validateStorefrontCustomFieldValue(field: StorefrontCustomField, value: string): string | null {\n if (field.type === 'checkbox') {\n if (field.required && !isStorefrontCheckboxCustomFieldValueChecked(value)) {\n return `${field.name} is required.`;\n }\n return null;\n }\n\n const normalized = value.trim();\n if (field.required && !normalized) {\n return `${field.name} is required.`;\n }\n\n if (field.regex && normalized) {\n try {\n const pattern = new RegExp(field.regex);\n if (!pattern.test(normalized)) {\n return `${field.name} has an invalid format.`;\n }\n } catch {\n return null;\n }\n }\n\n return null;\n}\n\nexport function buildStorefrontCustomFieldPayload(\n fields: StorefrontCustomField[],\n values: Record<string, string>,\n): Record<string, string> {\n const nextValues: Record<string, string> = {};\n\n fields.forEach((field) => {\n const rawValue = values[field.name] ?? field.defaultValue ?? '';\n\n if (field.type === 'checkbox') {\n if (isStorefrontCheckboxCustomFieldValueChecked(rawValue)) {\n nextValues[field.name] = 'true';\n }\n return;\n }\n\n const normalized = rawValue.trim();\n if (normalized.length > 0) {\n nextValues[field.name] = normalized;\n }\n });\n\n return nextValues;\n}\n","import type { Product, PriceVariant, ProductVariant } from '../types/index.js';\n\ntype VariantLike =\n | Pick<ProductVariant, 'stock' | 'orderable' | 'supplier_backed'>\n | Pick<PriceVariant, 'stock' | 'orderable' | 'supplier_backed'>;\n\ntype ProductLike = Pick<Product, 'type' | 'stock' | 'orderable' | 'supplier_backed' | 'on_hold' | 'price_variants' | 'variants'> & {\n onHold?: boolean | number | string | null;\n is_on_hold?: boolean | number | string | null;\n isOnHold?: boolean | number | string | null;\n};\n\n/** The sentinel every predicate in this module already treats as \"unbounded\". */\nconst UNLIMITED_STOCK = -1;\n\n/**\n * Dynamic Delivery (S8): fold `orderable` into the stock value.\n *\n * `orderable` is the backend's authoritative buyability predicate — `local stock\n * covers one unit OR an eligible supplier source can fulfil the line` — and it is\n * exactly what the order-time gates apply. A supplier-backed row holds NO local\n * stock by design, so gating the buyer on `stock` alone renders it \"out of stock\"\n * and the purchase can never happen.\n *\n * Rather than introduce a fourth availability state, a row that is orderable\n * without local units is normalised to the unlimited sentinel — the same value an\n * unlimited row already carries. Every downstream badge, quantity cap, variant\n * gate and CTA then behaves as it already does for unlimited stock.\n *\n * `orderable` alone cannot decide how far to widen: it is also `true` for an\n * ordinary locally-stocked row, whose finite counter must stay finite. That is what\n * `supplier_backed` settles. A supplier-backed row is fulfilled by the supplier\n * purchase and the completion excludes it from the local decrement, so any residual\n * local units bound NOTHING — its cap is unlimited even at `stock: 1`. A row that is\n * NOT supplier-backed keeps its exact finite counter, and only widens from 0 (the\n * product-wide mapping case, where the backend folded the mapping into `orderable`\n * and left `stock` at 0).\n *\n * When `orderable` is absent (an older payload or a cached response shape that\n * predates the field) the raw value is returned UNCHANGED, and an absent\n * `supplier_backed` widens nothing beyond what the previous rule already did. That\n * is the only permitted fallback direction: a missing field must never flip a\n * genuinely sold-out row into a buyable one, nor a finite counter into unlimited.\n */\nfunction applyOrderable(stock: number, orderable: unknown, supplierBacked?: unknown): number {\n if (orderable !== true) {\n return stock;\n }\n // Supplier-backed: local units do not bound the line, at any stock value.\n if (supplierBacked === true) {\n return UNLIMITED_STOCK;\n }\n // Already buyable or already unbounded — nothing to widen.\n if (stock !== 0) {\n return stock;\n }\n return UNLIMITED_STOCK;\n}\n\nfunction normalizeStockValue(value: unknown): number | null {\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n return null;\n }\n\n return Math.trunc(value);\n}\n\nfunction isTruthyFlag(value: unknown): boolean {\n if (value === true) return true;\n if (typeof value === 'number' && Number.isFinite(value)) return value !== 0;\n if (typeof value === 'string') {\n const normalized = value.trim().toLowerCase();\n return normalized === 'true' || normalized === '1';\n }\n return false;\n}\n\nfunction isProductOnHold(product: ProductLike | null | undefined): boolean {\n if (!product) return false;\n return isTruthyFlag(product.on_hold)\n || isTruthyFlag(product.onHold)\n || isTruthyFlag(product.is_on_hold)\n || isTruthyFlag(product.isOnHold);\n}\n\nfunction collectVariantStocks(product: ProductLike): number[] {\n const priceVariants = Array.isArray(product.price_variants) ? product.price_variants : [];\n if (priceVariants.length > 0) {\n return priceVariants.map((variant) => resolveVariantStockValue(variant));\n }\n\n const legacyVariants = Array.isArray(product.variants) ? product.variants : [];\n\n return legacyVariants.map((variant) => resolveVariantStockValue(variant));\n}\n\nexport function resolveVariantStockValue(variant: VariantLike | null | undefined): number {\n const normalized = normalizeStockValue(variant?.stock);\n return applyOrderable(normalized ?? UNLIMITED_STOCK, variant?.orderable, variant?.supplier_backed);\n}\n\nexport function resolveDisplayStock(product: ProductLike | null | undefined): number {\n if (!product) {\n return UNLIMITED_STOCK;\n }\n\n if (typeof product.type === 'string' && product.type.toUpperCase() === 'SERIALS') {\n return applyOrderable(\n normalizeStockValue(product.stock) ?? UNLIMITED_STOCK,\n product.orderable,\n product.supplier_backed,\n );\n }\n\n const variantStocks = collectVariantStocks(product);\n if (variantStocks.length > 0) {\n // A single unbounded option (including a supplier-backed one, already folded\n // into the sentinel above) makes the product unbounded — summing finite\n // siblings would understate it.\n if (variantStocks.some((stock) => stock < 0)) {\n return UNLIMITED_STOCK;\n }\n\n const total = variantStocks.reduce((sum, stock) => sum + Math.max(stock, 0), 0);\n // The product-level flag still applies: the backend folds a product-wide\n // supplier mapping into it, and that mapping backs options with no local units.\n return applyOrderable(total, product.orderable, product.supplier_backed);\n }\n\n return applyOrderable(\n normalizeStockValue(product.stock) ?? UNLIMITED_STOCK,\n product.orderable,\n product.supplier_backed,\n );\n}\n\nexport function isProductOutOfStock(product: ProductLike | null | undefined): boolean {\n // `on_hold` is a merchant pause, not a supply signal — it forces unavailable\n // BEFORE any `orderable` widening can apply.\n if (isProductOnHold(product)) return true;\n return resolveDisplayStock(product) === 0;\n}\n\nexport function isProductInStock(product: ProductLike | null | undefined): boolean {\n return !isProductOutOfStock(product);\n}\n\nexport function isVariantOutOfStock(variant: VariantLike | null | undefined): boolean {\n return resolveVariantStockValue(variant) === 0;\n}\n","import type { Product, ProductGroup } from '../types/index.js';\n\nexport function buildStorefrontProductLookup(products: Product[] = []): Map<string, Product> {\n const lookup = new Map<string, Product>();\n for (const product of products) {\n if (!product?.uniqid || lookup.has(product.uniqid)) continue;\n lookup.set(product.uniqid, product);\n }\n return lookup;\n}\n\n// Groups reference their products by uniqid; the objects live once in `products`.\nexport function getStorefrontGroupProducts(\n group: ProductGroup,\n productsOrLookup: Product[] | Map<string, Product> = [],\n): Product[] {\n const lookup = productsOrLookup instanceof Map\n ? productsOrLookup\n : buildStorefrontProductLookup(productsOrLookup);\n return (group.product_uniqids ?? []).flatMap((uniqid) => {\n const product = lookup.get(uniqid);\n return product ? [product] : [];\n });\n}\n\nexport function getMergedStorefrontProducts(products: Product[] = []): Product[] {\n return Array.from(buildStorefrontProductLookup(products).values());\n}\n","import type { Product, ProductGroup } from '../types/index.js';\nimport {\n buildStorefrontProductLookup,\n getMergedStorefrontProducts,\n getStorefrontGroupProducts,\n} from './storefront-catalog.js';\nimport { isProductInStock } from './storefront-stock.js';\n\nexport interface StorefrontSearchFilterOptions {\n hideOutOfStock?: boolean;\n maxResults?: number;\n}\n\nexport type StorefrontCatalogSearchItem =\n | { type: 'product'; product: Product }\n // Groups only carry `product_uniqids`; `products` holds the resolved product\n // objects (in group order) so consumers never re-resolve references themselves.\n | { type: 'group'; group: ProductGroup; products: Product[] };\n\nexport function stripHtmlFromText(value: string | null | undefined): string {\n if (!value) return '';\n return value.replace(/<[^>]*>/g, ' ').replace(/\\s+/g, ' ').trim();\n}\n\nexport function normalizeSearchQuery(query: string): string {\n return query.trim().toLowerCase();\n}\n\nfunction pushSearchPart(parts: string[], value: string | null | undefined): void {\n const normalized = stripHtmlFromText(value).toLowerCase();\n if (normalized) {\n parts.push(normalized);\n }\n}\n\nexport function collectProductSearchHaystack(product: Product): string[] {\n const parts: string[] = [];\n\n pushSearchPart(parts, product.title);\n pushSearchPart(parts, product.slug ?? undefined);\n pushSearchPart(parts, product.description);\n\n for (const highlight of product.product_highlights ?? []) {\n pushSearchPart(parts, highlight);\n }\n\n for (const variant of product.variants ?? []) {\n pushSearchPart(parts, variant.title);\n }\n\n for (const variant of product.price_variants ?? []) {\n pushSearchPart(parts, variant.title ?? variant.label);\n }\n\n return parts;\n}\n\nexport function productMatchesSearchQuery(product: Product, query: string): boolean {\n const normalized = normalizeSearchQuery(query);\n if (!normalized) return false;\n\n return collectProductSearchHaystack(product).some((haystack) => haystack.includes(normalized));\n}\n\nexport function groupMatchesSearchQuery(group: ProductGroup, query: string): boolean {\n const normalized = normalizeSearchQuery(query);\n if (!normalized) return false;\n\n const title = stripHtmlFromText(group.title).toLowerCase();\n const slug = stripHtmlFromText(group.slug ?? group.name ?? undefined).toLowerCase();\n const description = stripHtmlFromText(group.description).toLowerCase();\n\n return title.includes(normalized)\n || slug.includes(normalized)\n || description.includes(normalized);\n}\n\nexport function filterProductsBySearchQuery(\n products: Product[],\n query: string,\n options?: StorefrontSearchFilterOptions,\n): Product[] {\n const normalized = normalizeSearchQuery(query);\n if (!normalized) return [];\n\n let results = products.filter((product) => productMatchesSearchQuery(product, normalized));\n\n if (options?.hideOutOfStock) {\n results = results.filter((product) => isProductInStock(product));\n }\n\n if (options?.maxResults != null) {\n return results.slice(0, options.maxResults);\n }\n\n return results;\n}\n\nfunction groupHasVisibleProducts(\n groupProducts: Product[],\n hideOutOfStock: boolean,\n): boolean {\n if (groupProducts.length === 0) return false;\n if (!hideOutOfStock) return true;\n return groupProducts.some((product) => isProductInStock(product));\n}\n\nexport function searchMergedStorefrontCatalogItems(\n products: Product[],\n groups: ProductGroup[],\n query: string,\n options?: StorefrontSearchFilterOptions,\n): StorefrontCatalogSearchItem[] {\n const normalized = normalizeSearchQuery(query);\n if (!normalized) return [];\n\n const hideOutOfStock = options?.hideOutOfStock === true;\n const coveredProductIds = new Set<string>();\n const coveredGroupIds = new Set<string>();\n const results: StorefrontCatalogSearchItem[] = [];\n // Build the uniqid lookup once per search run; groups resolve against it.\n const lookup = buildStorefrontProductLookup(products);\n\n for (const group of groups) {\n const groupKey = group.uniqid ?? group.id;\n if (!groupKey || coveredGroupIds.has(groupKey)) continue;\n if (!groupMatchesSearchQuery(group, normalized)) continue;\n\n const groupProducts = getStorefrontGroupProducts(group, lookup);\n if (!groupHasVisibleProducts(groupProducts, hideOutOfStock)) continue;\n\n coveredGroupIds.add(groupKey);\n for (const product of groupProducts) {\n if (product?.uniqid) coveredProductIds.add(product.uniqid);\n }\n results.push({ type: 'group', group, products: groupProducts });\n }\n\n const merged = getMergedStorefrontProducts(products);\n for (const product of merged) {\n if (!product?.uniqid || coveredProductIds.has(product.uniqid)) continue;\n if (!productMatchesSearchQuery(product, normalized)) continue;\n if (hideOutOfStock && !isProductInStock(product)) continue;\n coveredProductIds.add(product.uniqid);\n results.push({ type: 'product', product });\n }\n\n if (options?.maxResults != null) {\n return results.slice(0, options.maxResults);\n }\n\n return results;\n}\n\nexport function searchMergedStorefrontCatalog(\n products: Product[],\n groups: ProductGroup[],\n query: string,\n options?: StorefrontSearchFilterOptions,\n): Product[] {\n const items = searchMergedStorefrontCatalogItems(products, groups, query, options);\n const matchedIds = new Set<string>();\n const results: Product[] = [];\n\n const addProduct = (product: Product) => {\n if (!product?.uniqid || matchedIds.has(product.uniqid)) return;\n if (options?.hideOutOfStock && !isProductInStock(product)) return;\n matchedIds.add(product.uniqid);\n results.push(product);\n };\n\n for (const item of items) {\n if (item.type === 'product') {\n addProduct(item.product);\n continue;\n }\n\n for (const product of item.products) {\n addProduct(product);\n }\n }\n\n if (options?.maxResults != null) {\n return results.slice(0, options.maxResults);\n }\n\n return results;\n}\n","import { DEFAULT_API_BASE_URL } from '../core/config';\n\nexport type StorefrontContactTicketInput = {\n shopSlug: string;\n email: string;\n message: string;\n title?: string;\n name?: string;\n invoiceId?: string;\n apiBaseUrl?: string;\n};\n\nexport type StorefrontContactTicketResult = {\n uniqid: string;\n};\n\nfunction isLocalDevHost(host: string): boolean {\n if (host === 'localhost' || host === '127.0.0.1' || host === '::1' || host.endsWith('.localhost')) {\n return true;\n }\n if (/^10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/.test(host)) {\n return true;\n }\n if (/^192\\.168\\.\\d{1,3}\\.\\d{1,3}$/.test(host)) {\n return true;\n }\n const private172 = host.match(/^172\\.(\\d{1,2})\\.\\d{1,3}\\.\\d{1,3}$/);\n if (private172) {\n const octet = Number(private172[1]);\n return octet >= 16 && octet <= 31;\n }\n return false;\n}\n\nexport function resolveStorefrontApiBaseUrl(options?: {\n apiBaseUrl?: string;\n hostname?: string;\n}): string {\n if (options?.apiBaseUrl?.trim()) {\n return options.apiBaseUrl.replace(/\\/+$/, '');\n }\n\n const hostname = options?.hostname\n ?? (typeof window !== 'undefined' ? window.location.hostname : '');\n\n if (hostname && !isLocalDevHost(hostname)) {\n return DEFAULT_API_BASE_URL;\n }\n\n // Edge/njk commerce is a classic IIFE (not an ES module) — import.meta is a syntax error there.\n // Storefront bootstrap sets window.apiBaseUrl; Vite/React callers may pass options.apiBaseUrl.\n if (typeof window !== 'undefined') {\n const bootstrapBase = (window as { apiBaseUrl?: unknown }).apiBaseUrl;\n if (typeof bootstrapBase === 'string' && bootstrapBase.trim()) {\n return bootstrapBase.replace(/\\/+$/, '');\n }\n }\n\n return 'http://localhost:3001'.replace(/\\/+$/, '');\n}\n\nexport function buildStorefrontContactMessage(input: {\n name?: string;\n message: string;\n maxLength?: number;\n}): string {\n const customerName = input.name?.trim() ?? '';\n const baseMessage = input.message.trim();\n const fullMessage = `${customerName ? `Name: ${customerName}\\n\\n` : ''}${baseMessage}`;\n const maxLength = input.maxLength ?? 2000;\n return fullMessage.slice(0, maxLength);\n}\n\nexport async function submitStorefrontContactTicket(\n input: StorefrontContactTicketInput,\n): Promise<StorefrontContactTicketResult> {\n const shopSlug = input.shopSlug.trim();\n if (!shopSlug) {\n throw new Error('Store data is not ready yet. Please try again in a moment.');\n }\n\n const normalizedEmail = input.email.trim().toLowerCase();\n const subject = input.title?.trim() ?? '';\n const title = subject.length >= 2 ? subject.slice(0, 30) : 'Contact Request';\n const message = buildStorefrontContactMessage({\n name: input.name,\n message: input.message,\n });\n const invoiceId = input.invoiceId?.trim() || undefined;\n const apiBaseUrl = resolveStorefrontApiBaseUrl({ apiBaseUrl: input.apiBaseUrl });\n\n const response = await fetch(\n `${apiBaseUrl}/v1/storefront/shops/name/${encodeURIComponent(shopSlug)}/tickets`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n },\n body: JSON.stringify({\n email: normalizedEmail,\n title,\n message,\n ...(invoiceId ? { invoice_id: invoiceId } : {}),\n }),\n },\n );\n\n const payload = await response.json().catch(() => null) as {\n message?: string;\n error?: string;\n data?: { uniqid?: string };\n } | null;\n\n if (!response.ok) {\n throw new Error(payload?.message || payload?.error || 'Failed to send your message.');\n }\n\n const uniqid = payload?.data?.uniqid;\n if (!uniqid) {\n throw new Error('Ticket created, but the response was incomplete.');\n }\n\n return { uniqid };\n}\n\nexport type StorefrontSocialLinks = {\n discord?: string | null;\n telegram?: string | null;\n};\n\nexport function resolveStorefrontSocialLinks(store: {\n discord_link?: string | null;\n telegram_link?: string | null;\n social?: Record<string, string | null | undefined> | null;\n} | null | undefined): StorefrontSocialLinks {\n return {\n discord: store?.discord_link ?? store?.social?.discord ?? null,\n telegram: store?.telegram_link ?? store?.social?.telegram ?? null,\n };\n}\n","const PARAM_PATTERN = /:([A-Za-z0-9_]+)/g;\n\nexport function buildEndpoint(\n template: string,\n params: Record<string, string | number | null | undefined>\n): string {\n return template.replace(PARAM_PATTERN, (_, key: string) => {\n const rawValue = params[key];\n if (rawValue === null || rawValue === undefined) {\n throw new Error(`Missing endpoint param: ${key}`);\n }\n\n const value = String(rawValue).trim();\n if (!value) {\n throw new Error(`Endpoint param \"${key}\" must not be empty`);\n }\n\n return encodeURIComponent(value);\n });\n}\n","/**\n * localStorage Wrapper\n *\n * Handles localStorage access with error handling for\n * environments where localStorage is not available.\n */\n\nconst STORAGE_PREFIX = 'shoppex_';\n\nfunction getKey(key: string): string {\n return `${STORAGE_PREFIX}${key}`;\n}\n\nexport function getItem<T>(key: string): T | null {\n try {\n const item = localStorage.getItem(getKey(key));\n if (!item) return null;\n return JSON.parse(item) as T;\n } catch {\n return null;\n }\n}\n\nexport function setItem<T>(key: string, value: T): void {\n try {\n localStorage.setItem(getKey(key), JSON.stringify(value));\n } catch {\n console.warn('[shoppex] Failed to save to localStorage');\n }\n}\n\nexport function removeItem(key: string): void {\n try {\n localStorage.removeItem(getKey(key));\n } catch {\n // Ignore errors\n }\n}\n","import { getConfig, getShopId, isInitialized } from './config';\nimport { buildEndpoint } from './endpoint';\nimport { getItem, setItem } from '../utils/storage';\n\nconst CONNECTION_ID_STORAGE_PREFIX = 'presence_connection_';\nconst CLIENT_ERROR_DEDUPE_WINDOW_MS = 15_000;\n\ntype VisibilityStateValue = 'hidden' | 'visible' | 'prerender' | 'unloaded';\ntype RequestMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';\n\nexport interface StorefrontClientErrorPayload {\n endpoint: string;\n method: RequestMethod;\n message: string;\n statusCode?: number;\n source?: 'sdk';\n phase?: 'request';\n attemptCount?: number;\n responseReceived?: boolean;\n pageUrl?: string;\n requestUrl?: string;\n online?: boolean;\n visibilityState?: VisibilityStateValue;\n}\n\nfunction createPresenceConnectionId(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n }\n return `spx_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;\n}\n\nexport function getStorefrontConnectionId(storeSlug: string): string | null {\n if (typeof window === 'undefined') return null;\n\n const storageKey = `${CONNECTION_ID_STORAGE_PREFIX}${storeSlug}`;\n const existing = getItem<string>(storageKey);\n if (existing && existing.trim()) {\n return existing;\n }\n\n const nextId = createPresenceConnectionId();\n setItem(storageKey, nextId);\n return nextId;\n}\n\nfunction getRecentClientErrorKey(payload: StorefrontClientErrorPayload): string {\n return [\n payload.method,\n payload.endpoint,\n payload.statusCode ?? 'none',\n payload.message.trim().toLowerCase(),\n payload.responseReceived ? 'response' : 'no-response',\n ].join('|');\n}\n\nfunction shouldSkipDuplicateClientError(payload: StorefrontClientErrorPayload): boolean {\n const dedupeKey = `client_error_${getRecentClientErrorKey(payload)}`;\n const now = Date.now();\n const lastSeenAt = getItem<number>(dedupeKey);\n if (typeof lastSeenAt === 'number' && now - lastSeenAt < CLIENT_ERROR_DEDUPE_WINDOW_MS) {\n return true;\n }\n\n setItem(dedupeKey, now);\n return false;\n}\n\nexport async function reportStorefrontClientError(payload: StorefrontClientErrorPayload): Promise<void> {\n if (!isInitialized()) return;\n if (typeof window === 'undefined') return;\n if (shouldSkipDuplicateClientError(payload)) return;\n\n const config = getConfig();\n const shopId = getShopId();\n const endpoint = shopId\n ? buildEndpoint('/v1/storefront/shops/id/:id/ping', { id: shopId })\n : buildEndpoint('/v1/storefront/shops/:storeSlug/ping', { storeSlug: config.storeSlug });\n const body = JSON.stringify({\n event_type: 'client_error',\n referer: document.referrer || undefined,\n connection_id: getStorefrontConnectionId(config.storeSlug) ?? undefined,\n client_error: {\n source: payload.source ?? 'sdk',\n phase: payload.phase ?? 'request',\n endpoint: payload.endpoint,\n method: payload.method,\n message: payload.message,\n status_code: payload.statusCode,\n attempt_count: payload.attemptCount,\n response_received: payload.responseReceived ?? false,\n page_url: payload.pageUrl ?? window.location.href,\n request_url: payload.requestUrl,\n online: payload.online ?? (typeof navigator !== 'undefined' ? navigator.onLine : undefined),\n visibility_state:\n payload.visibilityState ??\n (typeof document !== 'undefined'\n ? (document.visibilityState as VisibilityStateValue)\n : undefined),\n },\n });\n\n const targetUrl = `${config.apiBaseUrl}${endpoint}`;\n\n try {\n if (typeof navigator !== 'undefined' && typeof navigator.sendBeacon === 'function') {\n const beaconBody = new Blob([body], { type: 'application/json' });\n if (navigator.sendBeacon(targetUrl, beaconBody)) {\n return;\n }\n }\n\n await fetch(targetUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body,\n keepalive: true,\n });\n } catch {\n // Telemetry must never break storefront usage.\n }\n}\n","/**\n * HTTP Client for SDK\n *\n * IMPORTANT: No credentials! SDK runs on external domains,\n * and CORS with wildcard origin doesn't allow credentials.\n * All endpoints are public storefront endpoints.\n */\n\nimport type { ApiChallenge, ApiResponse, SDKResponse } from '../types';\nimport { getConfig, isInitialized } from './config';\nimport { ApiError, NetworkError, ShoppexError } from './errors';\nimport { getOrFetch, type CacheOptions } from './cache';\nimport { reportStorefrontClientError } from './telemetry';\n\nconst DEFAULT_TIMEOUT = 10000;\nconst MAX_RETRIES = 2;\n\ninterface RequestOptions {\n method?: 'GET' | 'POST' | 'PUT' | 'DELETE';\n body?: unknown;\n timeout?: number;\n retries?: number;\n baseUrl?: string;\n headers?: Record<string, string>;\n cache?: (CacheOptions & { key?: string }) | false;\n}\n\ninterface ParsedResponsePayload {\n data: unknown | null;\n rawText: string | null;\n}\n\ninterface FailureInfo {\n message: string;\n statusCode?: number;\n isTransport: boolean;\n responseReceived: boolean;\n responseDefinitive: boolean;\n challenge?: ApiChallenge;\n /** The server's `error_code`, when the failure was a named refusal. */\n code?: string;\n errorParams?: Record<string, unknown>;\n}\n\nasync function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport async function request<T>(\n endpoint: string,\n options: RequestOptions = {}\n): Promise<SDKResponse<T>> {\n const config = options.baseUrl ? null : getConfig();\n // The locale travels with EVERY request of an initialized SDK — a baseUrl\n // override (e.g. resolveStoreByDomain) must not silently drop it back to\n // Accept-Language negotiation (Codex P2).\n const localeConfig = config ?? (isInitialized() ? getConfig() : null);\n const {\n method = 'GET',\n body,\n timeout = DEFAULT_TIMEOUT,\n retries,\n baseUrl,\n headers: requestHeaders,\n cache,\n } = options;\n const retryCount =\n retries ?? (method === 'GET' ? MAX_RETRIES : 0);\n\n const apiBaseUrl = baseUrl ?? config?.apiBaseUrl ?? '';\n const url = `${apiBaseUrl}${endpoint}`;\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n ...requestHeaders,\n };\n // Explicit request locale (ADR-0055): without it the backend would fall\n // back to Accept-Language, detaching catalog content from the page locale.\n if (typeof localeConfig?.locale === 'string' && localeConfig.locale.trim()) {\n headers['x-shoppex-locale'] = localeConfig.locale.trim();\n }\n\n let lastFailure: FailureInfo | null = null;\n\n const executeRequest = async (): Promise<SDKResponse<T>> => {\n for (let attempt = 0; attempt <= retryCount; attempt++) {\n let responseReceived = false;\n let responseDefinitive = false;\n let responseChallenge: ApiChallenge | undefined;\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n const response = await fetch(url, {\n method,\n headers,\n body: body ? JSON.stringify(body) : undefined,\n signal: controller.signal,\n });\n responseReceived = true;\n\n clearTimeout(timeoutId);\n\n const payload = await parseResponsePayload(response);\n responseChallenge = readResponseChallenge(payload.data);\n\n if (!response.ok) {\n responseDefinitive = isDefinitiveHttpRefusal(payload.data)\n && response.status >= 400\n && response.status < 500\n && response.status !== 408;\n const fallbackHttpMessage = response.statusText\n ? `HTTP ${response.status}: ${response.statusText}`\n : `HTTP ${response.status}`;\n const message =\n (payload.data && typeof payload.data === 'object' && 'error' in payload.data && typeof payload.data.error === 'string'\n ? payload.data.error\n : null) ??\n (payload.data && typeof payload.data === 'object' && 'message' in payload.data && typeof payload.data.message === 'string'\n ? payload.data.message\n : null) ??\n payload.rawText ??\n fallbackHttpMessage;\n\n // A named server refusal keeps its name. Everything else stays a\n // NetworkError, exactly as before.\n const named = readErrorCodeFields(payload.data);\n if (named.code) {\n throw new ApiError(message, named.code, response.status, named.errorParams);\n }\n\n throw new NetworkError(message, response.status);\n }\n\n if (response.status === 204 && payload.data === null) {\n return {\n success: true,\n };\n }\n\n if (!payload.data || typeof payload.data !== 'object' || !('status' in payload.data)) {\n throw new NetworkError('Invalid API response', response.status);\n }\n\n const data = payload.data as ApiResponse<T>;\n const mapped = mapApiResponse(data);\n return mapped.success\n ? mapped\n : {\n ...mapped,\n responseReceived: true,\n responseDefinitive: data.status >= 400 && data.status < 500 && data.status !== 408,\n status: response.status,\n ...(responseChallenge ? { challenge: responseChallenge } : {}),\n };\n } catch (error) {\n let normalizedError = error instanceof Error ? error : new Error(String(error));\n\n if (error instanceof DOMException && error.name === 'AbortError') {\n normalizedError = new NetworkError('Request timeout', 408);\n }\n\n // Read from the base class, not NetworkError: a named ApiError also\n // carries the HTTP status, and losing it would misclassify a 400\n // refusal as a transport failure — retried and reported as an outage.\n const statusCode =\n normalizedError instanceof ShoppexError\n ? normalizedError.statusCode\n : undefined;\n\n lastFailure = {\n message: normalizedError.message,\n statusCode,\n isTransport: statusCode === undefined || statusCode === 408,\n responseReceived,\n responseDefinitive,\n ...(responseChallenge ? { challenge: responseChallenge } : {}),\n ...(normalizedError instanceof ApiError\n ? {\n code: normalizedError.code,\n ...(normalizedError.errorParams ? { errorParams: normalizedError.errorParams } : {}),\n }\n : {}),\n };\n\n // A named 4xx is the server's decision, not a transport hiccup:\n // `ApiError` only exists when the response carried an error code, and\n // a client-error status means the request itself was refused. Repeating\n // it verbatim cannot change the answer — it just multiplies the load\n // and delays the refusal the caller is waiting on by the full backoff\n // schedule. 408 stays retryable (it is a timeout wearing a 4xx) and\n // every 5xx, network failure and unnamed error retries exactly as\n // before.\n const isNamedClientRefusal =\n normalizedError instanceof ApiError\n && statusCode !== undefined\n && statusCode >= 400\n && statusCode < 500\n && statusCode !== 408;\n\n if (isNamedClientRefusal) {\n break;\n }\n\n if (attempt < retryCount) {\n await sleep(Math.pow(2, attempt) * 500);\n continue;\n }\n }\n }\n\n return {\n success: false,\n message: lastFailure?.message ?? 'Unknown error',\n ...(lastFailure ? { responseReceived: lastFailure.responseReceived } : {}),\n ...(lastFailure?.responseDefinitive ? { responseDefinitive: true } : {}),\n ...(lastFailure?.responseReceived && lastFailure.statusCode !== undefined\n ? { status: lastFailure.statusCode }\n : {}),\n ...(lastFailure?.challenge ? { challenge: lastFailure.challenge } : {}),\n ...(lastFailure?.code ? { code: lastFailure.code } : {}),\n ...(lastFailure?.errorParams ? { errorParams: lastFailure.errorParams } : {}),\n };\n };\n\n const result =\n method === 'GET' && cache && cache.ttl > 0\n ? await getOrFetch(\n cache.key ?? `GET:${url}`,\n executeRequest,\n { ttl: cache.ttl, staleWhileRevalidate: cache.staleWhileRevalidate },\n (value) => value.success\n )\n : await executeRequest();\n\n const failureForTelemetry = lastFailure as FailureInfo | null;\n\n if (!result.success && failureForTelemetry?.isTransport) {\n\n await reportStorefrontClientError({\n endpoint,\n method,\n message: result.message ?? failureForTelemetry.message,\n statusCode: failureForTelemetry.statusCode,\n attemptCount: retryCount + 1,\n requestUrl: url,\n responseReceived: failureForTelemetry.responseReceived,\n });\n }\n\n return result;\n}\n\nasync function parseResponsePayload(response: Response): Promise<ParsedResponsePayload> {\n const responseWithOptionalMethods = response as Response & {\n text?: () => Promise<string>;\n json?: () => Promise<unknown>;\n };\n\n // Runtime-safe fallback for test mocks that only implement `json()`.\n if (typeof responseWithOptionalMethods.text !== 'function') {\n if (typeof responseWithOptionalMethods.json === 'function') {\n try {\n return {\n data: await responseWithOptionalMethods.json(),\n rawText: null,\n };\n } catch {\n return { data: null, rawText: null };\n }\n }\n return { data: null, rawText: null };\n }\n\n try {\n const rawText = await responseWithOptionalMethods.text();\n if (!rawText) {\n return { data: null, rawText: null };\n }\n\n try {\n return {\n data: JSON.parse(rawText) as unknown,\n rawText: null,\n };\n } catch {\n const normalizedText = rawText.trim();\n return {\n data: null,\n rawText: normalizedText.length > 0 ? normalizedText : null,\n };\n }\n } catch {\n return { data: null, rawText: null };\n }\n}\n\nfunction readResponseChallenge(payload: unknown): ApiChallenge | undefined {\n if (!payload || typeof payload !== 'object') {\n return undefined;\n }\n const data = (payload as { data?: unknown }).data;\n if (!data || typeof data !== 'object') {\n return undefined;\n }\n const challenge = (data as { challenge?: unknown }).challenge;\n if (!challenge || typeof challenge !== 'object') {\n return undefined;\n }\n const provider = (challenge as { provider?: unknown }).provider;\n const siteKey = (challenge as { site_key?: unknown }).site_key;\n if (provider !== 'turnstile' || typeof siteKey !== 'string' || !siteKey.trim()) {\n return undefined;\n }\n return { provider, siteKey: siteKey.trim() };\n}\n\nfunction isDefinitiveHttpRefusal(payload: unknown): boolean {\n if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {\n return false;\n }\n\n const record = payload as Record<string, unknown>;\n return typeof record.status === 'number' && record.status >= 400 && record.status < 500;\n}\n\nfunction mapApiResponse<T>(apiResponse: ApiResponse<T>): SDKResponse<T> {\n if (apiResponse.status >= 200 && apiResponse.status < 300) {\n return {\n success: true,\n data: apiResponse.data,\n ...(apiResponse.message ? { message: apiResponse.message } : {}),\n };\n }\n\n return {\n success: false,\n message: apiResponse.error ?? apiResponse.message ?? `Request failed with status ${apiResponse.status}`,\n // The refusal the server actually made, kept machine-readable. Without it\n // a caller can only string-match a localized sentence, which breaks in\n // every locale but one.\n ...readErrorCodeFields(apiResponse),\n };\n}\n\n/**\n * Pull the localized-error envelope (`error_code` / `error_params`) off any\n * server payload shape. Returns an empty object when the payload carries none,\n * so the fields stay absent rather than becoming `undefined` keys.\n */\nfunction readErrorCodeFields(payload: unknown): { code?: string; errorParams?: Record<string, unknown> } {\n if (!payload || typeof payload !== 'object') {\n return {};\n }\n\n const record = payload as Record<string, unknown>;\n const code = typeof record.error_code === 'string' && record.error_code.length > 0\n ? record.error_code\n : null;\n if (!code) {\n return {};\n }\n\n const params = record.error_params;\n return {\n code,\n ...(params && typeof params === 'object' && !Array.isArray(params)\n ? { errorParams: params as Record<string, unknown> }\n : {}),\n };\n}\n\nexport async function get<T>(\n endpoint: string,\n options?: Omit<RequestOptions, 'method' | 'body'>\n): Promise<SDKResponse<T>> {\n return request<T>(endpoint, { ...options, method: 'GET' });\n}\n\nexport async function post<T>(\n endpoint: string,\n body?: unknown,\n options?: Omit<RequestOptions, 'method' | 'body'>\n): Promise<SDKResponse<T>> {\n return request<T>(endpoint, { ...options, method: 'POST', body });\n}\n","/**\n * Store Module\n *\n * API methods for store data.\n */\n\nimport { get } from '../core/client';\nimport { DEFAULT_API_BASE_URL, getConfig, isInitialized, setShopId } from '../core/config';\nimport { buildEndpoint } from '../core/endpoint';\nimport type {\n SDKResponse,\n Shop,\n Product,\n StorefrontData,\n ProductGroup,\n Category,\n StorefrontAddonBootstrap,\n CursorPagination,\n} from '../types';\n\ninterface StoreResponse {\n shop: Shop;\n products?: Product[];\n products_pagination?: CursorPagination | null;\n groups?: ProductGroup[];\n items?: StorefrontData['items'];\n categories?: Category[];\n addons?: StorefrontAddonBootstrap;\n}\n\ninterface StorefrontResponse {\n shop: Shop;\n}\n\nexport interface GetStorefrontOptions {\n productsLimit?: number;\n productsCursor?: string | null;\n}\n\nconst STORE_CACHE_TTL = 5 * 60 * 1000;\n\nexport async function getStore(): Promise<SDKResponse<Shop>> {\n const config = getConfig();\n const response = await get<StoreResponse>(\n buildEndpoint('/v1/storefront/shops/name/:storeSlug', {\n storeSlug: config.storeSlug,\n }),\n {\n cache: {\n key: `store:${config.storeSlug}`,\n ttl: STORE_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data) {\n // Cache the shopId for slug lookups\n if (response.data.shop?.id) {\n setShopId(response.data.shop.id);\n }\n return {\n success: true,\n data: response.data.shop,\n };\n }\n\n return {\n success: false,\n message: response.message,\n };\n}\n\nexport async function resolveStoreByDomain(\n domain?: string,\n apiBaseUrl?: string\n): Promise<SDKResponse<Shop>> {\n const resolvedDomain =\n domain ??\n (typeof window !== 'undefined' ? window.location.hostname : '');\n\n if (!resolvedDomain) {\n return {\n success: false,\n message: 'Domain is required to resolve store',\n };\n }\n\n const cleanDomain = resolvedDomain\n .replace(/^https?:\\/\\//, '')\n .split('/')[0]\n .trim();\n\n const baseUrl =\n apiBaseUrl ??\n (isInitialized() ? getConfig().apiBaseUrl : DEFAULT_API_BASE_URL);\n\n const response = await get<StorefrontResponse>(\n buildEndpoint('/v1/storefront/shops/domain/:domain', {\n domain: cleanDomain,\n }),\n {\n baseUrl,\n cache: {\n key: `store:domain:${cleanDomain}`,\n ttl: STORE_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data?.shop) {\n if (response.data.shop.id) {\n setShopId(response.data.shop.id);\n }\n return {\n success: true,\n data: response.data.shop,\n };\n }\n\n return {\n success: false,\n message: response.message ?? 'Failed to resolve store',\n };\n}\n\nexport async function getStorefront(options?: GetStorefrontOptions): Promise<SDKResponse<StorefrontData>> {\n const config = getConfig();\n const query = new URLSearchParams();\n if (Number.isFinite(options?.productsLimit)) {\n query.set('products_limit', String(Math.max(1, Math.floor(options?.productsLimit ?? 0))));\n }\n if (typeof options?.productsCursor === 'string' && options.productsCursor.trim().length > 0) {\n query.set('products_cursor', options.productsCursor);\n }\n const querySuffix = query.size > 0 ? `?${query.toString()}` : '';\n const response = await get<StoreResponse>(\n `${buildEndpoint('/v1/storefront/shops/name/:storeSlug', {\n storeSlug: config.storeSlug,\n })}${querySuffix}`,\n {\n cache: {\n key: `storefront:${config.storeSlug}:${options?.productsLimit ?? 'full'}:${options?.productsCursor ?? 'start'}`,\n ttl: STORE_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data) {\n // Cache the shopId for slug lookups\n if (response.data.shop?.id) {\n setShopId(response.data.shop.id);\n }\n return {\n success: true,\n data: {\n shop: response.data.shop,\n products: response.data.products ?? [],\n products_pagination: response.data.products_pagination ?? null,\n groups: response.data.groups ?? [],\n items: response.data.items ?? [],\n categories: response.data.categories ?? [],\n addons: response.data.addons ?? { items: [] },\n },\n };\n }\n\n return {\n success: false,\n message: response.message,\n };\n}\n\nexport async function getStoreLogoUrl(): Promise<string | null> {\n const response = await getStore();\n\n if (response.success && response.data?.logo) {\n return response.data.logo;\n }\n\n return null;\n}\n\nexport async function getStoreBannerUrl(): Promise<string | null> {\n const response = await getStore();\n\n if (response.success && response.data?.banner) {\n return response.data.banner;\n }\n\n return null;\n}\n","/**\n * Products Module\n *\n * API methods for product data.\n */\n\nimport { get } from '../core/client';\nimport { getConfig, getShopId } from '../core/config';\nimport { buildEndpoint } from '../core/endpoint';\nimport type {\n SDKResponse,\n Product,\n ProductCategory,\n ProductGroup,\n ProductVariant,\n PriceVariant,\n CursorPagination,\n} from '../types';\nimport { getStore } from './store';\nimport { getMergedStorefrontProducts } from '../utils/storefront-catalog';\n\ninterface ProductsResponse {\n products: Product[];\n groups?: ProductGroup[];\n pagination?: CursorPagination | null;\n}\n\ninterface ProductResponse {\n product: Product;\n}\n\nconst PRODUCTS_CACHE_TTL = 2 * 60 * 1000;\n\nexport interface GetStorefrontProductsPageOptions {\n cursor?: string | null;\n limit?: number;\n sort?: 'featured' | 'newest' | 'price-asc' | 'price-desc' | string | null;\n category?: string | null;\n hideOutOfStock?: boolean;\n}\n\nfunction getStorefrontProductsPageCategoryCacheKey(category: string | null | undefined): string {\n if (category === undefined) return 'category:unset';\n if (category === null) return 'category:null';\n return `category:${category}`;\n}\n\nfunction priceVariantToProductVariant(variant: PriceVariant & { stock?: number }): ProductVariant {\n return {\n id: variant.id,\n title: variant.title ?? variant.label ?? '',\n price: typeof variant.price === 'number' ? variant.price : Number(variant.price) || 0,\n stock: typeof variant.stock === 'number' ? variant.stock : undefined,\n // Dynamic Delivery (S8): carry the availability pair through. A supplier-backed\n // variant reports `stock: 0`, so dropping `orderable` here would make the mapped\n // variant look sold out. Left `undefined` when the source omits it, which keeps\n // the historical stock-only behaviour for payloads that predate the field.\n orderable: typeof variant.orderable === 'boolean' ? variant.orderable : undefined,\n supplier_backed:\n typeof variant.supplier_backed === 'boolean' ? variant.supplier_backed : undefined,\n quantity_min: variant.quantity_min,\n quantity_max: variant.quantity_max,\n quantityMin: variant.quantityMin,\n quantityMax: variant.quantityMax,\n image_id: variant.image_id,\n imageId: variant.imageId,\n cloudflare_image_id: variant.cloudflare_image_id,\n cloudflareImageId: variant.cloudflareImageId,\n image_url: variant.image_url,\n imageUrl: variant.imageUrl,\n };\n}\n\nfunction normalizeProduct(product: Product): Product {\n if (product.variants && product.variants.length > 0) {\n return product;\n }\n\n const priceVariants = product.price_variants;\n if (!Array.isArray(priceVariants) || priceVariants.length === 0) {\n return product;\n }\n\n return {\n ...product,\n variants: priceVariants.map((variant) =>\n priceVariantToProductVariant(variant as PriceVariant & { stock?: number })\n ),\n };\n}\n\nexport async function getProducts(): Promise<SDKResponse<Product[]>> {\n const config = getConfig();\n const response = await get<ProductsResponse>(\n buildEndpoint('/v1/storefront/products/public/:storeSlug', {\n storeSlug: config.storeSlug,\n }),\n {\n cache: {\n key: `products:${config.storeSlug}`,\n ttl: PRODUCTS_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data) {\n // The public route returns every public product exactly once in the flat `products` array —\n // group-bound products (e.g. variant-style DYNAMIC products) are included there too, so no\n // group merge is needed anymore. Groups only carry `product_uniqids` references into this\n // list. getMergedStorefrontProducts just dedupes by uniqid (first entry wins).\n return {\n success: true,\n data: getMergedStorefrontProducts(response.data.products.map(normalizeProduct)),\n };\n }\n\n return {\n success: false,\n message: response.message,\n data: [],\n };\n}\n\nexport async function getStorefrontProductsPage(\n options?: GetStorefrontProductsPageOptions,\n): Promise<SDKResponse<{ products: Product[]; pagination: CursorPagination | null }>> {\n const config = getConfig();\n const query = new URLSearchParams();\n if (typeof options?.cursor === 'string' && options.cursor.trim().length > 0) {\n query.set('cursor', options.cursor);\n }\n if (Number.isFinite(options?.limit)) {\n query.set('limit', String(Math.max(1, Math.floor(options?.limit ?? 0))));\n }\n if (typeof options?.sort === 'string' && options.sort.trim().length > 0) {\n query.set('sort', options.sort.trim());\n }\n if (typeof options?.category === 'string' && options.category.trim().length > 0) {\n query.set('category', options.category.trim());\n }\n if (options?.hideOutOfStock === true) {\n query.set('hide_out_of_stock', 'true');\n }\n const querySuffix = query.size > 0 ? `?${query.toString()}` : '';\n\n const response = await get<ProductsResponse>(\n `${buildEndpoint('/v1/storefront/products/shop/:storeSlug', {\n storeSlug: config.storeSlug,\n })}${querySuffix}`,\n {\n cache: {\n key: `products:page:${config.storeSlug}:${options?.limit ?? 'default'}:${options?.cursor ?? 'start'}:${options?.sort ?? 'featured'}:${getStorefrontProductsPageCategoryCacheKey(options?.category)}:${options?.hideOutOfStock === true ? 'in-stock' : 'all-stock'}`,\n ttl: PRODUCTS_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data) {\n return {\n success: true,\n data: {\n products: response.data.products.map(normalizeProduct),\n pagination: response.data.pagination ?? null,\n },\n };\n }\n\n return {\n success: false,\n message: response.message,\n };\n}\n\nexport async function getProduct(\n idOrSlug: string\n): Promise<SDKResponse<Product>> {\n // Slug lookups need the current shop id. Resolve it lazily so callers do not\n // have to remember to call getStore()/getStorefront() first.\n let shopId = getShopId();\n if (!shopId) {\n const store = await getStore();\n shopId = store.success ? (store.data?.id ?? null) : null;\n }\n\n const queryParams = shopId ? `?slug_shop_id=${encodeURIComponent(shopId)}` : '';\n\n const response = await get<ProductResponse>(\n `${buildEndpoint('/v1/storefront/products/unique/:idOrSlug', { idOrSlug })}${queryParams}`,\n {\n cache: {\n key: `product:${idOrSlug}:${shopId ?? 'no-shop'}`,\n ttl: PRODUCTS_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data?.product) {\n return {\n success: true,\n data: normalizeProduct(response.data.product),\n };\n }\n\n return {\n success: false,\n message: response.message,\n };\n}\n\nexport async function getCategories(): Promise<SDKResponse<string[]>> {\n const products = await getProducts();\n\n if (!products.success || !products.data) {\n return {\n success: false,\n message: products.message,\n };\n }\n\n const categories = new Set<string>();\n for (const product of products.data) {\n if (product.categories) {\n for (const category of product.categories) {\n if (typeof category === 'string') {\n categories.add(category);\n } else if (category && typeof category === 'object' && 'uniqid' in category) {\n categories.add((category as ProductCategory).uniqid);\n }\n }\n }\n }\n\n return {\n success: true,\n data: Array.from(categories),\n };\n}\n","import { getConfig, isInitialized } from '../core/config';\nimport { post } from '../core/client';\nimport type { AffiliateValidation, SDKResponse } from '../types';\n\nconst STORAGE_KEY = 'shoppex:affiliate_code:v1';\nconst SESSION_STORAGE_KEY = 'shoppex:affiliate_session:v1';\nconst DEFAULT_TTL_DAYS = 30;\n// 24 base-36 characters provide about 124 bits of entropy and stay within the API's 8-64 character limit.\nconst FALLBACK_SESSION_KEY_LENGTH = 24;\nconst SESSION_KEY_ALPHABET = 'abcdefghijklmnopqrstuvwxyz0123456789';\n\ntype StoredAffiliate = {\n code: string;\n expiresAt: number;\n};\n\nfunction nowMs() {\n return Date.now();\n}\n\nfunction ttlMs(days: number) {\n return Math.max(1, days) * 24 * 60 * 60 * 1000;\n}\n\nfunction normalizeAffiliateCode(code: string | null | undefined): string | null {\n const normalized = code?.trim().toLowerCase();\n return normalized ? normalized : null;\n}\n\nfunction safeRead(): StoredAffiliate | null {\n if (typeof window === 'undefined') return null;\n try {\n const raw = window.localStorage.getItem(STORAGE_KEY);\n if (!raw) return null;\n const parsed = JSON.parse(raw) as StoredAffiliate;\n if (!parsed || typeof parsed.code !== 'string' || typeof parsed.expiresAt !== 'number') return null;\n return parsed;\n } catch {\n return null;\n }\n}\n\nfunction safeWrite(value: StoredAffiliate) {\n if (typeof window === 'undefined') return;\n try {\n window.localStorage.setItem(STORAGE_KEY, JSON.stringify(value));\n } catch {\n // ignore\n }\n}\n\nexport function setAffiliateCode(code: string | null | undefined, ttlDays = DEFAULT_TTL_DAYS): string | null {\n const normalized = normalizeAffiliateCode(code);\n if (!normalized) {\n clearAffiliateCode();\n return null;\n }\n\n safeWrite({ code: normalized, expiresAt: nowMs() + ttlMs(ttlDays) });\n return normalized;\n}\n\nexport function clearAffiliateCode(): void {\n if (typeof window === 'undefined') return;\n try {\n window.localStorage.removeItem(STORAGE_KEY);\n } catch {\n // ignore\n }\n}\n\nexport function getAffiliateCode(): string | null {\n const stored = safeRead();\n if (!stored) return null;\n if (stored.expiresAt <= nowMs()) {\n clearAffiliateCode();\n return null;\n }\n return normalizeAffiliateCode(stored.code);\n}\n\nfunction createAffiliateSessionKey(): string {\n try {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n }\n } catch {\n // Fall through to the browser-safe random key.\n }\n\n let key = '';\n for (let index = 0; index < FALLBACK_SESSION_KEY_LENGTH; index += 1) {\n key += SESSION_KEY_ALPHABET[Math.floor(Math.random() * SESSION_KEY_ALPHABET.length)];\n }\n return key;\n}\n\n// Retained for the page's lifetime when sessionStorage is unavailable, so\n// repeated events in a storage-restricted browser still share one key and the\n// server-side session dedupe keeps working.\nlet inMemorySessionKey: string | null = null;\n\nfunction getAffiliateSessionKey(): string {\n try {\n const stored = window.sessionStorage.getItem(SESSION_STORAGE_KEY);\n if (stored && stored.length >= 8 && stored.length <= 64) {\n return stored;\n }\n } catch {\n // Read blocked entirely: the retained key is all we have.\n if (inMemorySessionKey) return inMemorySessionKey;\n }\n\n const key = createAffiliateSessionKey();\n try {\n window.sessionStorage.setItem(SESSION_STORAGE_KEY, key);\n // A write that silently no-ops (quota) must not hand out a fresh key per\n // event — verify it landed before trusting storage over the retained key.\n if (window.sessionStorage.getItem(SESSION_STORAGE_KEY) === key) {\n inMemorySessionKey = key;\n return key;\n }\n } catch {\n // Fall through to the retained key.\n }\n\n if (!inMemorySessionKey) inMemorySessionKey = key;\n return inMemorySessionKey;\n}\n\nexport async function trackAffiliateEvent(\n eventType: 'add_to_cart' | 'checkout_started',\n options?: {\n /**\n * The code the surrounding call actually resolved and submitted (e.g.\n * checkout()'s tri-state result). `null` means the caller explicitly\n * submitted WITHOUT a referral — no event is recorded, so an ambient\n * stored code is never credited for a sale it did not get. Omit the\n * options object entirely to attribute to the stored ambient code.\n */\n code: string | null;\n /**\n * Overrides the per-browser-session dedupe key. checkout entry points\n * pass `inv:<invoiceId>` so every created invoice counts as exactly one\n * checkout — a session-wide key would drop the second checkout of a\n * buyer who orders twice in one session while both sales still count.\n */\n dedupeKey?: string;\n }\n): Promise<void> {\n try {\n if (typeof window === 'undefined' || !isInitialized()) return;\n\n const code = options === undefined\n ? getAffiliateCode()\n : normalizeAffiliateCode(options.code);\n if (!code) return;\n\n const config = getConfig();\n // Raw fetch instead of the shared post helper: `keepalive` lets the\n // request survive the checkout redirect that immediately follows, which\n // would otherwise cancel it and undercount checkouts.\n await fetch(`${config.apiBaseUrl}/v1/storefront/affiliates/events`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n keepalive: true,\n body: JSON.stringify({\n shop_slug: config.storeSlug,\n code,\n event_type: eventType,\n // Dedupe key: per browser session by default (one add-to-cart per\n // session per link), or the caller's key — checkout passes one per\n // created invoice.\n session_key: options?.dedupeKey?.slice(0, 64) ?? getAffiliateSessionKey(),\n }),\n });\n } catch {\n // Funnel tracking must never break cart or checkout behavior.\n }\n}\n\nexport async function validateAffiliateCode(code: string): Promise<SDKResponse<AffiliateValidation>> {\n const normalizedCode = normalizeAffiliateCode(code);\n if (!normalizedCode) {\n return {\n success: false,\n data: {\n valid: false,\n affiliate_code: null,\n discount_active: false,\n discount_percent: 0,\n },\n message: 'Affiliate code is required',\n };\n }\n\n const config = getConfig();\n const response = await post<AffiliateValidation>(\n '/v1/storefront/affiliates/resolve',\n {\n shop_slug: config.storeSlug,\n code: normalizedCode,\n },\n { retries: 0 }\n );\n\n if (!response.success) {\n return response;\n }\n\n if (!response.data?.valid || !response.data.affiliate_code) {\n const programDisabled = response.data?.program_enabled === false;\n return {\n success: false,\n data: {\n valid: false,\n ...(response.data?.program_enabled !== undefined ? { program_enabled: response.data.program_enabled } : {}),\n affiliate_code: null,\n discount_active: false,\n discount_percent: 0,\n },\n message: response.message\n ?? (programDisabled ? 'Affiliate program is disabled for this shop.' : 'Invalid affiliate code.'),\n };\n }\n\n return {\n success: true,\n data: {\n valid: true,\n ...(response.data.program_enabled !== undefined ? { program_enabled: response.data.program_enabled } : {}),\n affiliate_code: normalizeAffiliateCode(response.data.affiliate_code),\n discount_active: Boolean(response.data.discount_active),\n discount_percent: Number(response.data.discount_percent ?? 0),\n },\n ...(response.message ? { message: response.message } : {}),\n };\n}\n\nexport async function applyAffiliateCode(code: string): Promise<SDKResponse<AffiliateValidation>> {\n const result = await validateAffiliateCode(code);\n if (result.success && result.data?.affiliate_code) {\n setAffiliateCode(result.data.affiliate_code);\n }\n\n return result;\n}\n\n/**\n * Capture an affiliate code from the current URL and store it for 30 days (last-click).\n *\n * Example:\n * - URL: https://mystore.com/product/abc?ref=deadbeef\n * - captureAffiliateFromUrl() stores \"deadbeef\" and returns it.\n */\nexport async function captureAffiliateFromUrl(param = 'ref'): Promise<string | null> {\n if (typeof window === 'undefined') return null;\n\n let code: string | null = null;\n try {\n const url = new URL(window.location.href);\n const raw = url.searchParams.get(param);\n code = raw ? raw.trim() : null;\n } catch {\n code = null;\n }\n\n code = normalizeAffiliateCode(code);\n if (!code) return null;\n\n // Store immediately so we don't lose it if attribution call fails.\n setAffiliateCode(code);\n\n // Optional: validate + normalize with backend. If invalid, clear it.\n if (isInitialized()) {\n try {\n const config = getConfig();\n const res = await post<{ accepted?: boolean; affiliate_code?: string | null }>(\n '/v1/storefront/affiliates/attribution',\n { shop_slug: config.storeSlug, code },\n { retries: 0 }\n );\n if (res.success && res.data?.accepted && res.data.affiliate_code) {\n setAffiliateCode(res.data.affiliate_code);\n return res.data.affiliate_code;\n }\n // Clear only on a definitive refusal (the server answered and said the\n // code is not attributable). A rate limit or transport failure must not\n // destroy a valid referral before checkout — from-cart validates later.\n if (res.success && res.data && res.data.accepted === false) {\n clearAffiliateCode();\n return null;\n }\n return code;\n } catch {\n // keep stored raw code, from-cart will validate later\n return code;\n }\n }\n\n return code;\n}\n","import type { CartAddon, CartItem } from '../types/cart';\n\nfunction hashString(value: string): string {\n let hash = 2166136261;\n for (let i = 0; i < value.length; i += 1) {\n hash ^= value.charCodeAt(i);\n hash += (hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24);\n }\n return (hash >>> 0).toString(16);\n}\n\nfunction normalizeAddons(addons: CartAddon[] | undefined): CartAddon[] {\n if (!addons?.length) return [];\n return [...addons]\n .map((addon) => ({ id: addon.id, quantity: addon.quantity ?? 1 }))\n .sort((a, b) => a.id.localeCompare(b.id));\n}\n\nfunction normalizeCustomFields(fields: Record<string, string> | undefined): Record<string, string> {\n if (!fields) return {};\n const entries = Object.entries(fields)\n .filter(([, value]) => typeof value === 'string')\n .sort(([a], [b]) => a.localeCompare(b));\n return Object.fromEntries(entries);\n}\n\nexport type CartLineIdentityInput = Pick<\n CartItem,\n 'product_id' | 'variant_id' | 'price_variant_id' | 'addons' | 'custom_fields' | 'price_data' | 'pay_what_you_want_price'\n>;\n\nexport function computeCartLineId(input: CartLineIdentityInput): string {\n const payload = {\n product_id: input.product_id,\n variant_id: input.variant_id,\n price_variant_id: input.price_variant_id ?? null,\n addons: normalizeAddons(input.addons),\n custom_fields: normalizeCustomFields(input.custom_fields),\n unit_price:\n typeof input.price_data?.unit_price === 'number' && Number.isFinite(input.price_data.unit_price)\n ? input.price_data.unit_price\n : null,\n pay_what_you_want_price:\n typeof input.pay_what_you_want_price === 'number' && Number.isFinite(input.pay_what_you_want_price)\n ? input.pay_what_you_want_price\n : null,\n };\n return hashString(JSON.stringify(payload));\n}\n\nexport function ensureCartLineId(item: CartItem): CartItem {\n if (typeof item.line_id === 'string' && item.line_id.trim()) {\n return item;\n }\n return { ...item, line_id: computeCartLineId(item) };\n}\n","export function normalizeRequestedCurrency(value: string | null | undefined): string | null {\n const normalized = value?.trim().toUpperCase();\n return normalized && /^[A-Z]{3}$/.test(normalized) ? normalized : null;\n}\n\nexport function getRequestedCurrencyFromLocation(): string | null {\n if (typeof window === 'undefined' || !window.location) {\n return null;\n }\n\n const search = typeof window.location.search === 'string' ? window.location.search : '';\n if (search) {\n return normalizeRequestedCurrency(new URLSearchParams(search).get('currency'));\n }\n\n const href = typeof window.location.href === 'string' ? window.location.href : '';\n if (!href) {\n return null;\n }\n\n try {\n return normalizeRequestedCurrency(\n new URL(href, 'https://storefront.shoppex.local').searchParams.get('currency'),\n );\n } catch {\n return null;\n }\n}\n","/**\n * Cart Module\n *\n * localStorage-based cart with support for Shoppex features:\n * - Addons (express shipping, gift wrap, etc.)\n * - Custom Fields (engraving, gift message, etc.)\n * - Price Variants (different pricing tiers)\n */\n\nimport { getItem, setItem, removeItem } from '../utils/storage';\nimport { getConfig } from '../core/config';\nimport { post } from '../core/client';\nimport { CartError } from '../core/errors';\nimport type {\n CartItem,\n CartAddOptions,\n CartItemUpdate,\n CartPayload,\n CartMetadata,\n CartStats,\n CartQuote,\n CartBasketMergeLine,\n CartCodeSource,\n} from '../types';\nimport { getAffiliateCode, trackAffiliateEvent } from './affiliates';\nimport { computeCartLineId, ensureCartLineId } from '../utils/cart-line-id';\nimport {\n getRequestedCurrencyFromLocation,\n normalizeRequestedCurrency,\n} from '../utils/requested-currency';\nimport { roundPayableAmount } from '@shoppex/contracts/catalog-unit-price';\n\nconst STORAGE_KEYS = {\n cart: 'cart',\n cartBackup: 'cart_backup',\n meta: 'cart_meta',\n metaBackup: 'cart_backup_meta',\n coupon: 'cart_coupon',\n couponBackup: 'cart_coupon_backup',\n} as const;\n\ntype StorageKeyType = keyof typeof STORAGE_KEYS;\n\nfunction getStorageKey(type: StorageKeyType): string {\n return `${STORAGE_KEYS[type]}_${getConfig().storeSlug}`;\n}\n\nfunction hashString(value: string): string {\n let hash = 2166136261;\n for (let i = 0; i < value.length; i += 1) {\n hash ^= value.charCodeAt(i);\n hash += (hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24);\n }\n return (hash >>> 0).toString(16);\n}\n\nfunction computeChecksum(cart: CartItem[]): string {\n return hashString(JSON.stringify(cart));\n}\n\nfunction normalizeQuantity(value: number): number {\n if (!Number.isFinite(value)) {\n throw new CartError('quantity must be a finite number');\n }\n return Math.floor(value);\n}\n\nfunction normalizeCouponCode(value: string | null | undefined): string | null {\n const normalized = value?.trim().toUpperCase();\n return normalized ? normalized : null;\n}\n\ntype StoredCartCode = {\n code: string;\n source: CartCodeSource;\n};\n\nfunction getStoredCartCode(): StoredCartCode | null {\n const raw = getItem<unknown>(getStorageKey('coupon'));\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {\n return null;\n }\n const record = raw as Record<string, unknown>;\n const code = typeof record.code === 'string' ? normalizeCouponCode(record.code) : null;\n const source = record.source === 'COUPON' || record.source === 'AFFILIATE'\n ? record.source\n : null;\n return code && source ? { code, source } : null;\n}\n\nfunction normalizeCartItems(value: unknown): CartItem[] {\n if (!Array.isArray(value)) return [];\n const normalized: CartItem[] = [];\n for (const entry of value) {\n if (!entry || typeof entry !== 'object') continue;\n const record = entry as Record<string, unknown>;\n const productId = typeof record.product_id === 'string' ? record.product_id.trim() : '';\n const variantId = typeof record.variant_id === 'string' ? record.variant_id.trim() : '';\n const quantity = Number(record.quantity);\n\n if (!productId || !variantId || !Number.isFinite(quantity) || quantity < 1) {\n continue;\n }\n\n const item: CartItem = {\n line_id: '',\n product_id: productId,\n variant_id: variantId,\n quantity: Math.floor(quantity),\n };\n\n if (typeof record.price_variant_id === 'string') {\n item.price_variant_id = record.price_variant_id;\n }\n if (record.price_data && typeof record.price_data === 'object') {\n const priceData = record.price_data as Record<string, unknown>;\n if (typeof priceData.unit_price === 'number' && Number.isFinite(priceData.unit_price)) {\n item.price_data = { unit_price: priceData.unit_price };\n }\n }\n if (typeof record.pay_what_you_want_price === 'number' && Number.isFinite(record.pay_what_you_want_price)) {\n item.pay_what_you_want_price = record.pay_what_you_want_price;\n }\n if (Array.isArray(record.addons)) {\n item.addons = record.addons as CartItem['addons'];\n }\n if (record.custom_fields && typeof record.custom_fields === 'object' && !Array.isArray(record.custom_fields)) {\n item.custom_fields = record.custom_fields as Record<string, string>;\n }\n\n // Preserve the optional display snapshot (title/variant_title/image_url/addon_labels) across the\n // localStorage round-trip so the njk cart drawer/page can render without a product fetch.\n if (typeof record.title === 'string') {\n item.title = record.title;\n }\n if (typeof record.variant_title === 'string') {\n item.variant_title = record.variant_title;\n }\n if (typeof record.image_url === 'string') {\n item.image_url = record.image_url;\n }\n if (Array.isArray(record.addon_labels)) {\n item.addon_labels = record.addon_labels.filter((label): label is string => typeof label === 'string');\n }\n if (typeof record.max_quantity === 'number' && Number.isFinite(record.max_quantity)) {\n item.max_quantity = record.max_quantity;\n }\n if (typeof record.min_quantity === 'number' && Number.isFinite(record.min_quantity)) {\n item.min_quantity = record.min_quantity;\n }\n\n // Self-heal on READ: clamp quantity to the stored [min,max] here, after the bounds are read. This is\n // the single chokepoint every access flows through (getCart -> getCartPayload -> serializeCart/\n // quoteCart -> checkout), so a stale/tampered/restored localStorage line can never reach checkout\n // out of bounds — closing restoreCartFromBackup and direct-localStorage-edit at the root, not just\n // the write paths.\n clampQuantityToBounds(item);\n\n const storedLineId = typeof record.line_id === 'string' ? record.line_id.trim() : '';\n item.line_id = storedLineId || computeCartLineId(item);\n\n normalized.push(ensureCartLineId(item));\n }\n return normalized;\n}\n\nfunction getCartMetadata(): CartMetadata | null {\n return getItem<CartMetadata>(getStorageKey('meta'));\n}\n\nexport function getCartCoupon(): string | null {\n return getStoredCartCode()?.code ?? null;\n}\n\nexport function getCartCouponSource(): CartCodeSource | null {\n return getStoredCartCode()?.source ?? null;\n}\n\nexport function setCartCoupon(\n coupon: string | null | undefined,\n source: CartCodeSource = 'COUPON',\n): string | null {\n const normalizedCoupon = normalizeCouponCode(coupon);\n if (!normalizedCoupon) {\n removeItem(getStorageKey('coupon'));\n return null;\n }\n\n setItem(getStorageKey('coupon'), { code: normalizedCoupon, source });\n return normalizedCoupon;\n}\n\nexport function clearCartCoupon(): void {\n removeItem(getStorageKey('coupon'));\n}\n\nfunction writeCart(cart: CartItem[]): void {\n const normalizedCart = normalizeCartItems(cart);\n setItem(getStorageKey('cart'), normalizedCart);\n const now = Date.now();\n const previous = getCartMetadata();\n const nextMeta: CartMetadata = {\n created_at: previous?.created_at ?? now,\n last_modified: now,\n version: (previous?.version ?? 0) + 1,\n checksum: computeChecksum(normalizedCart),\n };\n setItem(getStorageKey('meta'), nextMeta);\n\n if (normalizedCart.length === 0) {\n clearCartCoupon();\n }\n}\n\nfunction setCartWithMetadata(cart: CartItem[], metadata?: CartMetadata | null): void {\n const normalizedCart = normalizeCartItems(cart);\n setItem(getStorageKey('cart'), normalizedCart);\n const now = Date.now();\n const base = metadata ?? getCartMetadata();\n const nextMeta: CartMetadata = {\n created_at: base?.created_at ?? now,\n last_modified: now,\n version: base?.version ?? 1,\n checksum: computeChecksum(normalizedCart),\n };\n setItem(getStorageKey('meta'), nextMeta);\n}\n\nexport function getCart(): CartItem[] {\n const raw = getItem<unknown>(getStorageKey('cart'));\n return normalizeCartItems(raw);\n}\n\n/** Resolve a cart line_id for product+variant. When multiple configs exist, returns the first line. */\nexport function resolveCartLineId(\n productId: string,\n variantId: string,\n cart: CartItem[] = getCart(),\n): string {\n const matches = cart.filter(\n (item) => item.product_id === productId && item.variant_id === variantId,\n );\n if (matches.length === 0) {\n throw new CartError(`No cart line found for ${productId}/${variantId}`);\n }\n return matches[0].line_id;\n}\n\nexport function getCartItemCount(): number {\n const cart = getCart();\n return cart.reduce((sum, item) => sum + item.quantity, 0);\n}\n\nexport function addToCart(\n productId: string,\n variantId: string,\n quantity: number = 1,\n options?: CartAddOptions\n): void {\n if (!productId || !variantId) {\n throw new CartError('product_id and variant_id are required');\n }\n\n const normalizedQuantity = normalizeQuantity(quantity);\n if (normalizedQuantity < 1) {\n throw new CartError('quantity must be at least 1');\n }\n\n const cart = getCart();\n\n const lineId = computeCartLineId({\n product_id: productId,\n variant_id: variantId,\n addons: options?.addons,\n custom_fields: options?.custom_fields,\n price_variant_id: options?.price_variant_id,\n price_data: options?.price_data,\n pay_what_you_want_price: options?.pay_what_you_want_price,\n });\n\n const existingIndex = cart.findIndex((item) => item.line_id === lineId);\n const quantityBeforeAdd = existingIndex >= 0 ? cart[existingIndex].quantity : 0;\n\n if (existingIndex >= 0) {\n cart[existingIndex].quantity += normalizedQuantity;\n\n if (options?.addons) {\n cart[existingIndex].addons = options.addons;\n }\n if (options?.custom_fields) {\n cart[existingIndex].custom_fields = options.custom_fields;\n }\n if (options?.price_variant_id) {\n cart[existingIndex].price_variant_id = options.price_variant_id;\n }\n if (options?.price_data) {\n cart[existingIndex].price_data = options.price_data;\n }\n if (options?.pay_what_you_want_price !== undefined) {\n cart[existingIndex].pay_what_you_want_price = options.pay_what_you_want_price;\n }\n applyDisplaySnapshot(cart[existingIndex], options);\n clampQuantityToBounds(cart[existingIndex]);\n } else {\n const pushed: CartItem = {\n line_id: lineId,\n product_id: productId,\n variant_id: variantId,\n quantity: normalizedQuantity,\n addons: options?.addons,\n custom_fields: options?.custom_fields,\n price_variant_id: options?.price_variant_id,\n price_data: options?.price_data,\n pay_what_you_want_price: options?.pay_what_you_want_price,\n title: options?.title,\n variant_title: options?.variant_title,\n image_url: options?.image_url,\n addon_labels: options?.addon_labels,\n max_quantity: options?.max_quantity,\n min_quantity: options?.min_quantity,\n };\n clampQuantityToBounds(pushed);\n cart.push(pushed);\n }\n\n const intendedQuantity = (existingIndex >= 0 ? cart[existingIndex] : cart[cart.length - 1]).quantity;\n writeCart(cart);\n // The storage wrapper swallows quota/availability failures, and the cart\n // and metadata writes can fail independently, so the funnel event is gated\n // on the LINE itself: the post-clamp quantity actually grew (a clamped\n // max-quantity no-op did not add anything) AND that exact quantity is\n // readable back from storage (the write of the cart payload landed).\n const persistedLine = getCart().find((item) => item.line_id === lineId);\n if (intendedQuantity > quantityBeforeAdd && persistedLine?.quantity === intendedQuantity) {\n // Attribute like checkout() does: a code applied to the cart (AFFILIATE\n // coupon source) outranks the ambient stored referral.\n const cartAffiliateCode = getCartCouponSource() === 'AFFILIATE' ? getCartCoupon() : null;\n void trackAffiliateEvent('add_to_cart', cartAffiliateCode ? { code: cartAffiliateCode } : undefined);\n }\n}\n\n// Cart-wide invariant: a line's quantity must stay within its stored [min_quantity, max_quantity]\n// bounds. Every write path routes through this — addToCart (merge+push), setCartItem (merge+push),\n// updateCartItem, mergeBaskets (merge+push), moveBasketItem (merge+push) — AND, crucially, the READ\n// path normalizeCartItems (getCart) clamps too, so a stale/tampered/restored localStorage line is\n// self-healed before it can reach checkout. No entrypoint can persist or serve a quantity outside the\n// purchasable range the backend would reject.\n// Order matters: apply min FIRST, then max — so on the degenerate min>max case (e.g. quantity_min 2 but\n// only 1 in stock) MAX wins and the line is never pushed above the stock cap (over-stock is the harder\n// backend reject than under-min). Never below 1. No-op for the bound(s) that are absent.\nfunction clampQuantityToBounds(item: CartItem): void {\n const min = item.min_quantity;\n if (typeof min === 'number' && Number.isFinite(min) && item.quantity < min) {\n item.quantity = Math.floor(min);\n }\n const max = item.max_quantity;\n if (typeof max === 'number' && Number.isFinite(max) && item.quantity > max) {\n item.quantity = Math.floor(max);\n }\n if (item.quantity < 1) {\n item.quantity = 1;\n }\n}\n\n// Copy the optional display snapshot fields from add-options onto an existing line. Display-only —\n// kept separate from the pricing/identity fields so the snapshot logic is identical for add and set.\nfunction applyDisplaySnapshot(item: CartItem, options?: CartAddOptions): void {\n // Authoritative full re-snapshot (buy-box producer): replace ALL display fields verbatim, including\n // CLEARING ones the new snapshot omits — a removed add-on or a lifted cap must not leave stale data.\n if (options?.replace_display_snapshot) {\n item.title = options.title;\n item.variant_title = options.variant_title;\n item.image_url = options.image_url;\n item.addon_labels = options.addon_labels;\n item.max_quantity = options.max_quantity;\n item.min_quantity = options.min_quantity;\n return;\n }\n // Partial direct SDK call: only overwrite the fields actually provided.\n if (options?.title !== undefined) {\n item.title = options.title;\n }\n if (options?.variant_title !== undefined) {\n item.variant_title = options.variant_title;\n }\n if (options?.image_url !== undefined) {\n item.image_url = options.image_url;\n }\n if (options?.addon_labels !== undefined) {\n item.addon_labels = options.addon_labels;\n }\n if (options?.max_quantity !== undefined) {\n item.max_quantity = options.max_quantity;\n }\n if (options?.min_quantity !== undefined) {\n item.min_quantity = options.min_quantity;\n }\n}\n\nexport function setCartItem(\n productId: string,\n variantId: string,\n quantity: number = 1,\n options?: CartAddOptions\n): void {\n if (!productId || !variantId) {\n throw new CartError('product_id and variant_id are required');\n }\n\n const normalizedQuantity = normalizeQuantity(quantity);\n if (normalizedQuantity < 1) {\n throw new CartError('quantity must be at least 1');\n }\n\n const cart = getCart();\n const lineId = computeCartLineId({\n product_id: productId,\n variant_id: variantId,\n addons: options?.addons,\n custom_fields: options?.custom_fields,\n price_variant_id: options?.price_variant_id,\n price_data: options?.price_data,\n pay_what_you_want_price: options?.pay_what_you_want_price,\n });\n\n // Buy-now / replace semantics: one visible line per (product_id, variant_id). Drop any prior\n // line_ids for that pair so a config change (addons, price_data) does not leave a stale sibling.\n for (let index = cart.length - 1; index >= 0; index -= 1) {\n if (cart[index].product_id === productId && cart[index].variant_id === variantId) {\n cart.splice(index, 1);\n }\n }\n\n const pushed: CartItem = {\n line_id: lineId,\n product_id: productId,\n variant_id: variantId,\n quantity: normalizedQuantity,\n addons: options?.addons,\n custom_fields: options?.custom_fields,\n price_variant_id: options?.price_variant_id,\n price_data: options?.price_data,\n pay_what_you_want_price: options?.pay_what_you_want_price,\n title: options?.title,\n variant_title: options?.variant_title,\n image_url: options?.image_url,\n addon_labels: options?.addon_labels,\n max_quantity: options?.max_quantity,\n min_quantity: options?.min_quantity,\n };\n clampQuantityToBounds(pushed);\n cart.push(pushed);\n\n writeCart(cart);\n}\n\n/**\n * Patch one cart line.\n *\n * TRI-STATE BOUNDS: `min_quantity`/`max_quantity` accept `null` to DELETE the\n * stored bound — see {@link CartItemUpdate}. `undefined` (or an absent key)\n * leaves it alone, which is why a removed ceiling needs its own spelling.\n *\n * NO-OP UPDATES DO NOT WRITE. An update that leaves the cart byte-identical\n * returns without touching storage: no metadata bump, no `version` increment,\n * and — because the storage write is what other tabs observe — no `storage`\n * event. Writing anyway made an ineffective heal indistinguishable from a real\n * cart change, and two tabs healing the same line could hand the event back and\n * forth indefinitely. Line-shape healing of a legacy stored row is NOT this\n * function's job: `normalizeCartItems` clamps and repairs on every READ, which\n * is the chokepoint every access already flows through.\n */\nexport function updateCartItem(\n lineId: string,\n updates: CartItemUpdate\n): void {\n const cart = getCart();\n const normalizedLineId = lineId.trim();\n if (!normalizedLineId) {\n throw new CartError('line_id is required');\n }\n\n const index = cart.findIndex((item) => item.line_id === normalizedLineId);\n\n if (index < 0) {\n throw new CartError('Item not found in cart');\n }\n\n // The exact bytes the result is compared against, taken BEFORE any mutation.\n const before = JSON.stringify(cart);\n\n if (updates.quantity !== undefined) {\n const normalizedQuantity = normalizeQuantity(updates.quantity);\n if (normalizedQuantity < 1) {\n cart.splice(index, 1);\n writeCart(cart);\n return;\n }\n cart[index].quantity = normalizedQuantity;\n }\n\n if (updates.addons !== undefined) {\n cart[index].addons = updates.addons;\n }\n\n if (updates.custom_fields !== undefined) {\n cart[index].custom_fields = updates.custom_fields;\n }\n\n if (updates.price_variant_id !== undefined) {\n cart[index].price_variant_id = updates.price_variant_id;\n }\n if (updates.price_data !== undefined) {\n cart[index].price_data = updates.price_data;\n }\n if (updates.pay_what_you_want_price !== undefined) {\n cart[index].pay_what_you_want_price = updates.pay_what_you_want_price;\n }\n // Tri-state: `null` is the merchant's bound being REMOVED, and it has to\n // delete the stored key — a bound that can only be raised and lowered but\n // never cleared outlives the limit it describes.\n if (updates.max_quantity !== undefined) {\n if (updates.max_quantity === null) delete cart[index].max_quantity;\n else cart[index].max_quantity = updates.max_quantity;\n }\n if (updates.min_quantity !== undefined) {\n if (updates.min_quantity === null) delete cart[index].min_quantity;\n else cart[index].min_quantity = updates.min_quantity;\n }\n clampQuantityToBounds(cart[index]);\n\n // Pricing and configuration fields are part of a cart line's identity.\n // Recompute after every update and merge if the new identity already exists.\n const nextLineId = computeCartLineId(cart[index]);\n const duplicateIndex = cart.findIndex((item, itemIndex) => itemIndex !== index && item.line_id === nextLineId);\n if (duplicateIndex >= 0) {\n cart[duplicateIndex].quantity += cart[index].quantity;\n clampQuantityToBounds(cart[duplicateIndex]);\n cart.splice(index, 1);\n } else {\n cart[index].line_id = nextLineId;\n }\n\n // Nothing moved: writing would bump `version`/`last_modified` and emit a\n // storage event that says the cart changed when it did not.\n if (JSON.stringify(cart) === before) return;\n\n writeCart(cart);\n}\n\nexport function removeFromCart(lineId: string): void {\n const normalizedLineId = lineId.trim();\n if (!normalizedLineId) {\n throw new CartError('line_id is required');\n }\n\n const cart = getCart();\n const filtered = cart.filter((item) => item.line_id !== normalizedLineId);\n writeCart(filtered);\n}\n\n/**\n * Discards the cart entirely — and with it the proof that describes it.\n *\n * PAYMENT PATH. `latestQuoteToken` is evidence about a specific cart, and this\n * is the one mutation after which that cart does not exist in any form. Held\n * across the clear, the proof outlives its subject: a caller that clears and\n * re-adds (Buy Now REPLACES the cart) hands `/from-cart` a token bound to the\n * previous cart's hash, which is refused as `quote_token_stale` — a hand-off\n * dead-ended by a proof nobody asked for. And with no re-quote in between there\n * is nothing to replace it with, so the retry is refused identically.\n *\n * Only this path clears it. Every OTHER mutation turns one cart into another\n * cart, where a proof that no longer matches is the server's to refuse: it\n * answers `quote_token_stale`, the surfaces re-quote, and the buyer approves the\n * new total. Dropping the proof there instead would silently remove the approved\n * -total ceiling from a checkout that raced the re-quote, which is the failure\n * the token exists to prevent.\n */\nexport function clearCart(): void {\n removeItem(getStorageKey('cart'));\n removeItem(getStorageKey('meta'));\n clearCartCoupon();\n clearLatestQuoteToken();\n}\n\nexport function createCartBackup(): void {\n const cart = getCart();\n setItem(getStorageKey('cartBackup'), cart);\n const cartCode = getStoredCartCode();\n if (cartCode) {\n setItem(getStorageKey('couponBackup'), cartCode);\n } else {\n removeItem(getStorageKey('couponBackup'));\n }\n const metadata = getCartMetadata();\n if (metadata) {\n setItem(getStorageKey('metaBackup'), metadata);\n } else {\n const now = Date.now();\n setItem(getStorageKey('metaBackup'), {\n created_at: now,\n last_modified: now,\n version: 1,\n checksum: computeChecksum(cart),\n });\n }\n}\n\nexport function restoreCartFromBackup(): boolean {\n const backupRaw = getItem<unknown>(getStorageKey('cartBackup'));\n const backup = normalizeCartItems(backupRaw);\n const backupMeta = getItem<CartMetadata>(getStorageKey('metaBackup'));\n const backupCoupon = getItem<unknown>(getStorageKey('couponBackup'));\n\n if (backup && backup.length > 0) {\n setCartWithMetadata(backup, backupMeta);\n if (backupCoupon && typeof backupCoupon === 'object' && !Array.isArray(backupCoupon)) {\n const record = backupCoupon as Record<string, unknown>;\n const source = record.source === 'COUPON' || record.source === 'AFFILIATE'\n ? record.source\n : null;\n if (typeof record.code === 'string' && source) {\n setCartCoupon(record.code, source);\n } else {\n clearCartCoupon();\n }\n } else {\n clearCartCoupon();\n }\n return true;\n }\n\n return false;\n}\n\nexport function mergeBaskets(items: CartBasketMergeLine[]): CartItem[] {\n const cart = getCart();\n\n for (const incoming of items) {\n const productId = typeof incoming.product_id === 'string' ? incoming.product_id.trim() : '';\n const variantId = typeof incoming.variant_id === 'string' ? incoming.variant_id.trim() : '';\n if (!productId || !variantId) {\n continue;\n }\n\n let normalizedQuantity: number;\n try {\n normalizedQuantity = normalizeQuantity(incoming.quantity);\n } catch {\n continue;\n }\n\n if (normalizedQuantity < 1) {\n continue;\n }\n\n const mergedLine = ensureCartLineId({\n ...incoming,\n line_id: incoming.line_id ?? computeCartLineId(incoming),\n product_id: productId,\n variant_id: variantId,\n quantity: normalizedQuantity,\n });\n const index = cart.findIndex((item) => item.line_id === mergedLine.line_id);\n\n if (index >= 0) {\n cart[index].quantity = Math.max(cart[index].quantity, normalizedQuantity);\n clampQuantityToBounds(cart[index]);\n } else {\n clampQuantityToBounds(mergedLine);\n cart.push(mergedLine);\n }\n }\n\n writeCart(cart);\n return cart;\n}\n\nexport function moveBasketItem(\n fromProductId: string,\n fromVariantId: string,\n toProductId: string,\n toVariantId: string\n): void {\n const cart = getCart();\n const fromIndex = cart.findIndex(\n (item) => item.product_id === fromProductId && item.variant_id === fromVariantId\n );\n\n if (fromIndex < 0) {\n throw new CartError('Item not found in cart');\n }\n\n const [fromItem] = cart.splice(fromIndex, 1);\n const toLineId = computeCartLineId({\n ...fromItem,\n product_id: toProductId,\n variant_id: toVariantId,\n });\n const toIndex = cart.findIndex((item) => item.line_id === toLineId);\n\n if (toIndex >= 0) {\n cart[toIndex].quantity += fromItem.quantity;\n clampQuantityToBounds(cart[toIndex]);\n } else {\n const moved = ensureCartLineId({\n ...fromItem,\n product_id: toProductId,\n variant_id: toVariantId,\n line_id: toLineId,\n });\n clampQuantityToBounds(moved);\n cart.push(moved);\n }\n\n writeCart(cart);\n}\n\nexport function validateCartIntegrity(): boolean {\n const cart = getCart();\n const metadata = getCartMetadata();\n const checksum = computeChecksum(cart);\n\n if (!metadata) {\n setCartWithMetadata(cart, null);\n return true;\n }\n\n return metadata.checksum === checksum;\n}\n\nexport function getCartStats(): CartStats {\n const cart = getCart();\n const integrityValid = validateCartIntegrity();\n const metadata = getCartMetadata();\n const backup = getItem<CartItem[]>(getStorageKey('cartBackup')) ?? [];\n const hasCompletePriceSnapshots =\n cart.length > 0 &&\n cart.every((item) => typeof item.price_data?.unit_price === 'number');\n const totalPrice = cart.reduce((sum, item) => {\n const unitPrice = item.price_data?.unit_price ?? 0;\n return sum + roundPayableAmount(unitPrice * item.quantity);\n }, 0);\n\n return {\n item_count: cart.length,\n total_quantity: cart.reduce((sum, item) => sum + item.quantity, 0),\n last_modified: metadata?.last_modified ?? 0,\n version: metadata?.version ?? 0,\n has_backup: backup.length > 0,\n integrity_valid: integrityValid,\n total_price: roundPayableAmount(totalPrice),\n total_price_is_estimate: cart.length > 0 && !hasCompletePriceSnapshots,\n };\n}\n\nexport function getCartPayload(coupon?: string): CartPayload {\n const config = getConfig();\n const normalizedCoupon = normalizeCouponCode(coupon) ?? getCartCoupon() ?? undefined;\n return {\n store_slug: config.storeSlug,\n items: getCart(),\n coupon: normalizedCoupon,\n };\n}\n\n/**\n * The ambient referral code checkout() will submit as `affiliate_code`.\n *\n * Read exactly like checkout()'s normalizeAffiliateCode ambient branch: the\n * referral code the cart itself carries (source `AFFILIATE`) takes precedence\n * over the stored `?ref=` attribution. Sending it with the quote is what makes\n * the displayed total equal the amount the invoice will charge — without it a\n * cart holding both a coupon and a `?ref=` attribution quotes high.\n */\nfunction getAmbientAffiliateCodeForQuote(): string | null {\n const storedCode = getCartCoupon();\n const storedSource = getCartCouponSource();\n if (storedSource === 'AFFILIATE' && storedCode) {\n return storedCode.trim().toLowerCase();\n }\n return getAffiliateCode();\n}\n\n/**\n * The proof from the most recent successful quote, held in memory only.\n *\n * Module-scoped rather than persisted: the token is evidence about a cart as\n * it was priced moments ago, and a stale one from a previous page load is\n * simply ignored by the server. Not exported as public API — `checkout()`\n * reads it, callers do not have to know it exists.\n */\nlet latestQuoteToken: string | null = null;\n\n/**\n * Which quote call the held token belongs to.\n *\n * Quote responses settle in ARRIVAL order, not request order: two overlapping\n * `quoteCart` calls (cart A, then cart A+B) can answer with the OLDER one last,\n * and the token stored is then evidence about a cart the buyer no longer has.\n *\n * That is not a mispricing — `/from-cart` binds the token to a hash of the cart\n * content, currency, shop and submitted codes (`isCartQuoteTokenApplicable`),\n * so a superseded token simply fails to apply and is treated as ABSENT, and the\n * proof is a one-directional CEILING that can never lower a price. What it\n * costs is the ceiling itself: the buyer silently loses the protection for the\n * rest of that checkout. Keeping the newest call's answer is what keeps the\n * proof present for the cart actually on screen.\n */\nlet quoteSequence = 0;\n\n/** @internal — read by checkout(); exported only across module boundaries. */\nexport function getLatestQuoteToken(): string | null {\n return latestQuoteToken;\n}\n\n/** @internal — test seam and cart-reset hook. */\nexport function clearLatestQuoteToken(): void {\n latestQuoteToken = null;\n // A quote already in flight must not resurrect the proof this cleared.\n quoteSequence += 1;\n}\n\nexport async function quoteCart(coupon?: string, currency?: string) {\n const sequence = (quoteSequence += 1);\n const payload = getCartPayload(coupon);\n const normalizedCurrency = normalizeRequestedCurrency(currency)\n ?? getRequestedCurrencyFromLocation()\n ?? normalizeRequestedCurrency(getConfig().currency);\n const response = await post<CartQuote>('/v1/storefront/cart/quote', {\n shop_slug: payload.store_slug,\n cart: payload.items,\n coupon: payload.coupon,\n affiliate_code: getAmbientAffiliateCodeForQuote() ?? undefined,\n currency: normalizedCurrency ?? undefined,\n });\n\n // Only a successful quote replaces the held proof — a failed quote must not\n // clear a still-valid one.\n //\n // A SUCCESSFUL quote that carries no token clears it, rather than leaving the\n // previous one in place. The proof is evidence about one specific priced\n // cart, and `/from-cart` refuses a submitted proof it cannot apply\n // (`quote_token_stale` / `_invalid`) instead of ignoring it. So a held token\n // that this quote did not reissue is not a harmless leftover: every later\n // `checkout()` submits it, is refused, and re-quoting never helps because a\n // tokenless answer used to leave it untouched — a dead end the buyer cannot\n // escape from inside the cart.\n //\n // And only the NEWEST call may replace it: a slower earlier quote answering\n // last would otherwise overwrite the current cart's proof with one bound to a\n // cart hash that no longer exists.\n if (sequence !== quoteSequence) return response;\n if (response.success) {\n latestQuoteToken = typeof response.data?.quote_token === 'string'\n ? response.data.quote_token\n : null;\n }\n\n return response;\n}\n\nexport function serializeCart(coupon?: string): string {\n const payload = getCartPayload(coupon);\n const json = JSON.stringify(payload);\n // UTF-8 safe Base64: encodeURIComponent converts to UTF-8, unescape converts percent-encoding to bytes\n if (typeof btoa !== 'undefined') {\n return btoa(unescape(encodeURIComponent(json)));\n }\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(json, 'utf8').toString('base64');\n }\n throw new CartError('Base64 encoding is not available in this environment');\n}\n","/**\n * Checkout Module\n *\n * Creates invoice via backend API and redirects to hosted checkout page.\n * All checkout flows go through: checkout.shoppex.io/invoice/{invoiceId}\n */\n\nimport { getConfig } from '../core/config';\nimport { post } from '../core/client';\nimport { getCart, getCartCoupon, getCartCouponSource, createCartBackup, clearCart, getLatestQuoteToken } from './cart';\nimport { getAffiliateCode, trackAffiliateEvent } from './affiliates';\nimport type { CartItem, CartAddon } from '../types/cart';\nimport type { ApiChallenge, BuyerRewards } from '../types/api';\nimport {\n findRemainingProductRedirectPlaceholders,\n isSafeHttpsRedirectTemplateUrl,\n} from '@shoppex/contracts/redirect-link-template';\nimport {\n getRequestedCurrencyFromLocation,\n normalizeRequestedCurrency,\n} from '../utils/requested-currency';\n\nexport interface CheckoutOptions {\n autoRedirect?: boolean;\n locale?: string;\n email?: string;\n coupon?: string;\n currency?: string;\n /**\n * Absolute HTTPS URL used after a completed purchase when the product does\n * not define its own redirect. This is persisted on the invoice, so each\n * sales channel can provide its own return destination.\n */\n redirectUrl?: string;\n /**\n * A Cloudflare Turnstile proof for the `storefront_checkout` action.\n *\n * Normally omitted. When checkout returns a challenge, mount the hosted\n * broker with `mountCheckoutChallenge()` and retry with its renewed proof.\n * The proof is transport-only and does not change the checkout intent or its\n * idempotency key.\n */\n turnstileToken?: string;\n /**\n * Referral (affiliate) code to submit, as a tri-state:\n *\n * - `undefined` — the SDK resolves it from storage (cart-applied referral\n * code first, then the ambient `?ref=` attribution).\n * - `''` — explicitly none: submit no referral code and do NOT re-read\n * storage. This is how a caller pins \"quoted WITHOUT a referral\"; without\n * it a code captured between the quote and the submit would be applied to\n * a total the buyer never saw.\n * - non-empty — pinned: submit exactly this code.\n *\n * `referralCode` is an alias and follows the same rules; `affiliateCode`\n * wins when both are present.\n */\n affiliateCode?: string;\n /** Alias of {@link CheckoutOptions.affiliateCode}, same tri-state. */\n referralCode?: string;\n customerCheckoutPath?: '/dashboard/api/checkout';\n /**\n * The cart this hand-off was approved FOR, as `JSON.stringify(getCart())`.\n *\n * PAYMENT PATH. A caller that writes the cart and reads it back before\n * checking out (Buy Now, which replaces the cart, is the sharp case) verifies\n * a cart it read at one moment, while these functions read storage again on\n * their way into the request — and localStorage is shared with every other\n * tab on the domain. A write landing in that gap is billed without ever\n * having passed the caller's verification.\n *\n * The caller cannot close that itself: any check it makes is one more read\n * BEFORE this one. Pinning the expected bytes moves the comparison to the\n * only place it can be conclusive — against the exact cart the call is about\n * to POST. A mismatch refuses before anything is created or sent.\n *\n * Honoured identically by BOTH invoice-creating entry points, `checkout()`\n * and `buildCheckoutUrl()` — they hit the same endpoint and create the same\n * invoice, so a pin that held on one and not the other would be a promise\n * the caller could not rely on. Only the refusal shape differs, following\n * each function's own success shape: `checkout()` returns\n * `{ success: false }`, `buildCheckoutUrl()` throws.\n *\n * Optional and additive: omitted, nothing changes, and the server is not\n * involved either way.\n */\n expectedCart?: string;\n}\n\nexport interface CheckoutResult {\n success: boolean;\n redirectUrl?: string;\n invoiceId?: string;\n rewards?: BuyerRewards | null;\n message?: string;\n /**\n * The server's machine-readable refusal identifier when the checkout was\n * refused, e.g. `errors.checkout.price_increased_since_quote` or\n * `errors.checkout.affiliate_code_not_applicable`. Branch on this rather\n * than on `message`, which is localized display copy.\n *\n * The quote-proof family — `errors.checkout.quote_token_invalid`,\n * `errors.checkout.quote_token_expired`, `errors.checkout.quote_token_stale`\n * — says the proof this call submitted could not be honoured: not ours, past\n * its window, or priced for a cart/currency/codes that have since moved. The\n * server refuses rather than pricing without the ceiling, so the caller's\n * response is always the same: `quoteCart()` again, show the buyer the new\n * total, and only then retry. A retry with the same stale token is refused\n * identically.\n *\n * Absent for failures the server never named (transport, timeout, an empty\n * cart caught client-side).\n */\n code?: string;\n /**\n * Human-verification challenge required before creating the invoice. Mount\n * it with `mountCheckoutChallenge()`, then retry with its proof as\n * `turnstileToken`.\n */\n challenge?: ApiChallenge;\n}\n\n/**\n * Typed refusal from {@link buildCheckoutUrl}. The function keeps its existing\n * throw-based contract while exposing a server-requested human-verification\n * challenge so callers can render it and retry with `turnstileToken`.\n */\nexport class CheckoutCreateError extends Error {\n readonly challenge?: ApiChallenge;\n readonly code?: string;\n readonly status?: number;\n\n constructor(message: string, options: {\n challenge?: ApiChallenge;\n code?: string;\n status?: number;\n } = {}) {\n super(message);\n this.name = 'CheckoutCreateError';\n this.challenge = options.challenge;\n this.code = options.code;\n this.status = options.status;\n Object.setPrototypeOf(this, CheckoutCreateError.prototype);\n }\n}\n\ninterface CheckoutApiResponse {\n invoiceId?: string;\n checkoutUrl?: string;\n invoice_id?: string;\n checkout_url?: string;\n uniqid?: string;\n url?: string;\n url_branded?: string;\n rewards?: BuyerRewards | null;\n invoice?: {\n invoiceId?: string;\n checkoutUrl?: string;\n invoice_id?: string;\n checkout_url?: string;\n uniqid?: string;\n url?: string;\n url_branded?: string;\n rewards?: BuyerRewards | null;\n };\n}\n\ninterface NormalizedCheckoutData {\n invoiceId: string;\n checkoutUrl: string;\n rewards: BuyerRewards | null;\n}\n\nconst CHECKOUT_PREFILL_EMAIL_HASH_KEY = 'shoppex_prefill_email';\n\n/**\n * PAYMENT PATH. The single refusal copy for a broken `expectedCart` pin, shared\n * by every entry point that honours the pin so the buyer reads the same\n * sentence whichever one the theme calls. One literal, because two copies drift\n * and the difference would be visible to buyers on the same storefront.\n */\nconst CART_CHANGED_MESSAGE = 'Your cart changed while checkout was starting. Please review it and try again.';\n\n/**\n * PAYMENT PATH. True when the caller pinned a cart and storage no longer holds\n * it — see `CheckoutOptions.expectedCart`. Compared against the exact array the\n * caller is about to bill, which is the only comparison that is conclusive:\n * anything the caller checks itself is one more read BEFORE the read that\n * feeds the request.\n *\n * An omitted pin is not a mismatch. The pin is additive, and a caller that\n * never made the promise is left exactly as it was.\n */\nfunction isExpectedCartMismatch(cart: CartItem[], expectedCart: string | undefined): boolean {\n return expectedCart !== undefined && JSON.stringify(cart) !== expectedCart;\n}\n\nfunction normalizeCoupon(coupon: string | null | undefined): string | null {\n const normalized = coupon?.trim();\n return normalized ? normalized : null;\n}\n\nfunction normalizeEmail(email: string | null | undefined): string | null {\n const normalized = email?.trim();\n return normalized ? normalized : null;\n}\n\nfunction resolvePostPurchaseRedirectUrl(\n redirectUrl: string | null | undefined,\n): { value: string | null; error: null } | { value: null; error: string } {\n const normalized = redirectUrl?.trim();\n if (!normalized) {\n return { value: null, error: null };\n }\n if (!isSafeHttpsRedirectTemplateUrl(normalized)) {\n return { value: null, error: 'redirectUrl must be an absolute HTTPS URL.' };\n }\n if (findRemainingProductRedirectPlaceholders(normalized).length > 0) {\n return { value: null, error: 'redirectUrl must not contain template placeholders.' };\n }\n return { value: normalized, error: null };\n}\n\ninterface PendingCheckoutCreate {\n fingerprint: string;\n key: string;\n}\n\nconst pendingCheckoutCreates = new Map<string, PendingCheckoutCreate>();\n\nfunction acquireCheckoutCreateIdempotency(\n requestTarget: { endpoint: string; baseUrl?: string },\n createIntent: object,\n): PendingCheckoutCreate {\n const fingerprint = JSON.stringify({\n endpoint: requestTarget.endpoint,\n baseUrl: requestTarget.baseUrl ?? null,\n createIntent,\n });\n const existingAttempt = pendingCheckoutCreates.get(fingerprint);\n if (existingAttempt) {\n return existingAttempt;\n }\n\n const attempt = {\n fingerprint,\n key: globalThis.crypto.randomUUID(),\n };\n pendingCheckoutCreates.set(fingerprint, attempt);\n return attempt;\n}\n\nfunction releaseCheckoutCreateIdempotency(\n attempt: PendingCheckoutCreate,\n outcomeDefinitive: boolean,\n): void {\n // Only a parsed server refusal or a validated success makes the outcome\n // definitive. A rejected fetch, timeout, truncated body, or malformed body\n // may follow a committed create, so the next identical intent replays it.\n if (outcomeDefinitive && pendingCheckoutCreates.get(attempt.fingerprint) === attempt) {\n pendingCheckoutCreates.delete(attempt.fingerprint);\n }\n}\n\nfunction resolveCustomerCheckoutRequestTarget(options: CheckoutOptions): {\n endpoint: string;\n baseUrl?: string;\n} {\n if (\n options.customerCheckoutPath === '/dashboard/api/checkout'\n && typeof window !== 'undefined'\n && typeof window.location?.origin === 'string'\n ) {\n return {\n endpoint: options.customerCheckoutPath,\n baseUrl: window.location.origin,\n };\n }\n\n return { endpoint: '/v1/storefront/invoices/from-cart' };\n}\n\nfunction resolveRequestedCheckoutCurrency(options: CheckoutOptions): string | null {\n return normalizeRequestedCurrency(options.currency)\n ?? getRequestedCurrencyFromLocation()\n ?? normalizeRequestedCurrency(getConfig().currency);\n}\n\nfunction normalizeCheckoutFailureMessage(rawMessage: string | null | undefined): string {\n const message = rawMessage?.trim() ?? '';\n if (!message) {\n return 'Checkout failed. Please try again.';\n }\n\n if (isStaleCartProductError(message)) {\n return 'Your cart is outdated. Please add the products again.';\n }\n\n const httpMatch = message.match(/^HTTP\\s+(\\d{3})(?::\\s*(.*))?$/i);\n if (httpMatch) {\n const status = Number(httpMatch[1]);\n const detail = httpMatch[2]?.trim();\n\n if (detail && detail.length > 0) {\n return `Checkout failed: ${detail}`;\n }\n\n if (status >= 500) {\n return 'Checkout is temporarily unavailable. Please try again.';\n }\n\n if (status === 400) {\n return 'Checkout failed. Please check your details and try again.';\n }\n\n if (status === 401 || status === 403) {\n return 'Checkout is currently unavailable for this request.';\n }\n\n return 'Checkout failed. Please try again.';\n }\n\n if (/^internal server error$/i.test(message)) {\n return 'Checkout is temporarily unavailable. Please try again.';\n }\n\n return message;\n}\n\nfunction isStaleCartProductError(rawMessage: string | null | undefined): boolean {\n const message = rawMessage?.trim().toLowerCase() ?? '';\n if (!message) {\n return false;\n }\n\n return message.includes('product not found')\n || message.includes('product not available')\n || message.includes('products are no longer available')\n || message.includes('outdated product');\n}\n\nfunction validateCheckoutUrl(\n checkoutUrl: string,\n checkoutBaseUrl: string | undefined,\n expectedInvoiceId?: string\n): string | null {\n const expectedBaseUrl = checkoutBaseUrl?.trim();\n if (!expectedBaseUrl) {\n return null;\n }\n\n try {\n const parsedCheckoutUrl = new URL(checkoutUrl);\n const parsedExpectedBaseUrl = new URL(expectedBaseUrl);\n\n if (parsedCheckoutUrl.origin !== parsedExpectedBaseUrl.origin) {\n return null;\n }\n\n const normalizedPath = parsedCheckoutUrl.pathname.replace(/\\/+$/, '');\n const normalizedBasePath = parsedExpectedBaseUrl.pathname.replace(/\\/+$/, '');\n const expectedInvoicePath = `${normalizedBasePath}/invoice/`.replace(/\\/{2,}/g, '/');\n if (!normalizedPath.startsWith(expectedInvoicePath)) {\n return null;\n }\n\n const invoiceIdSegment = normalizedPath.slice(expectedInvoicePath.length);\n if (!invoiceIdSegment || invoiceIdSegment.includes('/')) {\n return null;\n }\n\n if (expectedInvoiceId) {\n const normalizedExpectedInvoiceId = expectedInvoiceId.trim();\n const invoiceIdFromUrl = decodeURIComponent(invoiceIdSegment);\n if (!normalizedExpectedInvoiceId || invoiceIdFromUrl !== normalizedExpectedInvoiceId) {\n return null;\n }\n }\n\n return parsedCheckoutUrl.toString();\n } catch {\n return null;\n }\n}\n\nfunction buildCheckoutUrlFromInvoiceId(\n checkoutBaseUrl: string | undefined,\n invoiceId: string\n): string | null {\n const normalizedBaseUrl = checkoutBaseUrl?.trim();\n if (!normalizedBaseUrl) {\n return null;\n }\n\n try {\n const baseUrl = new URL(normalizedBaseUrl);\n const basePath = baseUrl.pathname.replace(/\\/+$/, '');\n baseUrl.pathname = `${basePath}/invoice/${encodeURIComponent(invoiceId)}`.replace(/\\/{2,}/g, '/');\n baseUrl.search = '';\n baseUrl.hash = '';\n return baseUrl.toString();\n } catch {\n return null;\n }\n}\n\nfunction appendCheckoutUrlOptions(\n checkoutUrl: string,\n options: { email?: string | null; locale?: string },\n): string {\n const normalizedEmail = normalizeEmail(options.email);\n const normalizedLocale = typeof options.locale === 'string' ? options.locale.trim() : '';\n\n if (!normalizedEmail && !normalizedLocale) {\n return checkoutUrl;\n }\n\n try {\n const parsedCheckoutUrl = new URL(checkoutUrl);\n if (normalizedLocale) {\n parsedCheckoutUrl.searchParams.set('locale', normalizedLocale);\n }\n if (normalizedEmail) {\n const hashParams = new URLSearchParams(parsedCheckoutUrl.hash.startsWith('#')\n ? parsedCheckoutUrl.hash.slice(1)\n : parsedCheckoutUrl.hash);\n hashParams.set(CHECKOUT_PREFILL_EMAIL_HASH_KEY, normalizedEmail);\n parsedCheckoutUrl.hash = hashParams.toString();\n }\n return parsedCheckoutUrl.toString();\n } catch {\n return checkoutUrl;\n }\n}\n\nfunction normalizeCheckoutResponse(\n response: CheckoutApiResponse | undefined,\n checkoutBaseUrl: string | undefined\n): NormalizedCheckoutData | null {\n const nestedInvoice = response?.invoice;\n const invoiceId = response?.invoiceId?.trim()\n || response?.invoice_id?.trim()\n || response?.uniqid?.trim()\n || nestedInvoice?.invoiceId?.trim()\n || nestedInvoice?.invoice_id?.trim()\n || nestedInvoice?.uniqid?.trim();\n let checkoutUrl = response?.checkoutUrl?.trim()\n || response?.checkout_url?.trim()\n || response?.url_branded?.trim()\n || response?.url?.trim()\n || nestedInvoice?.checkoutUrl?.trim()\n || nestedInvoice?.checkout_url?.trim()\n || nestedInvoice?.url_branded?.trim()\n || nestedInvoice?.url?.trim();\n\n if (!checkoutUrl && invoiceId && nestedInvoice) {\n checkoutUrl = buildCheckoutUrlFromInvoiceId(checkoutBaseUrl, invoiceId) ?? undefined;\n }\n\n if (!invoiceId || !checkoutUrl) {\n return null;\n }\n\n return {\n invoiceId,\n checkoutUrl,\n rewards: response?.rewards ?? nestedInvoice?.rewards ?? null,\n };\n}\n\nfunction resolveCheckoutOptions(\n couponOrOptions?: string | CheckoutOptions,\n options?: CheckoutOptions\n): CheckoutOptions {\n if (typeof couponOrOptions === 'string') {\n return {\n ...options,\n coupon: couponOrOptions,\n };\n }\n\n return couponOrOptions ?? options ?? {};\n}\n\nfunction normalizeAffiliateCode(options: CheckoutOptions, storedAffiliateCode: string | null): string | null {\n const explicitCode = options.affiliateCode ?? options.referralCode;\n // Tri-state, mirroring `coupon`: an explicit empty string means \"none\" and\n // must suppress the storage re-read. Only `undefined` lets the SDK resolve\n // the code itself — otherwise a referral captured after the quote was\n // rendered would be applied to a total the buyer never saw.\n if (typeof explicitCode === 'string') {\n const normalized = explicitCode.trim().toLowerCase();\n return normalized.length > 0 ? normalized : null;\n }\n\n return storedAffiliateCode?.trim().toLowerCase() ?? getAffiliateCode();\n}\n\nfunction resolveCheckoutCodes(options: CheckoutOptions): {\n coupon: string | null;\n affiliateCode: string | null;\n} {\n const storedCode = getCartCoupon();\n const storedSource = getCartCouponSource();\n const coupon = options.coupon === undefined\n ? (storedSource === 'COUPON' ? storedCode : null)\n : normalizeCoupon(options.coupon);\n const storedAffiliateCode = options.coupon === undefined && storedSource === 'AFFILIATE'\n ? storedCode\n : null;\n\n return {\n coupon,\n affiliateCode: normalizeAffiliateCode(options, storedAffiliateCode),\n };\n}\n\nfunction mapCartItemsForApi(items: CartItem[]) {\n const normalizeVariantIdForApi = (value: string | null | undefined): string | null => {\n const normalized = value?.trim();\n if (!normalized) return null;\n // Themes use \"default\" as a sentinel for \"no variant selected\".\n // Backend expects `null` in that case.\n if (normalized.toLowerCase() === 'default') return null;\n return normalized;\n };\n\n return items.map((item) => ({\n product_id: item.product_id,\n variant_id: normalizeVariantIdForApi(item.variant_id),\n quantity: item.quantity,\n addons: item.addons?.map((a: CartAddon) => ({ id: a.id, quantity: a.quantity ?? 1 })),\n custom_fields: item.custom_fields,\n price_variant_id: item.price_variant_id || null,\n pay_what_you_want_price: item.pay_what_you_want_price,\n }));\n}\n\nexport async function checkout(\n couponOrOptions?: string | CheckoutOptions,\n options?: CheckoutOptions\n): Promise<CheckoutResult> {\n const resolvedOptions = resolveCheckoutOptions(couponOrOptions, options);\n const { autoRedirect = true, email } = resolvedOptions;\n const checkoutCodes = resolveCheckoutCodes(resolvedOptions);\n const normalizedCoupon = checkoutCodes.coupon;\n const normalizedEmail = normalizeEmail(email);\n const normalizedAffiliateCode = checkoutCodes.affiliateCode;\n const requestedCurrency = resolveRequestedCheckoutCurrency(resolvedOptions);\n const postPurchaseRedirect = resolvePostPurchaseRedirectUrl(resolvedOptions.redirectUrl);\n\n const cart = getCart();\n if (cart.length === 0) {\n return {\n success: false,\n message: 'Cart is empty',\n };\n }\n\n // PAYMENT PATH. The cart the caller approved, compared against the cart this\n // call will actually POST — see `CheckoutOptions.expectedCart`. Refused\n // before the backup and before the request, so a cart that changed under the\n // caller is never billed and nothing is left half-done.\n if (isExpectedCartMismatch(cart, resolvedOptions.expectedCart)) {\n return {\n success: false,\n message: CART_CHANGED_MESSAGE,\n };\n }\n if (postPurchaseRedirect.error) {\n return {\n success: false,\n message: postPurchaseRedirect.error,\n };\n }\n\n createCartBackup();\n\n const config = getConfig();\n const checkoutRequestTarget = resolveCustomerCheckoutRequestTarget(resolvedOptions);\n\n const createIntent = {\n shop_slug: config.storeSlug,\n cart: mapCartItemsForApi(cart),\n email: normalizedEmail,\n coupon: normalizedCoupon,\n currency: requestedCurrency,\n return_url: postPurchaseRedirect.value ?? undefined,\n affiliate_code: normalizedAffiliateCode,\n // Proof of the total the buyer approved, from the last quoteCart(). Sent\n // automatically so the server can refuse an invoice priced above it.\n // Undefined when nothing has been quoted this session — the endpoint\n // treats that exactly as an older SDK.\n quote_token: getLatestQuoteToken() ?? undefined,\n };\n const createCommand = {\n ...createIntent,\n turnstile_token: resolvedOptions.turnstileToken?.trim() || undefined,\n };\n const createAttempt = acquireCheckoutCreateIdempotency(checkoutRequestTarget, createIntent);\n const response = await post<CheckoutApiResponse>(\n checkoutRequestTarget.endpoint,\n createCommand,\n {\n retries: 0,\n baseUrl: checkoutRequestTarget.baseUrl,\n headers: {\n 'X-Idempotency-Key': createAttempt.key,\n },\n }\n );\n if (!response.success || !response.data) {\n releaseCheckoutCreateIdempotency(createAttempt, response.responseDefinitive === true);\n if (isStaleCartProductError(response.message)) {\n clearCart();\n }\n return {\n success: false,\n message: normalizeCheckoutFailureMessage(response.message),\n // The server's machine-readable refusal, preserved so callers can react\n // to e.g. `errors.checkout.price_increased_since_quote` without matching\n // localized copy.\n ...(response.code ? { code: response.code } : {}),\n ...(response.challenge ? { challenge: response.challenge } : {}),\n };\n }\n\n const checkoutData = normalizeCheckoutResponse(response.data, config.checkoutBaseUrl);\n if (!checkoutData) {\n return {\n success: false,\n message: 'Failed to create invoice',\n };\n }\n\n const { invoiceId } = checkoutData;\n const safeCheckoutUrl = validateCheckoutUrl(\n checkoutData.checkoutUrl,\n config.checkoutBaseUrl,\n invoiceId\n );\n if (!safeCheckoutUrl) {\n return {\n success: false,\n message: 'Failed to create invoice',\n };\n }\n\n releaseCheckoutCreateIdempotency(createAttempt, true);\n\n // One checkout_started per created invoice: dedupes accidental duplicate\n // sends without dropping a buyer's genuine second order in the same session.\n void trackAffiliateEvent('checkout_started', {\n code: normalizedAffiliateCode,\n dedupeKey: `inv:${invoiceId}`,\n });\n\n const checkoutUrlWithPrefill = appendCheckoutUrlOptions(safeCheckoutUrl, {\n email: normalizedEmail,\n locale: resolvedOptions.locale ?? config.locale,\n });\n\n if (autoRedirect) {\n if (typeof window !== 'undefined' && window?.location) {\n window.location.href = checkoutUrlWithPrefill;\n clearCart();\n }\n }\n\n return {\n success: true,\n redirectUrl: checkoutUrlWithPrefill,\n invoiceId,\n rewards: checkoutData.rewards,\n };\n}\n\n/**\n * Build checkout URL by creating invoice first.\n * Returns the checkout URL for the created invoice.\n *\n * PAYMENT PATH. \"Build a URL\" names what this returns, not a lighter way to\n * price a cart: it POSTs the same invoice-creating endpoint as `checkout()` and\n * bills whatever storage holds when it reads. It therefore honours\n * `CheckoutOptions.expectedCart` on exactly the same terms — a pinned cart that\n * moved is refused, not invoiced.\n *\n * A refusal throws, like every other refusal on this function: the success\n * shape is a URL string, so there is no in-band value that a caller could\n * mistake for one. The thrown message is the buyer-facing copy, identical to\n * the sentence `checkout()` returns, and callers that already handle the\n * `Cart is empty` throw handle this one unchanged.\n */\nexport async function buildCheckoutUrl(\n couponOrOptions?: string | CheckoutOptions,\n options?: CheckoutOptions\n): Promise<string> {\n const resolvedOptions = resolveCheckoutOptions(couponOrOptions, options);\n const { email } = resolvedOptions;\n const checkoutCodes = resolveCheckoutCodes(resolvedOptions);\n const normalizedCoupon = checkoutCodes.coupon;\n const normalizedEmail = normalizeEmail(email);\n const normalizedAffiliateCode = checkoutCodes.affiliateCode;\n const requestedCurrency = resolveRequestedCheckoutCurrency(resolvedOptions);\n const postPurchaseRedirect = resolvePostPurchaseRedirectUrl(resolvedOptions.redirectUrl);\n\n const cart = getCart();\n if (cart.length === 0) {\n throw new Error('Cart is empty');\n }\n\n // PAYMENT PATH. Same position `checkout()` puts it in: after the empty-cart\n // check and before anything is created or sent. This path has no cart backup\n // to write, so the request is the first side effect there is — refusing here\n // means a cart that changed under the caller never reaches the endpoint, and\n // the buyer's cart is left exactly as the interfering write left it. It\n // matters most with no quote token in play, because then nothing downstream\n // carries an approved-total ceiling either.\n if (isExpectedCartMismatch(cart, resolvedOptions.expectedCart)) {\n throw new Error(CART_CHANGED_MESSAGE);\n }\n if (postPurchaseRedirect.error) {\n throw new Error(postPurchaseRedirect.error);\n }\n\n const config = getConfig();\n const checkoutRequestTarget = resolveCustomerCheckoutRequestTarget(resolvedOptions);\n\n const createIntent = {\n shop_slug: config.storeSlug,\n cart: mapCartItemsForApi(cart),\n email: normalizedEmail,\n coupon: normalizedCoupon,\n currency: requestedCurrency,\n return_url: postPurchaseRedirect.value ?? undefined,\n affiliate_code: normalizedAffiliateCode,\n // Same invoice-creating endpoint as `checkout()`, so it carries the same\n // proof of the approved total. \"Build a URL\" describes what this returns\n // to the caller, not a different way to price a cart — omitting the\n // token here left a public path on which the server had nothing to check\n // the invoice against. Same optional semantics: undefined when nothing\n // was quoted this session.\n quote_token: getLatestQuoteToken() ?? undefined,\n };\n const createCommand = {\n ...createIntent,\n turnstile_token: resolvedOptions.turnstileToken?.trim() || undefined,\n };\n const createAttempt = acquireCheckoutCreateIdempotency(checkoutRequestTarget, createIntent);\n const response = await post<CheckoutApiResponse>(\n checkoutRequestTarget.endpoint,\n createCommand,\n {\n retries: 0,\n baseUrl: checkoutRequestTarget.baseUrl,\n headers: {\n 'X-Idempotency-Key': createAttempt.key,\n },\n }\n );\n if (!response.success || !response.data) {\n releaseCheckoutCreateIdempotency(createAttempt, response.responseDefinitive === true);\n if (isStaleCartProductError(response.message)) {\n clearCart();\n }\n throw new CheckoutCreateError(normalizeCheckoutFailureMessage(response.message), {\n ...(response.challenge ? { challenge: response.challenge } : {}),\n ...(response.code ? { code: response.code } : {}),\n ...(response.status !== undefined ? { status: response.status } : {}),\n });\n }\n const checkoutData = normalizeCheckoutResponse(response.data, config.checkoutBaseUrl);\n if (!checkoutData) {\n throw new Error('Failed to create invoice');\n }\n\n const safeCheckoutUrl = validateCheckoutUrl(\n checkoutData.checkoutUrl,\n config.checkoutBaseUrl,\n checkoutData.invoiceId\n );\n if (!safeCheckoutUrl) {\n throw new Error('Failed to create invoice');\n }\n\n releaseCheckoutCreateIdempotency(createAttempt, true);\n\n // Same funnel point as checkout(): both entry points create the invoice.\n void trackAffiliateEvent('checkout_started', {\n code: normalizedAffiliateCode,\n dedupeKey: `inv:${checkoutData.invoiceId}`,\n });\n\n return appendCheckoutUrlOptions(safeCheckoutUrl, {\n email: normalizedEmail,\n locale: resolvedOptions.locale ?? config.locale,\n });\n}\n\n/**\n * @deprecated Use buildCheckoutUrl instead.\n * Sync version is no longer supported as invoice creation requires API call.\n */\nexport function buildCheckoutUrlSync(): never {\n throw new Error('buildCheckoutUrlSync is deprecated. Use buildCheckoutUrl (async) instead.');\n}\n","import { getConfig } from '../core/config';\nimport type { ApiChallenge } from '../types/api';\n\nconst TURNSTILE_FRAME_MESSAGE_SOURCE = 'shoppex-turnstile';\nconst TURNSTILE_FRAME_MESSAGE_VERSION = 1;\n// The hosted broker posts `ready` immediately after Turnstile renders. Ten\n// seconds tolerates slow mobile networks while bounding a broken/CSP-blocked frame.\nconst TURNSTILE_FRAME_READY_TIMEOUT_MS = 10_000;\n\nexport interface CheckoutChallengeCallbacks {\n onSuccess(token: string): void;\n onExpired?(): void;\n onUnavailable?(): void;\n}\n\nexport interface CheckoutChallengeFrame {\n element: HTMLIFrameElement;\n dispose(): void;\n}\n\nfunction readFrameMessage(\n value: unknown,\n nonce: string,\n): { type: 'ready' | 'visible' | 'hidden' | 'success' | 'expired' | 'timeout' | 'error'; token?: string } | null {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return null;\n const record = value as Record<string, unknown>;\n if (\n record.source !== TURNSTILE_FRAME_MESSAGE_SOURCE\n || record.version !== TURNSTILE_FRAME_MESSAGE_VERSION\n || record.nonce !== nonce\n || !['ready', 'visible', 'hidden', 'success', 'expired', 'timeout', 'error'].includes(String(record.type))\n ) return null;\n if (record.type === 'success' && (typeof record.token !== 'string' || !record.token.trim())) {\n return null;\n }\n return {\n type: record.type as 'ready' | 'visible' | 'hidden' | 'success' | 'expired' | 'timeout' | 'error',\n ...(typeof record.token === 'string' ? { token: record.token.trim() } : {}),\n };\n}\n\n/**\n * Mount the Shoppex-hosted Turnstile broker requested by a checkout refusal.\n *\n * The challenge always executes on the configured hosted-checkout origin, so\n * this works on arbitrary custom storefront domains without adding each one\n * to Cloudflare's widget hostname allowlist. Retry `checkout()` or\n * `buildCheckoutUrl()` with the token delivered to `onSuccess`.\n */\nexport function mountCheckoutChallenge(\n container: HTMLElement,\n challenge: ApiChallenge,\n callbacks: CheckoutChallengeCallbacks,\n): CheckoutChallengeFrame {\n if (challenge.provider !== 'turnstile' || !challenge.siteKey.trim()) {\n throw new Error('Checkout challenge is invalid.');\n }\n\n const win = container.ownerDocument.defaultView;\n if (!win) throw new Error('Checkout challenge requires a browser document.');\n\n const checkoutBaseUrl = getConfig().checkoutBaseUrl;\n const frameUrl = new URL('/turnstile', checkoutBaseUrl);\n if (frameUrl.protocol !== 'https:' && frameUrl.protocol !== 'http:') {\n throw new Error('Checkout base URL must use http or https.');\n }\n const nonce = win.crypto.randomUUID();\n frameUrl.searchParams.set('site_key', challenge.siteKey.trim());\n frameUrl.searchParams.set('nonce', nonce);\n\n const frame = container.ownerDocument.createElement('iframe');\n frame.src = frameUrl.toString();\n frame.title = 'Checkout verification';\n frame.referrerPolicy = 'no-referrer';\n frame.style.border = '0';\n frame.style.width = '100%';\n frame.style.height = '0';\n\n let disposed = false;\n let ready = false;\n const readyTimeout = win.setTimeout(() => {\n if (!disposed && !ready) callbacks.onUnavailable?.();\n }, TURNSTILE_FRAME_READY_TIMEOUT_MS);\n const onMessage = (event: MessageEvent) => {\n if (\n disposed\n || event.origin !== frameUrl.origin\n || event.source !== frame.contentWindow\n ) return;\n const message = readFrameMessage(event.data, nonce);\n if (!message) return;\n ready = true;\n win.clearTimeout(readyTimeout);\n if (message.type === 'visible') frame.style.height = '72px';\n if (message.type === 'hidden') frame.style.height = '0';\n if (message.type === 'success') {\n frame.style.height = '0';\n callbacks.onSuccess(message.token!);\n }\n if (message.type === 'expired' || message.type === 'timeout') callbacks.onExpired?.();\n if (message.type === 'error') callbacks.onUnavailable?.();\n };\n const onFrameError = () => callbacks.onUnavailable?.();\n\n win.addEventListener('message', onMessage);\n frame.addEventListener('error', onFrameError, { once: true });\n container.appendChild(frame);\n\n return {\n element: frame,\n dispose() {\n if (disposed) return;\n disposed = true;\n win.clearTimeout(readyTimeout);\n win.removeEventListener('message', onMessage);\n frame.removeEventListener('error', onFrameError);\n frame.remove();\n },\n };\n}\n","/**\n * Coupons Module\n *\n * Coupon validation before checkout.\n */\n\nimport { post } from '../core/client';\nimport { getShopId } from '../core/config';\nimport { getStore } from './store';\nimport { getCart } from './cart';\nimport type { SDKResponse, CouponValidation, CouponValidationOptions } from '../types';\n\nasync function resolveShopId(): Promise<string | null> {\n const cachedShopId = getShopId();\n if (cachedShopId) {\n return cachedShopId;\n }\n\n const storeResult = await getStore();\n if (!storeResult.success || !storeResult.data?.id) {\n return null;\n }\n\n return storeResult.data.id;\n}\n\nexport async function validateCoupon(\n code: string,\n productOrOptions?: string | CouponValidationOptions\n): Promise<SDKResponse<CouponValidation>> {\n const trimmedCode = code.trim();\n if (!trimmedCode) {\n return {\n success: false,\n message: 'Coupon code is required',\n };\n }\n\n const payload: Record<string, unknown> = {\n code: trimmedCode,\n };\n const productId = typeof productOrOptions === 'string'\n ? productOrOptions\n : productOrOptions?.productId;\n const variantId = typeof productOrOptions === 'string'\n ? undefined\n : productOrOptions?.variantId;\n\n if (variantId && !productId) {\n return {\n success: false,\n message: 'productId is required when variantId is provided',\n };\n }\n\n if (productId) {\n payload.product_id = productId;\n if (variantId) {\n payload.variant_id = variantId;\n }\n } else {\n const cart = getCart();\n if (cart.length === 0) {\n return {\n success: false,\n message: 'Cart is empty',\n };\n }\n\n const shopId = await resolveShopId();\n if (!shopId) {\n return {\n success: false,\n message: 'Failed to resolve store',\n };\n }\n\n payload.cart = JSON.stringify({\n shop_id: shopId,\n products: cart.map((item) => ({\n uniqid: item.product_id,\n quantity: item.quantity,\n variant_id: item.variant_id,\n price_variant_id: item.price_variant_id,\n addons: item.addons?.map((addon) => ({\n id: addon.id,\n quantity: addon.quantity ?? 1,\n })),\n })),\n });\n }\n\n const response = await post<CouponValidation>(\n '/v1/storefront/coupons/check',\n payload\n );\n\n return response;\n}\n","/**\n * Reviews Module\n *\n * Shop-level feedback/reviews.\n * Note: Shoppex has shop-level feedback, not product-level reviews.\n */\n\nimport { get } from '../core/client';\nimport { getConfig } from '../core/config';\nimport { buildEndpoint } from '../core/endpoint';\nimport type { SDKResponse, Feedback, ShopReviewsPage } from '../types';\n\nconst REVIEWS_PAGE_LIMIT = 100;\nconst REVIEWS_CACHE_TTL = 2 * 60 * 1000;\n\nfunction toFiniteNumber(value: unknown): number | null {\n if (typeof value === 'number' && Number.isFinite(value)) {\n return value;\n }\n\n if (typeof value === 'string' && value.trim() !== '') {\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : null;\n }\n\n return null;\n}\n\nfunction firstString(...values: unknown[]): string | undefined {\n for (const value of values) {\n if (typeof value === 'string' && value.length > 0) {\n return value;\n }\n }\n\n return undefined;\n}\n\nfunction normalizeFeedback(raw: Feedback, index: number): Feedback {\n const record = raw as Feedback & Record<string, unknown>;\n const rating = toFiniteNumber(record.rating) ?? toFiniteNumber(record.score) ?? 0;\n const comment = firstString(record.comment, record.message);\n const author = firstString(record.author, record.customer_name);\n const createdAt = record.created_at ?? record.createdAt;\n const created_at =\n typeof createdAt === 'number' || typeof createdAt === 'string'\n ? String(createdAt)\n : '';\n const id = firstString(record.id, record.uniqid) ?? `review:${created_at || index}`;\n\n return {\n ...record,\n id,\n rating,\n ...(comment ? { comment } : {}),\n ...(author ? { author } : {}),\n created_at,\n };\n}\n\nexport async function getShopReviewsPage(cursor?: string | null): Promise<SDKResponse<ShopReviewsPage>> {\n const config = getConfig();\n const query = new URLSearchParams();\n query.set('limit', String(REVIEWS_PAGE_LIMIT));\n if (typeof cursor === 'string' && cursor.trim().length > 0) {\n query.set('cursor', cursor);\n }\n const querySuffix = `?${query.toString()}`;\n\n const response = await get<ShopReviewsPage>(\n `${buildEndpoint('/v1/storefront/feedback/shop/:storeSlug', {\n storeSlug: config.storeSlug,\n })}${querySuffix}`,\n {\n cache: {\n key: `reviews:${config.storeSlug}:${cursor ?? 'start'}:${REVIEWS_PAGE_LIMIT}`,\n ttl: REVIEWS_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data) {\n return {\n success: true,\n data: {\n ...response.data,\n feedback: response.data.feedback.map(normalizeFeedback),\n },\n };\n }\n\n return {\n success: false,\n message: response.message,\n };\n}\n\nexport async function getShopReviews(): Promise<SDKResponse<Feedback[]>> {\n const allFeedback: Feedback[] = [];\n const seenCursors = new Set<string>();\n let cursor: string | null = null;\n\n while (true) {\n const response = await getShopReviewsPage(cursor);\n if (!response.success || !response.data) {\n return {\n success: false,\n message: response.message,\n data: [],\n };\n }\n\n allFeedback.push(...response.data.feedback);\n\n const pagination = response.data.pagination;\n if (!pagination?.has_more || !pagination.next_cursor) {\n break;\n }\n\n if (seenCursors.has(pagination.next_cursor)) {\n break;\n }\n\n seenCursors.add(pagination.next_cursor);\n cursor = pagination.next_cursor;\n }\n\n return {\n success: true,\n data: allFeedback,\n };\n}\n","/**\n * Customer Module\n *\n * Authenticated customer account calls for code-lane storefronts. The edge\n * worker owns the HttpOnly session cookie and derives the shop from the host.\n * This module therefore sends neither a session token nor shop identity.\n */\n\nimport {\n customerLoyaltyRedeemSchema,\n customerLoyaltySchema,\n customerPortalDashboardSchema,\n customerPortalInvoiceDetailSchema,\n customerPortalPaginatedInvoicesSchema,\n customerWarrantyClaimSchema,\n customerWarrantyListSchema,\n type CustomerLoyaltyRedeemWire,\n type CustomerLoyaltyWire,\n type CustomerPortalDashboardWire,\n type CustomerPortalInvoiceDetailWire,\n type CustomerPortalPaginatedInvoicesWire,\n type CustomerWarrantyClaimWire,\n type CustomerWarrantyListWire,\n} from '@shoppex/contracts';\nimport type { SDKResponse } from '../types';\n\nconst CUSTOMER_API_PREFIX = '/api/customer';\n\ntype CustomerMethod = 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE';\n\n/**\n * A producer-owned schema for the response payload.\n *\n * Only the endpoints whose shape is defined in `@shoppex/contracts` get one.\n * The rest stay `unknown` on purpose: inventing a type here would assert a wire\n * shape the producer never promised, which is the pattern the retired portal's\n * 544-line hand-written type file demonstrates the cost of.\n */\ninterface CustomerPayloadSchema<T> {\n safeParse(value: unknown): { success: true; data: T } | { success: false };\n}\n\ninterface CustomerRequestOptions<T> {\n method?: CustomerMethod;\n body?: unknown;\n /** Multipart payload. Mutually exclusive with `body`; the browser sets the boundary. */\n formData?: FormData;\n schema?: CustomerPayloadSchema<T>;\n}\n\nexport interface CustomerOrdersQuery {\n page?: number;\n limit?: number;\n /**\n * Invoice status filter, verbatim from the producer's enum. Anything else is\n * answered with a 400 rather than quietly ignored, so pass what the buyer\n * actually chose.\n */\n status?: string;\n /** Partial invoice-id search. The producer trims it to 64 characters. */\n search?: string;\n}\n\ninterface CustomerApiEnvelope {\n status: number;\n data: unknown;\n error?: unknown;\n message?: unknown;\n error_code?: unknown;\n error_params?: unknown;\n}\n\nexport interface CustomerTicketPayload {\n title?: string;\n message: string;\n invoice_id?: string;\n}\n\nexport interface CustomerProfilePatch {\n name: string;\n}\n\nexport interface CustomerSubscriptionCancelOptions {\n cancel_at_period_end?: boolean;\n reason?: string | null;\n}\n\nexport interface CustomerEmailPreferencesPatch {\n global_unsubscribed?: boolean;\n list_subscriptions?: Array<{ list_id: string; subscribed: boolean }>;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction narrowEnvelope(value: unknown): CustomerApiEnvelope | null {\n if (!isRecord(value) || typeof value.status !== 'number' || !('data' in value)) {\n return null;\n }\n\n return value as unknown as CustomerApiEnvelope;\n}\n\nfunction readMessage(envelope: CustomerApiEnvelope, response: Response): string {\n if (typeof envelope.error === 'string' && envelope.error.length > 0) {\n return envelope.error;\n }\n\n if (typeof envelope.message === 'string' && envelope.message.length > 0) {\n return envelope.message;\n }\n\n return response.statusText\n ? `HTTP ${response.status}: ${response.statusText}`\n : `HTTP ${response.status}`;\n}\n\nfunction readErrorFields(envelope: CustomerApiEnvelope): Pick<SDKResponse<unknown>, 'code' | 'errorParams'> {\n const code = typeof envelope.error_code === 'string' && envelope.error_code.length > 0\n ? envelope.error_code\n : null;\n\n if (!code) {\n return {};\n }\n\n return {\n code,\n ...(isRecord(envelope.error_params) ? { errorParams: envelope.error_params } : {}),\n };\n}\n\nasync function requestCustomer<T = unknown>(\n path: string,\n options: CustomerRequestOptions<T> = {},\n): Promise<SDKResponse<T>> {\n const method = options.method ?? 'GET';\n const headers: Record<string, string> = {\n Accept: 'application/json',\n };\n\n if (options.body !== undefined) {\n headers['Content-Type'] = 'application/json';\n }\n\n // FormData carries its own multipart boundary in the Content-Type the browser\n // generates; setting the header here would produce a body the server cannot parse.\n const payload = options.formData ?? (options.body !== undefined ? JSON.stringify(options.body) : undefined);\n\n try {\n const response = await fetch(`${CUSTOMER_API_PREFIX}${path}`, {\n method,\n headers,\n body: payload,\n credentials: 'same-origin',\n cache: 'no-store',\n });\n\n if (response.status === 204) {\n return response.ok\n ? { success: true, status: response.status }\n : {\n success: false,\n status: response.status,\n message: readMessage({ status: response.status, data: null }, response),\n };\n }\n\n let rawEnvelope: unknown;\n try {\n rawEnvelope = await response.json();\n } catch {\n return { success: false, status: response.status, message: 'Invalid customer API response' };\n }\n\n const envelope = narrowEnvelope(rawEnvelope);\n if (!envelope) {\n return { success: false, status: response.status, message: 'Invalid customer API response' };\n }\n\n if (!response.ok || envelope.status < 200 || envelope.status >= 300) {\n return {\n success: false,\n // The transport status, not the envelope's: a caller deciding whether\n // the buyer is signed out must not be steered by a body the edge may\n // never have produced.\n status: response.status,\n message: readMessage(envelope, response),\n ...readErrorFields(envelope),\n };\n }\n\n const message = typeof envelope.message === 'string' && envelope.message.length > 0\n ? { message: envelope.message }\n : {};\n\n if (!options.schema) {\n return { success: true, data: envelope.data as T, ...message };\n }\n\n const parsed = options.schema.safeParse(envelope.data);\n if (!parsed.success) {\n // Fail loudly instead of handing back a payload that does not match what\n // the producer promised. A silently reshaped or partially-read response\n // is how a contract drift reaches the buyer's screen as wrong data.\n return { success: false, message: 'Customer API response did not match the expected contract' };\n }\n\n return { success: true, data: parsed.data, ...message };\n } catch (error) {\n return {\n success: false,\n message: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\n/** One basket line for a QUOTE. `variant_id` is omitted, never null, when a product has no variants. */\nexport interface ResellerOrderItem {\n product_id: string;\n variant_id?: string;\n quantity: number;\n}\n\nexport interface ResellerCatalogQuery {\n search?: string;\n page?: number;\n per_page?: number;\n}\n\nexport interface ResellerOrdersQuery {\n page?: number;\n per_page?: number;\n}\n\nexport function requestOtp(email: string): Promise<SDKResponse<unknown>> {\n return requestCustomer('/auth/otp/request', {\n method: 'POST',\n body: { email },\n });\n}\n\n/**\n * The wire field is `otp`, not `code` — `CustomerOtpVerifyBodySchema` in\n * `apps/backend-elysia/src/routes/v1/customer/schemas.ts` requires it under that\n * name, and a `code` body is rejected with 400.\n */\nexport function verifyOtp(email: string, otp: string): Promise<SDKResponse<unknown>> {\n return requestCustomer('/auth/otp/verify', {\n method: 'POST',\n body: { email, otp },\n });\n}\n\nexport function logout(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/auth/logout', { method: 'POST' });\n}\n\nexport function me(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/me');\n}\n\nexport function dashboard(): Promise<SDKResponse<CustomerPortalDashboardWire>> {\n return requestCustomer('/dashboard', { schema: customerPortalDashboardSchema });\n}\n\n/**\n * Paginated order history.\n *\n * Page-based, matching the producer: `invoices.routes.ts` reads `page` and\n * `limit` and answers with a `has_more` envelope. A cursor parameter would be\n * ignored upstream and silently return page one forever.\n *\n * `status` and `search` are filtered SERVER-side, which is why they belong\n * here rather than in the caller: `/invoices` is paged, and a filter applied\n * to the page in hand would filter only the rows that page happens to hold.\n * The producer spells the search `q`.\n */\nexport function orders(options: CustomerOrdersQuery = {}): Promise<SDKResponse<CustomerPortalPaginatedInvoicesWire>> {\n const query = new URLSearchParams();\n if (options.page !== undefined) query.set('page', String(options.page));\n if (options.limit !== undefined) query.set('limit', String(options.limit));\n if (options.status) query.set('status', options.status);\n if (options.search) query.set('q', options.search);\n\n const suffix = query.size > 0 ? `?${query.toString()}` : '';\n return requestCustomer(`/invoices${suffix}`, { schema: customerPortalPaginatedInvoicesSchema });\n}\n\nexport function order(id: string): Promise<SDKResponse<CustomerPortalInvoiceDetailWire>> {\n return requestCustomer(`/invoice/${encodeURIComponent(id)}`, {\n schema: customerPortalInvoiceDetailSchema,\n });\n}\n\nexport function loyalty(): Promise<SDKResponse<CustomerLoyaltyWire>> {\n return requestCustomer('/loyalty', { schema: customerLoyaltySchema });\n}\n\nexport function redeemLoyaltyPoints(input: {\n points: number;\n idempotencyKey: string;\n}): Promise<SDKResponse<CustomerLoyaltyRedeemWire>> {\n return requestCustomer('/loyalty/redeem', {\n method: 'POST',\n body: {\n points: input.points,\n idempotency_key: input.idempotencyKey,\n },\n schema: customerLoyaltyRedeemSchema,\n });\n}\n\n/**\n * The warranties this buyer holds — all of them, or the ones on one order.\n *\n * `invoiceUniqid` becomes the producer's own `invoice=` filter, which matches\n * `invoices.uniqid`: the id an order carries everywhere a storefront shows one.\n * So an order detail asks for its own cover rather than reading every warranty\n * the buyer owns and discarding most of them.\n */\nexport function warranties(invoiceUniqid?: string): Promise<SDKResponse<CustomerWarrantyListWire>> {\n const suffix = invoiceUniqid ? `?invoice=${encodeURIComponent(invoiceUniqid)}` : '';\n return requestCustomer(`/warranties${suffix}`, { schema: customerWarrantyListSchema });\n}\n\nexport function claimWarranty(\n uniqid: string,\n message?: string,\n): Promise<SDKResponse<CustomerWarrantyClaimWire>> {\n return requestCustomer(`/warranties/${encodeURIComponent(uniqid)}/claim`, {\n method: 'POST',\n body: message ? { message } : {},\n schema: customerWarrantyClaimSchema,\n });\n}\n\n// ---------------------------------------------------------------------------\n// Licenses, subscriptions and tickets have NO collection route.\n//\n// Those three lists arrive inside `/dashboard` — `licenses.routes.ts`,\n// `subscriptions.routes.ts` and `tickets.routes.ts` expose per-item routes only.\n// A `GET /licenses` here would 404 on every call, which is what the earlier\n// spelling of this module did.\n// ---------------------------------------------------------------------------\n\nexport function resetLicenseHwid(uniqid: string): Promise<SDKResponse<unknown>> {\n return requestCustomer(`/licenses/${encodeURIComponent(uniqid)}/reset-hwid`, {\n method: 'POST',\n body: {},\n });\n}\n\nexport function subscriptionBillingHistory(uniqid: string): Promise<SDKResponse<unknown>> {\n return requestCustomer(`/subscriptions/${encodeURIComponent(uniqid)}/billing-history`);\n}\n\nexport function cancelSubscription(\n uniqid: string,\n options: CustomerSubscriptionCancelOptions = {},\n): Promise<SDKResponse<unknown>> {\n return requestCustomer(`/subscriptions/${encodeURIComponent(uniqid)}/cancel`, {\n method: 'POST',\n body: {\n ...(options.cancel_at_period_end !== undefined\n ? { cancel_at_period_end: options.cancel_at_period_end }\n : {}),\n ...(options.reason !== undefined ? { reason: options.reason } : {}),\n },\n });\n}\n\nexport function pauseSubscription(uniqid: string): Promise<SDKResponse<unknown>> {\n return requestCustomer(`/subscriptions/${encodeURIComponent(uniqid)}/pause`, {\n method: 'POST',\n body: {},\n });\n}\n\nexport function resumeSubscription(uniqid: string): Promise<SDKResponse<unknown>> {\n return requestCustomer(`/subscriptions/${encodeURIComponent(uniqid)}/resume`, {\n method: 'POST',\n body: {},\n });\n}\n\nexport function favorites(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/favorites');\n}\n\n/** Idempotent upstream, and a PUT — `customer-favorites.ts` has no POST route. */\nexport function addFavorite(productUniqid: string): Promise<SDKResponse<unknown>> {\n return requestCustomer(`/favorites/${encodeURIComponent(productUniqid)}`, { method: 'PUT' });\n}\n\nexport function removeFavorite(productUniqid: string): Promise<SDKResponse<unknown>> {\n return requestCustomer(`/favorites/${encodeURIComponent(productUniqid)}`, { method: 'DELETE' });\n}\n\nexport function affiliate(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/affiliate');\n}\n\nexport function affiliateStats(days?: number): Promise<SDKResponse<unknown>> {\n const suffix = days === undefined ? '' : `?days=${encodeURIComponent(String(days))}`;\n return requestCustomer(`/affiliate/stats${suffix}`);\n}\n\nexport function createTicket(payload: CustomerTicketPayload): Promise<SDKResponse<unknown>> {\n return requestCustomer('/tickets', {\n method: 'POST',\n body: {\n ...(payload.title !== undefined ? { title: payload.title } : {}),\n message: payload.message,\n ...(payload.invoice_id !== undefined ? { invoice_id: payload.invoice_id } : {}),\n },\n });\n}\n\nexport function ticket(uniqid: string): Promise<SDKResponse<unknown>> {\n return requestCustomer(`/tickets/${encodeURIComponent(uniqid)}`);\n}\n\nexport function replyToTicket(uniqid: string, message: string): Promise<SDKResponse<unknown>> {\n return requestCustomer(`/tickets/${encodeURIComponent(uniqid)}/reply`, {\n method: 'POST',\n body: { message },\n });\n}\n\n/**\n * The producer is `POST /v1/customer/profile`, not PATCH.\n *\n * There is no `GET /profile` to pair with it — the buyer's own record comes from\n * `/me` and `/dashboard`.\n */\nexport function updateProfile(patch: CustomerProfilePatch): Promise<SDKResponse<unknown>> {\n return requestCustomer('/profile', {\n method: 'POST',\n body: { name: patch.name },\n });\n}\n\nexport function updateAvatar(file: File): Promise<SDKResponse<unknown>> {\n const form = new FormData();\n form.append('file', file);\n return requestCustomer('/profile/avatar', { method: 'POST', formData: form });\n}\n\nexport function removeAvatar(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/profile/avatar', { method: 'DELETE' });\n}\n\nexport function emailPreferences(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/email-marketing/preferences');\n}\n\nexport function updateEmailPreferences(\n patch: CustomerEmailPreferencesPatch,\n): Promise<SDKResponse<unknown>> {\n return requestCustomer('/email-marketing/preferences', {\n method: 'PATCH',\n body: {\n ...(patch.global_unsubscribed !== undefined\n ? { global_unsubscribed: patch.global_unsubscribed }\n : {}),\n ...(patch.list_subscriptions !== undefined\n ? { list_subscriptions: patch.list_subscriptions }\n : {}),\n },\n });\n}\n\nexport function sessions(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/sessions');\n}\n\nexport function revokeSession(id: string): Promise<SDKResponse<unknown>> {\n return requestCustomer(`/sessions/${encodeURIComponent(id)}`, { method: 'DELETE' });\n}\n\n/**\n * Ends every session except this one.\n *\n * `others=true` is required, not decorative: `RevokeOtherSessionsQuerySchema`\n * declares it as a literal, so the route answers 400 without it. The selector\n * is explicit on purpose — \"revoke sessions\" with no qualifier is one typo away\n * from signing the buyer out of the device they are holding.\n */\nexport function revokeAllSessions(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/sessions?others=true', { method: 'DELETE' });\n}\n\n// ---------------------------------------------------------------------------\n// Wholesale (reseller program)\n//\n// A second program on the same account: its own way in, its own prepaid\n// balance, its own prices. Every route re-checks \"program enabled AND this\n// reseller is ACTIVE\" server-side, so nothing a storefront caches can widen\n// what a buyer may do here.\n//\n// Two writes are deliberately absent, and adding them back would be adding\n// methods that answer 404: the storefront worker refuses them. On a code\n// storefront the JavaScript on this origin is the MERCHANT's and it holds the\n// buyer's cookie, so the edge's same-origin check proves that script sent the\n// request, never that the buyer wanted it.\n// - placing a wholesale order debits the buyer's prepaid balance; a purchase\n// needs a boundary the merchant does not control\n// - minting an API key hands back a plaintext credential that keeps\n// authorizing orders after the session ends\n// Pricing a basket stays, because it writes nothing.\n// ---------------------------------------------------------------------------\n\n/** The program's state and this buyer's place in it. Null reseller means not enrolled. */\nexport function reseller(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/reseller');\n}\n\n/** `APPLICATION` mode. The note is optional unless the shop requires one. */\nexport function applyForReseller(note?: string): Promise<SDKResponse<unknown>> {\n return requestCustomer('/reseller/apply', {\n method: 'POST',\n body: note === undefined ? {} : { note },\n });\n}\n\n/** `OPEN` mode: no application, the buyer is a reseller when they say so. */\nexport function enrollAsReseller(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/reseller/enroll', { method: 'POST', body: {} });\n}\n\n/** `MANUAL` mode: the merchant invited this buyer and gave them a token. */\nexport function acceptResellerInvite(token: string): Promise<SDKResponse<unknown>> {\n return requestCustomer('/reseller/accept-invite', { method: 'POST', body: { token } });\n}\n\n/** The buyer's own tier prices. Page-based, like the order history. */\nexport function resellerCatalog(options: ResellerCatalogQuery = {}): Promise<SDKResponse<unknown>> {\n const query = new URLSearchParams();\n if (options.search !== undefined) query.set('search', options.search);\n if (options.page !== undefined) query.set('page', String(options.page));\n if (options.per_page !== undefined) query.set('per_page', String(options.per_page));\n\n const suffix = query.size > 0 ? `?${query.toString()}` : '';\n return requestCustomer(`/reseller/catalog${suffix}`);\n}\n\n/**\n * Prices a basket and writes nothing.\n *\n * The volume discount cannot be derived from the catalog — it only reports that\n * one exists — so a storefront that adds up unit prices itself shows a total\n * the shop will not charge. This is the number to display.\n */\nexport function quoteResellerOrder(items: ResellerOrderItem[]): Promise<SDKResponse<unknown>> {\n return requestCustomer('/reseller/orders/quote', { method: 'POST', body: { items } });\n}\n\nexport function resellerOrders(options: ResellerOrdersQuery = {}): Promise<SDKResponse<unknown>> {\n const query = new URLSearchParams();\n if (options.page !== undefined) query.set('page', String(options.page));\n if (options.per_page !== undefined) query.set('per_page', String(options.per_page));\n\n const suffix = query.size > 0 ? `?${query.toString()}` : '';\n return requestCustomer(`/reseller/orders${suffix}`);\n}\n\n/** One order with its lines, delivery state and delivered serials. */\nexport function resellerOrder(uniqid: string): Promise<SDKResponse<unknown>> {\n return requestCustomer(`/reseller/orders/${encodeURIComponent(uniqid)}`);\n}\n\n/** The prepaid balance the wholesale orders are paid from. */\nexport function resellerWallet(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/reseller/wallet');\n}\n\nexport function resellerApiKeys(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/reseller/api-keys');\n}\n\n/*\n * There is no `revokeResellerApiKey`. Revoking is irreversible and stops\n * whatever the key was driving, and this SDK is the transport for code\n * storefronts — merchant-authored JavaScript running with the buyer's session,\n * where a confirmation proves nothing because the merchant renders it. The\n * edge omits the DELETE from `CUSTOMER_API_ALLOWLIST`\n * (`workers/storefront/src/customer-api.ts`), so exporting a method for it\n * would advertise a call that always answers 404.\n */\n","import { getStorefront } from './store.js';\nimport { isInitialized } from '../core/config.js';\nimport {\n searchMergedStorefrontCatalog,\n searchMergedStorefrontCatalogItems,\n type StorefrontCatalogSearchItem,\n} from '../utils/storefront-search.js';\nimport type { SDKResponse, Product } from '../types/index.js';\n\nexport interface SearchOptions {\n hideOutOfStock?: boolean;\n maxResults?: number;\n}\n\nexport type { StorefrontCatalogSearchItem };\n\nexport async function searchCatalogItems(\n query: string,\n options?: SearchOptions,\n): Promise<SDKResponse<StorefrontCatalogSearchItem[]>> {\n if (!isInitialized()) {\n return { success: false, message: 'SDK not initialized' };\n }\n\n const trimmed = query.trim();\n if (!trimmed) {\n return { success: true, data: [] };\n }\n\n const storefront = await getStorefront();\n if (!storefront.success || !storefront.data) {\n return {\n success: false,\n message: storefront.message ?? 'Failed to fetch storefront catalog',\n };\n }\n\n const results = searchMergedStorefrontCatalogItems(\n storefront.data.products ?? [],\n storefront.data.groups ?? [],\n trimmed,\n {\n hideOutOfStock: options?.hideOutOfStock,\n maxResults: options?.maxResults,\n },\n );\n\n return { success: true, data: results };\n}\n\nexport async function searchProducts(\n query: string,\n options?: SearchOptions,\n): Promise<SDKResponse<Product[]>> {\n if (!isInitialized()) {\n return { success: false, message: 'SDK not initialized' };\n }\n\n const trimmed = query.trim();\n if (!trimmed) {\n return { success: true, data: [] };\n }\n\n const storefront = await getStorefront();\n if (!storefront.success || !storefront.data) {\n return {\n success: false,\n message: storefront.message ?? 'Failed to fetch storefront catalog',\n };\n }\n\n const results = searchMergedStorefrontCatalog(\n storefront.data.products ?? [],\n storefront.data.groups ?? [],\n trimmed,\n {\n hideOutOfStock: options?.hideOutOfStock,\n maxResults: options?.maxResults,\n },\n );\n\n return { success: true, data: results };\n}\n","/**\n * Invoices Module\n *\n * Invoice status checking after payment.\n */\n\nimport { get } from '../core/client';\nimport { buildEndpoint } from '../core/endpoint';\nimport type { SDKResponse, Invoice } from '../types';\n\nfunction normalizeInvoiceId(invoiceId: string): string | null {\n const normalized = invoiceId.trim();\n if (!normalized) {\n return null;\n }\n return normalized;\n}\n\nexport async function getInvoice(\n invoiceId: string\n): Promise<SDKResponse<Invoice>> {\n const normalizedInvoiceId = normalizeInvoiceId(invoiceId);\n if (!normalizedInvoiceId) {\n return {\n success: false,\n message: 'Invoice ID is required',\n };\n }\n\n const response = await get<{ invoice: Invoice }>(\n buildEndpoint('/v1/storefront/invoices/unique/:invoiceId', {\n invoiceId: normalizedInvoiceId,\n })\n );\n if (!response.success) {\n return {\n success: false,\n message: response.message,\n };\n }\n\n if (!response.data?.invoice) {\n return {\n success: false,\n message: 'Invalid invoice response',\n };\n }\n\n return {\n success: true,\n data: response.data.invoice,\n };\n}\n\nexport async function getInvoiceStatus(\n invoiceId: string\n): Promise<SDKResponse<{ status: string }>> {\n const normalizedInvoiceId = normalizeInvoiceId(invoiceId);\n if (!normalizedInvoiceId) {\n return {\n success: false,\n message: 'Invoice ID is required',\n };\n }\n\n const response = await get<{ invoice: { status: string } }>(\n buildEndpoint('/v1/storefront/invoices/status/:invoiceId', {\n invoiceId: normalizedInvoiceId,\n })\n );\n if (!response.success) {\n return {\n success: false,\n message: response.message,\n };\n }\n\n if (!response.data?.invoice?.status) {\n return {\n success: false,\n message: 'Invalid invoice status response',\n };\n }\n\n return {\n success: true,\n data: { status: response.data.invoice.status },\n };\n}\n","/**\n * Pages Module\n *\n * API methods for public pages.\n */\n\nimport { get } from '../core/client';\nimport { getConfig } from '../core/config';\nimport { buildEndpoint } from '../core/endpoint';\nimport type { SDKResponse, Page } from '../types';\n\ninterface PagesResponse {\n pages: Page[];\n}\n\ninterface PageResponse {\n page: Page;\n}\n\nconst PAGES_CACHE_TTL = 5 * 60 * 1000;\n\n/**\n * Get all public pages for the store\n */\nexport async function getPages(): Promise<SDKResponse<Page[]>> {\n const config = getConfig();\n const response = await get<PagesResponse>(\n buildEndpoint('/v1/storefront/shops/name/:storeSlug/pages', {\n storeSlug: config.storeSlug,\n }),\n {\n cache: {\n key: `pages:${config.storeSlug}`,\n ttl: PAGES_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data) {\n return {\n success: true,\n data: response.data.pages,\n };\n }\n\n return {\n success: false,\n message: response.message,\n };\n}\n\n/**\n * Get a public page by slug\n */\nexport async function getPage(slug: string): Promise<SDKResponse<Page>> {\n const config = getConfig();\n const response = await get<PageResponse>(\n buildEndpoint('/v1/storefront/shops/name/:storeSlug/pages/:slug', {\n storeSlug: config.storeSlug,\n slug,\n }),\n {\n cache: {\n key: `page:${config.storeSlug}:${slug}`,\n ttl: PAGES_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data) {\n return {\n success: true,\n data: response.data.page,\n };\n }\n\n return {\n success: false,\n message: response.message,\n };\n}\n","/**\n * Navigation Module\n *\n * API methods for menus and navigation.\n */\n\nimport { get } from '../core/client';\nimport { getConfig } from '../core/config';\nimport { buildEndpoint } from '../core/endpoint';\nimport type { SDKResponse, Menu } from '../types';\nimport type { NavigationMenuSlot } from '@shoppex/contracts/navigation';\nimport { getNavigationMenuTitles } from '@shoppex/contracts/navigation';\n\ninterface MenusResponse {\n menus: Menu[];\n}\n\ninterface MenuResponse {\n menu: Menu;\n}\n\nconst NAVIGATION_CACHE_TTL = 5 * 60 * 1000;\n\n/**\n * Get all menus for the store\n */\nexport async function getMenus(): Promise<SDKResponse<Menu[]>> {\n const config = getConfig();\n const response = await get<MenusResponse>(\n buildEndpoint('/v1/storefront/shops/name/:storeSlug/menus', {\n storeSlug: config.storeSlug,\n }),\n {\n cache: {\n key: `menus:${config.storeSlug}`,\n ttl: NAVIGATION_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data) {\n return {\n success: true,\n data: response.data.menus,\n };\n }\n\n return {\n success: false,\n message: response.message,\n };\n}\n\n/**\n * Get a menu by its exact title.\n */\nexport async function getMenuByTitle(title: string): Promise<SDKResponse<Menu>> {\n const config = getConfig();\n const response = await get<MenuResponse>(\n buildEndpoint('/v1/storefront/shops/name/:storeSlug/menus/:title', {\n storeSlug: config.storeSlug,\n title,\n }),\n {\n cache: {\n key: `menu:${config.storeSlug}:${title}`,\n ttl: NAVIGATION_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data) {\n return {\n success: true,\n data: response.data.menu,\n };\n }\n\n return {\n success: false,\n message: response.message,\n };\n}\n\n/**\n * Get a menu by its exact title.\n */\nexport async function getMenu(title: string): Promise<SDKResponse<Menu>> {\n return getMenuByTitle(title);\n}\n\n/**\n * Get a menu by canonical slot. The backend resolves legacy menu titles too.\n */\nexport async function getMenuBySlot(slot: NavigationMenuSlot): Promise<SDKResponse<Menu>> {\n const config = getConfig();\n const response = await get<MenuResponse>(\n buildEndpoint('/v1/storefront/shops/name/:storeSlug/menus/:title', {\n storeSlug: config.storeSlug,\n title: slot,\n }),\n {\n cache: {\n key: `menu-slot:${config.storeSlug}:${slot}`,\n ttl: NAVIGATION_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data) {\n return {\n success: true,\n data: response.data.menu,\n };\n }\n\n return {\n success: false,\n message: response.message,\n };\n}\n\nexport function getMenuSlotTitles(slot: NavigationMenuSlot): string[] {\n return getNavigationMenuTitles(slot);\n}\n","/**\n * UTM attribution for storefront page views.\n *\n * Campaign parameters only appear on the landing URL, but a visitor usually\n * browses several pages before doing anything interesting. Without persistence\n * every page after the first would be attributed to \"direct\" and the numbers\n * would understate every campaign.\n *\n * Last-touch: a fresh set of parameters replaces the stored one, matching what\n * merchants expect from analytics tools — the most recent campaign gets credit.\n * Navigating without parameters keeps whatever was stored.\n */\n\nconst STORAGE_PREFIX = 'shoppex:utm:';\nconst TTL_MS = 30 * 24 * 60 * 60 * 1000;\n\nconst UTM_KEYS = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content'] as const;\n\ntype UtmKey = (typeof UTM_KEYS)[number];\n\nexport type UtmParameters = Partial<Record<UtmKey, string>>;\n\ninterface StoredAttribution {\n utm: UtmParameters;\n /** Epoch ms of the last touch, used for TTL expiry. */\n at: number;\n}\n\n/** Values are merchant-supplied and land in a text column; keep them bounded. */\nconst MAX_VALUE_LENGTH = 255;\n\nfunction readFromUrl(search: string): UtmParameters {\n let params: URLSearchParams;\n try {\n params = new URLSearchParams(search);\n } catch {\n return {};\n }\n\n const utm: UtmParameters = {};\n for (const key of UTM_KEYS) {\n const value = params.get(key)?.trim();\n if (value) {\n utm[key] = value.slice(0, MAX_VALUE_LENGTH);\n }\n }\n return utm;\n}\n\nfunction storageKey(storeSlug: string): string {\n return `${STORAGE_PREFIX}${storeSlug}`;\n}\n\nfunction readStored(storeSlug: string): UtmParameters {\n try {\n const raw = window.localStorage.getItem(storageKey(storeSlug));\n if (!raw) return {};\n\n const parsed = JSON.parse(raw) as StoredAttribution;\n if (!parsed || typeof parsed.at !== 'number' || typeof parsed.utm !== 'object') return {};\n if (Date.now() - parsed.at > TTL_MS) {\n window.localStorage.removeItem(storageKey(storeSlug));\n return {};\n }\n\n const utm: UtmParameters = {};\n for (const key of UTM_KEYS) {\n const value = parsed.utm?.[key];\n if (typeof value === 'string' && value.length > 0) {\n utm[key] = value.slice(0, MAX_VALUE_LENGTH);\n }\n }\n return utm;\n } catch {\n // Private mode, quota errors, corrupt JSON — attribution is best-effort and\n // must never break a page view.\n return {};\n }\n}\n\nfunction writeStored(storeSlug: string, utm: UtmParameters): void {\n try {\n const payload: StoredAttribution = { utm, at: Date.now() };\n window.localStorage.setItem(storageKey(storeSlug), JSON.stringify(payload));\n } catch {\n // Ignore: the current page view still reports the parameters it just read.\n }\n}\n\n/**\n * Resolves the UTM parameters to report for the current page view.\n *\n * Reads the current URL first; when it carries any campaign parameter that set\n * wins and is persisted. Otherwise the stored set is returned unchanged.\n *\n * @returns the parameters, or undefined when there is nothing to report\n */\nexport function resolveUtmParameters(storeSlug: string): UtmParameters | undefined {\n if (typeof window === 'undefined' || typeof window.location === 'undefined') {\n return undefined;\n }\n\n const fromUrl = readFromUrl(window.location.search);\n if (Object.keys(fromUrl).length > 0) {\n writeStored(storeSlug, fromUrl);\n return fromUrl;\n }\n\n const stored = readStored(storeSlug);\n return Object.keys(stored).length > 0 ? stored : undefined;\n}\n","import { isInitialized, getConfig } from '../core/config';\nimport { buildEndpoint } from '../core/endpoint';\nimport { getStorefrontConnectionId } from '../core/telemetry';\nimport { resolveUtmParameters } from '../core/attribution';\n\nexport async function trackPageView(cartValue?: number, itemCount?: number): Promise<void> {\n if (!isInitialized()) return;\n if (typeof document === 'undefined') return;\n\n const config = getConfig();\n const connectionId = getStorefrontConnectionId(config.storeSlug);\n\n try {\n const endpoint = buildEndpoint('/v1/storefront/shops/:storeSlug/ping', {\n storeSlug: config.storeSlug,\n });\n await fetch(`${config.apiBaseUrl}${endpoint}`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n referer: document.referrer || undefined,\n cart_value: cartValue ?? undefined,\n item_count: itemCount ?? undefined,\n connection_id: connectionId ?? undefined,\n utm: resolveUtmParameters(config.storeSlug),\n }),\n });\n } catch {\n // Intentionally silent - analytics should never block the user experience\n }\n}\n","import { get, post } from '../core/client';\nimport { getConfig, getShopId, isInitialized } from '../core/config';\nimport { buildEndpoint } from '../core/endpoint';\nimport { getStorefrontConnectionId } from '../core/telemetry';\nimport { resolveUtmParameters } from '../core/attribution';\nimport type { SDKResponse, StorefrontOnlineUsers, StorefrontRecentSales } from '../types';\n\n/**\n * Anonymized recent-sales feed for storefront social proof (product title +\n * relative age only — never buyer identity). Empty items when the shop has no\n * recent completed orders.\n */\nexport async function getStorefrontRecentSales(): Promise<SDKResponse<StorefrontRecentSales>> {\n if (!isInitialized()) {\n return { success: false, message: 'SDK not initialized' };\n }\n\n const config = getConfig();\n const shopId = getShopId();\n const endpoint = shopId\n ? buildEndpoint('/v1/storefront/shops/id/:id/recent-sales', { id: shopId })\n : buildEndpoint('/v1/storefront/shops/:storeSlug/recent-sales', {\n storeSlug: config.storeSlug,\n });\n\n return get<StorefrontRecentSales>(endpoint, {\n cache: false,\n retries: 0,\n timeout: 5000,\n });\n}\n\nexport async function getStorefrontOnlineUsers(): Promise<SDKResponse<StorefrontOnlineUsers>> {\n if (!isInitialized()) {\n return { success: false, message: 'SDK not initialized' };\n }\n\n const config = getConfig();\n const shopId = getShopId();\n const endpoint = shopId\n ? buildEndpoint('/v1/storefront/shops/id/:id/online-users', { id: shopId })\n : buildEndpoint('/v1/storefront/shops/:storeSlug/online-users', {\n storeSlug: config.storeSlug,\n });\n\n return get<StorefrontOnlineUsers>(endpoint, {\n cache: false,\n retries: 0,\n timeout: 5000,\n });\n}\n\nexport async function touchStorefrontPresence(): Promise<SDKResponse<{ pong: string }>> {\n if (!isInitialized()) {\n return { success: false, message: 'SDK not initialized' };\n }\n if (typeof document === 'undefined') {\n return { success: false, message: 'Document is not available' };\n }\n\n const config = getConfig();\n const shopId = getShopId();\n const endpoint = shopId\n ? buildEndpoint('/v1/storefront/shops/id/:id/ping', { id: shopId })\n : buildEndpoint('/v1/storefront/shops/:storeSlug/ping', {\n storeSlug: config.storeSlug,\n });\n\n return post<{ pong: string }>(\n endpoint,\n {\n referer: document.referrer || undefined,\n connection_id: getStorefrontConnectionId(config.storeSlug) ?? undefined,\n utm: resolveUtmParameters(config.storeSlug),\n },\n {\n retries: 0,\n timeout: 5000,\n },\n );\n}\n","/**\n * Formatting Utilities\n */\n\nimport { getConfig } from '../core/config';\nimport { CATALOG_UNIT_PRICE_FORMAT_OPTIONS } from '@shoppex/contracts/catalog-unit-price';\n\nexport function createFormatter(\n currency?: string,\n locale?: string\n): Intl.NumberFormat {\n const config = getConfig();\n\n return new Intl.NumberFormat(locale ?? config.locale ?? 'en-US', {\n style: 'currency',\n currency: currency ?? config.currency ?? 'USD',\n ...CATALOG_UNIT_PRICE_FORMAT_OPTIONS,\n });\n}\n\nexport function formatPrice(\n amount: number | string,\n currency?: string,\n locale?: string\n): string {\n const numericAmount = typeof amount === 'string' ? parseFloat(amount) : amount;\n if (Number.isNaN(numericAmount)) {\n return createFormatter(currency, locale).format(0);\n }\n return createFormatter(currency, locale).format(numericAmount);\n}\n","import type { ThemeConfig, ResolvedThemeSettings } from '../types/theme-config';\nimport { get } from '../core/client';\nimport { buildEndpoint } from '../core/endpoint';\n\ntype JsonRecord = Record<string, unknown>;\n\nexport interface PublishedBuilderSettings {\n version: number;\n revision: number;\n theme: {\n content: JsonRecord;\n layout: JsonRecord;\n style_slots: JsonRecord;\n pages?: unknown[];\n terms?: JsonRecord;\n [key: string]: unknown;\n };\n [key: string]: unknown;\n}\n\nexport interface PublishedThemeSettingsPayload {\n settings: ResolvedThemeSettings;\n builder_settings: PublishedBuilderSettings | null;\n content: JsonRecord;\n style_slots: JsonRecord;\n}\n\nfunction isRecord(value: unknown): value is JsonRecord {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction normalizePublishedBuilderSettings(value: unknown): PublishedBuilderSettings | null {\n if (!isRecord(value) || !isRecord(value.theme)) {\n return null;\n }\n\n return {\n ...value,\n version: typeof value.version === 'number' ? value.version : 0,\n revision: typeof value.revision === 'number' ? value.revision : 0,\n theme: {\n ...value.theme,\n content: isRecord(value.theme.content) ? value.theme.content : {},\n layout: isRecord(value.theme.layout) ? value.theme.layout : {},\n style_slots: isRecord(value.theme.style_slots) ? value.theme.style_slots : {},\n ...(Array.isArray(value.theme.pages) ? { pages: value.theme.pages } : {}),\n ...(isRecord(value.theme.terms) ? { terms: value.theme.terms } : {}),\n },\n };\n}\n\nfunction normalizePublishedThemeSettingsPayload(value: unknown): PublishedThemeSettingsPayload | null {\n if (!isRecord(value)) {\n return null;\n }\n\n return {\n settings: isRecord(value.settings) ? value.settings as ResolvedThemeSettings : {},\n builder_settings: normalizePublishedBuilderSettings(value.builder_settings),\n content: isRecord(value.content) ? value.content : {},\n style_slots: isRecord(value.style_slots) ? value.style_slots : {},\n };\n}\n\nexport async function fetchPublishedBuilderSettings(\n shopSlug: string\n): Promise<PublishedThemeSettingsPayload | null> {\n const result = await get<PublishedThemeSettingsPayload>(\n buildEndpoint('/v1/storefront/themes/builder/published/:shopSlug', { shopSlug })\n );\n\n return result.success && result.data ? normalizePublishedThemeSettingsPayload(result.data) : null;\n}\n\nexport async function fetchPublishedThemeSettings(\n shopSlug: string\n): Promise<ResolvedThemeSettings | null> {\n const payload = await fetchPublishedBuilderSettings(shopSlug);\n return payload ? payload.settings : null;\n}\n\nexport function resolveDefaults(config: ThemeConfig): ResolvedThemeSettings {\n const resolved: ResolvedThemeSettings = {};\n for (const [category, fields] of Object.entries(config.settings)) {\n resolved[category] = {};\n for (const [key, field] of Object.entries(fields)) {\n resolved[category][key] = field.default;\n }\n }\n return resolved;\n}\n\nexport function mergeSettings(\n defaults: ResolvedThemeSettings,\n overrides: Partial<ResolvedThemeSettings>\n): ResolvedThemeSettings {\n const merged = { ...defaults };\n for (const [category, fields] of Object.entries(overrides)) {\n if (fields) {\n merged[category] = { ...merged[category], ...fields };\n }\n }\n return merged;\n}\n","/**\n * Shoppex Storefront SDK\n *\n * Usage:\n * ```html\n * <script src=\"https://cdn.shoppex.io/sdk/v1.0/shoppex.umd.js\"></script>\n * <script>\n * shoppex.init('my-store');\n *\n * shoppex.getStore().then(store => console.log(store));\n * shoppex.addToCart('product-id', 'variant-id', 2);\n * shoppex.checkout();\n * </script>\n * ```\n */\n\nimport { initConfig, isInitialized, getConfig } from './core/config';\nimport { getTypedClient } from './core/typed-client';\nimport type { ShoppexInitOptions } from './types';\n\n// Re-export types\nexport * from './types';\nexport * from './core/errors';\nexport {\n buildStorefrontCustomFieldPayload,\n isStorefrontCheckboxCustomFieldValueChecked,\n normalizeStorefrontCustomFields,\n validateStorefrontCustomFieldValue,\n} from './utils/storefront-custom-fields';\nexport type { StorefrontCustomField } from './utils/storefront-custom-fields';\nexport {\n isProductInStock,\n isProductOutOfStock,\n isVariantOutOfStock,\n resolveDisplayStock,\n resolveVariantStockValue,\n} from './utils/storefront-stock';\nexport {\n buildStorefrontProductLookup,\n getMergedStorefrontProducts,\n getStorefrontGroupProducts,\n} from './utils/storefront-catalog';\nexport {\n stripHtmlFromText,\n normalizeSearchQuery,\n collectProductSearchHaystack,\n productMatchesSearchQuery,\n groupMatchesSearchQuery,\n filterProductsBySearchQuery,\n searchMergedStorefrontCatalog,\n searchMergedStorefrontCatalogItems,\n} from './utils/storefront-search';\nexport type { StorefrontSearchFilterOptions, StorefrontCatalogSearchItem } from './utils/storefront-search';\nexport {\n buildStorefrontContactMessage,\n resolveStorefrontApiBaseUrl,\n resolveStorefrontSocialLinks,\n submitStorefrontContactTicket,\n} from './utils/storefront-contact';\nexport type {\n StorefrontContactTicketInput,\n StorefrontContactTicketResult,\n StorefrontSocialLinks,\n} from './utils/storefront-contact';\nexport type {\n BlockDefinition,\n BlockInstance,\n PageLayout,\n ThemeConfig,\n ThemeBlockManifest,\n SettingField,\n SectionDefinition,\n ResolvedThemeSettings,\n} from './types/theme-config';\nexport type { PublishedBuilderSettings, PublishedThemeSettingsPayload } from './modules/theme';\nexport type { NavigationMenuSlot } from '@shoppex/contracts/navigation';\nexport {\n CATALOG_UNIT_PRICE_DECIMAL_PLACES,\n CATALOG_UNIT_PRICE_FORMAT_OPTIONS,\n PAYABLE_AMOUNT_DECIMAL_PLACES,\n roundPayableAmount,\n} from '@shoppex/contracts/catalog-unit-price';\n\n// Store module\nimport {\n getStore,\n getStorefront,\n getStoreLogoUrl,\n getStoreBannerUrl,\n resolveStoreByDomain,\n} from './modules/store';\n\n// Products module\nimport { getProducts, getProduct, getCategories, getStorefrontProductsPage } from './modules/products';\n\n// Cart module\nimport {\n getCart,\n getCartItemCount,\n getCartCoupon,\n getCartCouponSource,\n setCartCoupon,\n clearCartCoupon,\n addToCart,\n setCartItem,\n updateCartItem,\n removeFromCart,\n clearCart,\n createCartBackup,\n restoreCartFromBackup,\n mergeBaskets,\n moveBasketItem,\n getCartStats,\n validateCartIntegrity,\n quoteCart,\n resolveCartLineId,\n} from './modules/cart';\n// resolveCartLineId is re-exported on the default shoppex object below (not only type-only).\nexport { computeCartLineId, ensureCartLineId } from './utils/cart-line-id';\nexport type { CartLineIdentityInput } from './utils/cart-line-id';\n\n// Checkout module\nimport { checkout, buildCheckoutUrl, buildCheckoutUrlSync } from './modules/checkout';\nexport type { CheckoutOptions, CheckoutResult } from './modules/checkout';\nexport { CheckoutCreateError } from './modules/checkout';\nimport { mountCheckoutChallenge } from './modules/checkout-challenge';\nexport { mountCheckoutChallenge } from './modules/checkout-challenge';\nexport type {\n CheckoutChallengeCallbacks,\n CheckoutChallengeFrame,\n} from './modules/checkout-challenge';\nexport type { SearchOptions } from './modules/search';\n\n// Affiliate module\nimport {\n applyAffiliateCode,\n captureAffiliateFromUrl,\n getAffiliateCode,\n setAffiliateCode,\n clearAffiliateCode,\n trackAffiliateEvent,\n validateAffiliateCode,\n} from './modules/affiliates';\n\n// Coupons module\nimport { validateCoupon } from './modules/coupons';\n\n// Reviews module\nimport { getShopReviews, getShopReviewsPage } from './modules/reviews';\nexport { getShopReviewsPage } from './modules/reviews';\n\n// Customer module\nimport {\n requestOtp,\n verifyOtp,\n logout,\n me,\n dashboard,\n orders,\n order,\n loyalty,\n redeemLoyaltyPoints,\n warranties,\n claimWarranty,\n resetLicenseHwid,\n subscriptionBillingHistory,\n cancelSubscription,\n pauseSubscription,\n resumeSubscription,\n favorites,\n addFavorite,\n removeFavorite,\n affiliate,\n affiliateStats,\n createTicket,\n ticket,\n replyToTicket,\n updateProfile,\n updateAvatar,\n removeAvatar,\n emailPreferences,\n updateEmailPreferences,\n sessions,\n revokeSession,\n revokeAllSessions,\n reseller,\n applyForReseller,\n enrollAsReseller,\n acceptResellerInvite,\n resellerCatalog,\n quoteResellerOrder,\n resellerOrders,\n resellerOrder,\n resellerWallet,\n resellerApiKeys,\n} from './modules/customer';\nexport {\n requestOtp,\n verifyOtp,\n logout,\n me,\n dashboard,\n orders,\n order,\n loyalty,\n redeemLoyaltyPoints,\n warranties,\n claimWarranty,\n resetLicenseHwid,\n subscriptionBillingHistory,\n cancelSubscription,\n pauseSubscription,\n resumeSubscription,\n favorites,\n addFavorite,\n removeFavorite,\n affiliate,\n affiliateStats,\n createTicket,\n ticket,\n replyToTicket,\n updateProfile,\n updateAvatar,\n removeAvatar,\n emailPreferences,\n updateEmailPreferences,\n sessions,\n revokeSession,\n revokeAllSessions,\n reseller,\n applyForReseller,\n enrollAsReseller,\n acceptResellerInvite,\n resellerCatalog,\n quoteResellerOrder,\n resellerOrders,\n resellerOrder,\n resellerWallet,\n resellerApiKeys,\n} from './modules/customer';\nexport type {\n CustomerTicketPayload,\n CustomerProfilePatch,\n CustomerSubscriptionCancelOptions,\n CustomerEmailPreferencesPatch,\n ResellerOrderItem,\n ResellerCatalogQuery,\n ResellerOrdersQuery,\n} from './modules/customer';\n\n// Search module\nimport { searchProducts, searchCatalogItems } from './modules/search';\n\n// Invoices module\nimport { getInvoice, getInvoiceStatus } from './modules/invoices';\n\n// Pages module\nimport { getPages, getPage } from './modules/pages';\n\n// Navigation module\nimport { getMenus, getMenu, getMenuBySlot, getMenuByTitle, getMenuSlotTitles } from './modules/navigation';\n\n// Analytics module\nimport { trackPageView } from './modules/analytics';\nimport { getStorefrontOnlineUsers, getStorefrontRecentSales, touchStorefrontPresence } from './modules/presence';\n\n// Format utilities\nimport { createFormatter, formatPrice } from './utils/format';\nimport { clearCache, invalidateCache, getCacheStats } from './core/cache';\nimport { fetchPublishedBuilderSettings, fetchPublishedThemeSettings, resolveDefaults, mergeSettings } from './modules/theme';\n\nexport { fetchPublishedBuilderSettings, fetchPublishedThemeSettings, resolveDefaults, mergeSettings } from './modules/theme';\nexport { trackPageView } from './modules/analytics';\nexport { getStorefrontOnlineUsers, getStorefrontRecentSales, touchStorefrontPresence } from './modules/presence';\nexport { getMenus, getMenu, getMenuBySlot, getMenuByTitle, getMenuSlotTitles } from './modules/navigation';\n\n/**\n * Initialize the SDK with a store slug\n */\nfunction init(storeSlug: string, options?: ShoppexInitOptions): void;\nfunction init(options: ShoppexInitOptions & { storeId: string }): void;\nfunction init(\n storeSlugOrOptions: string | (ShoppexInitOptions & { storeId: string }),\n options?: ShoppexInitOptions\n): void {\n if (typeof storeSlugOrOptions === 'string') {\n initConfig(storeSlugOrOptions, options);\n } else {\n initConfig(storeSlugOrOptions.storeId, storeSlugOrOptions);\n }\n}\n\n/**\n * Shoppex SDK instance\n */\nexport const shoppex = {\n // Initialization\n init,\n isInitialized,\n getConfig,\n\n // Typed OpenAPI client — drop to this when you need an endpoint the\n // high-level modules below do not cover yet.\n client: getTypedClient,\n\n // Store\n getStore,\n getStorefront,\n getStoreLogoUrl,\n getStoreBannerUrl,\n resolveStoreByDomain,\n\n // Products\n getProducts,\n getStorefrontProductsPage,\n getProduct,\n getCategories,\n\n // Cart\n getCart,\n getCartItemCount,\n getCartCoupon,\n getCartCouponSource,\n setCartCoupon,\n clearCartCoupon,\n addToCart,\n setCartItem,\n updateCartItem,\n removeFromCart,\n clearCart,\n createCartBackup,\n restoreCartFromBackup,\n mergeBaskets,\n moveBasketItem,\n getCartStats,\n validateCartIntegrity,\n quoteCart,\n resolveCartLineId,\n\n // Checkout\n checkout,\n buildCheckoutUrl,\n buildCheckoutUrlSync,\n mountCheckoutChallenge,\n\n // Affiliates\n captureAffiliateFromUrl,\n validateAffiliateCode,\n applyAffiliateCode,\n getAffiliateCode,\n setAffiliateCode,\n clearAffiliateCode,\n trackAffiliateEvent,\n\n // Coupons\n validateCoupon,\n\n // Reviews\n getShopReviews,\n getShopReviewsPage,\n\n // Customer account\n requestOtp,\n verifyOtp,\n logout,\n me,\n dashboard,\n orders,\n order,\n loyalty,\n redeemLoyaltyPoints,\n warranties,\n claimWarranty,\n resetLicenseHwid,\n subscriptionBillingHistory,\n cancelSubscription,\n pauseSubscription,\n resumeSubscription,\n favorites,\n addFavorite,\n removeFavorite,\n affiliate,\n affiliateStats,\n createTicket,\n ticket,\n replyToTicket,\n updateProfile,\n updateAvatar,\n removeAvatar,\n emailPreferences,\n updateEmailPreferences,\n sessions,\n revokeSession,\n revokeAllSessions,\n reseller,\n applyForReseller,\n enrollAsReseller,\n acceptResellerInvite,\n resellerCatalog,\n quoteResellerOrder,\n resellerOrders,\n resellerOrder,\n resellerWallet,\n resellerApiKeys,\n\n // Search\n searchProducts,\n searchCatalogItems,\n\n // Invoices\n getInvoice,\n getInvoiceStatus,\n\n // Pages\n getPages,\n getPage,\n\n // Navigation\n getMenus,\n getMenu,\n getMenuBySlot,\n getMenuByTitle,\n getMenuSlotTitles,\n\n // Analytics\n trackPageView,\n getStorefrontOnlineUsers,\n getStorefrontRecentSales,\n touchStorefrontPresence,\n\n // Formatting\n createFormatter,\n formatPrice,\n\n // Cache\n clearCache,\n invalidateCache,\n getCacheStats,\n\n // Theme settings helpers\n fetchPublishedBuilderSettings,\n fetchPublishedThemeSettings,\n resolveDefaults,\n mergeSettings,\n};\n\n// Default export for ES modules\nexport default shoppex;\n\n// UMD global exposure — never clobber an already-initialized client. Theme\n// artifacts can load multiple SDK chunks; a late bundle must not reset init.\nif (typeof window !== 'undefined') {\n const w = window as unknown as { shoppex?: typeof shoppex };\n if (!w.shoppex?.isInitialized?.()) {\n w.shoppex = shoppex;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAuBA,IAAM,QAA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A;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAGA;AAAA,EACA;AAAA;AAAA,EAGA;AAAA,EACA;AAAA;AAAA,EAGA;AAAA,EACA;AAAA;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAGA;AAAA,EACA;AAAA;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAGA,IAAO,cAAQ;AAIf,IAAI,OAAO,WAAW,aAAa;AACjC,QAAM,IAAI;AACV,MAAI,CAAC,EAAE,SAAS,gBAAgB,GAAG;AACjC,MAAE,UAAU;AAAA,EACd;AACF;","names":["fetch","init","request","error","url","final","joiner","url","record","HexColorSchema","url","storageKey","cache","url","record","url","hashString","record","email","normalizeAffiliateCode","record","cachedShopId","record","email","STORAGE_PREFIX","isRecord"]}