@konfiqo/storefront-sdk 0.6.0 → 0.6.1
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.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -764,7 +764,7 @@ async function renderTurnstile(element, siteKey, options) {
|
|
|
764
764
|
}
|
|
765
765
|
|
|
766
766
|
// src/index.ts
|
|
767
|
-
var SDK_VERSION = "0.6.
|
|
767
|
+
var SDK_VERSION = "0.6.1";
|
|
768
768
|
// Annotate the CommonJS export names for ESM import in node:
|
|
769
769
|
0 && (module.exports = {
|
|
770
770
|
BUYER_IP_HEADER,
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/errors.ts","../src/client.ts","../src/theme.ts","../src/payment.ts","../src/money.ts","../src/host-pixels.ts","../src/cart-storage.ts","../src/turnstile.ts"],"sourcesContent":["/** Version of the Storefront SDK package. */\nexport const SDK_VERSION = '0.6.0';\n\nexport {\n createStorefrontClient,\n DEFAULT_TIMEOUT_MS,\n PUBLISHABLE_KEY_HEADER,\n STOREFRONT_KEY_HEADER,\n BUYER_IP_HEADER,\n TURNSTILE_TOKEN_HEADER,\n} from './client';\nexport type {\n CheckoutOptions,\n RequestCodeOptions,\n RequestOptions,\n StorefrontClient,\n StorefrontClientOptions,\n} from './client';\nexport { StorefrontError, isStorefrontError } from './errors';\nexport type {\n AnyStorefrontError,\n BuyerDetailField,\n CheckoutMissing,\n StorefrontApiErrorCode,\n StorefrontClientErrorCode,\n StorefrontErrorCode,\n StorefrontErrorDetails,\n StorefrontErrorDetailsMap,\n ValidationIssue,\n} from './errors';\nexport type * from './models';\nexport { THEME_FONTS, isKnownThemeSection } from './theme';\nexport type {\n CategoryGridSection,\n FeaturedProductsSection,\n HeroSection,\n KnownThemeSection,\n RichTextSection,\n ThemeColors,\n ThemeFont,\n ThemeFooter,\n ThemeHomepage,\n ThemeLink,\n ThemeSection,\n ThemeSocial,\n ThemeV1,\n UnknownThemeSection,\n} from './theme';\nexport { mountPayment } from './payment';\nexport type {\n ClosedPaymentMount,\n EmbeddedPaymentMount,\n MountPaymentOptions,\n PaymentMount,\n PaymentPresentation,\n RedirectPaymentMount,\n UnsupportedPaymentMount,\n} from './payment';\nexport { formatMoney } from './money';\nexport { cookiesForHost, onDefaultDomain, pixelsForHost } from './host-pixels';\nexport {\n cartIdKey,\n clearCartId,\n cookieCartStorage,\n loadCartId,\n saveCartId,\n} from './cart-storage';\nexport type { CartIdStorage, CookieJar } from './cart-storage';\nexport {\n TURNSTILE_SCRIPT_URL,\n loadTurnstile,\n renderTurnstile,\n} from './turnstile';\nexport type {\n RenderTurnstileOptions,\n TurnstileApi,\n TurnstileWidget,\n} from './turnstile';\n","import type { CartLine, ShippingOption } from './models';\n\n/** `checkout_incomplete`: what the cart still lacks. */\nexport type CheckoutMissing =\n | 'lines'\n | 'customer'\n | 'identityNumber'\n | 'shippingAddress'\n | 'shippingOption';\n\n/**\n * `invalid_buyer_details`: the buyer detail the payment provider refused.\n * Address fields come as `shippingAddress.<field>` / `billingAddress.<field>`.\n */\nexport type BuyerDetailField =\n | 'name'\n | 'surname'\n | 'email'\n | 'phone'\n | 'identityNumber'\n | `shippingAddress.${string}`\n | `billingAddress.${string}`;\n\n/** One validation problem of an `invalid_request`. */\nexport interface ValidationIssue {\n /** Dotted path of the field (`phone`, `shipping.city`, …). */\n path: string;\n /** What is wrong with it (never echoes the submitted value). */\n message: string;\n}\n\n/**\n * The extras each error code carries (`StorefrontError.details`). Codes\n * not listed here carry no details (`undefined`).\n */\nexport interface StorefrontErrorDetailsMap {\n /** Prices or shipping changed: show the new totals, then check out again. */\n cart_changed: {\n lines: CartLine[];\n subtotalMinor: number;\n shippingMinor: number;\n totalMinor: number;\n shippingOptions: ShippingOption[];\n };\n /**\n * A personalization text is refused (400, no details) or, at checkout\n * (409), a line's stored text no longer satisfies the product's rule:\n * `lineIds` are those lines. Remove the line and add it again with a\n * valid text.\n */\n invalid_personalization: { lineIds?: string[] };\n /** These variants cannot be bought (no longer sold, or not enough units). */\n out_of_stock: { variantIds: string[] };\n /** Collect what is missing, then check out again. */\n checkout_incomplete: { missing: CheckoutMissing[] };\n /** Let the buyer fix `field`, then check out again. */\n invalid_buyer_details: { field: BuyerDetailField };\n /** Only `available` units can be added. */\n insufficient_stock: { available: number };\n /** The request body or query failed validation. */\n invalid_request: { issues: ValidationIssue[] };\n /** The cart can no longer change: start a new cart. */\n cart_read_only: { status: 'ordered' | 'expired' };\n /** Throttled. `retryAfter` = seconds to wait, when the response said so. */\n rate_limited: { retryAfter?: number };\n /** No response within `timeoutMs`. */\n timeout: { timeoutMs: number };\n /** The server answered an error code this SDK version does not know. */\n unknown_error: { error: string | null };\n}\n\n/** Error codes of the Storefront API (the `error` field of an error response). */\nexport type StorefrontApiErrorCode =\n | 'store_not_found'\n | 'origin_not_allowed'\n | 'invalid_request'\n | 'invalid_buyer_ip'\n | 'catalog_unavailable'\n | 'product_not_found'\n | 'content_not_found'\n | 'cart_not_found'\n | 'variant_not_found'\n | 'line_not_found'\n | 'insufficient_stock'\n | 'quantity_out_of_range'\n | 'too_many_lines'\n | 'invalid_shipping_option'\n | 'cart_read_only'\n | 'checkout_in_progress'\n | 'checkout_incomplete'\n | 'cart_changed'\n | 'invalid_personalization'\n | 'out_of_stock'\n | 'amount_out_of_range'\n | 'nothing_to_pay'\n | 'invalid_buyer_details'\n | 'payment_unavailable'\n | 'checkout_unavailable'\n | 'order_not_found'\n | 'order_unavailable'\n | 'media_not_found'\n | 'media_unavailable'\n | 'challenge_required'\n | 'challenge_failed'\n | 'challenge_unavailable'\n | 'too_many_open_orders'\n | 'not_signed_in'\n | 'invalid_code'\n | 'profile_required'\n | 'too_many_code_requests'\n | 'invalid_recovery_token'\n | 'cart_not_recoverable'\n | 'unavailable';\n\n/**\n * Codes the SDK assigns itself:\n * - `rate_limited` — HTTP 429 without a known `error` code (the throttler);\n * - `unauthorized` — HTTP 401 without a code (a wrong `trustedStorefrontKey`);\n * - `http_error` — any other non-2xx response without an `error` code;\n * - `unknown_error` — an `error` code this SDK version does not know (in `details.error`);\n * - `invalid_response` — a 2xx response that is not JSON;\n * - `network_error` — no readable response: the API was unreachable (DNS,\n * TLS, offline), or, in a browser, the origin is allowed by no store;\n * - `timeout` — no response within `timeoutMs`;\n * - `aborted` — the caller's `signal` aborted the request.\n */\nexport type StorefrontClientErrorCode =\n | 'rate_limited'\n | 'unauthorized'\n | 'http_error'\n | 'unknown_error'\n | 'invalid_response'\n | 'network_error'\n | 'timeout'\n | 'aborted';\n\n/** Every code a {@link StorefrontError} can have. */\nexport type StorefrontErrorCode =\n StorefrontApiErrorCode | StorefrontClientErrorCode;\n\n/** The `details` type of an error code (`undefined` for codes without extras). */\nexport type StorefrontErrorDetails<C extends StorefrontErrorCode> =\n C extends keyof StorefrontErrorDetailsMap\n ? StorefrontErrorDetailsMap[C]\n : undefined;\n\nconst API_CODES: ReadonlySet<string> = new Set<StorefrontApiErrorCode>([\n 'store_not_found',\n 'origin_not_allowed',\n 'invalid_request',\n 'invalid_buyer_ip',\n 'catalog_unavailable',\n 'product_not_found',\n 'content_not_found',\n 'cart_not_found',\n 'variant_not_found',\n 'line_not_found',\n 'insufficient_stock',\n 'quantity_out_of_range',\n 'too_many_lines',\n 'invalid_shipping_option',\n 'cart_read_only',\n 'checkout_in_progress',\n 'checkout_incomplete',\n 'cart_changed',\n 'invalid_personalization',\n 'out_of_stock',\n 'amount_out_of_range',\n 'nothing_to_pay',\n 'invalid_buyer_details',\n 'payment_unavailable',\n 'checkout_unavailable',\n 'order_not_found',\n 'order_unavailable',\n 'media_not_found',\n 'media_unavailable',\n 'challenge_required',\n 'challenge_failed',\n 'challenge_unavailable',\n 'too_many_open_orders',\n 'not_signed_in',\n 'invalid_code',\n 'profile_required',\n 'too_many_code_requests',\n 'invalid_recovery_token',\n 'cart_not_recoverable',\n 'unavailable',\n]);\n\n/**\n * Marks every {@link StorefrontError}. A global (`Symbol.for`) symbol, so\n * an error thrown by one installed copy of the SDK is recognised by another\n * (e.g. the React package resolving its own copy), where `instanceof` fails.\n */\nconst ERROR_BRAND = Symbol.for('@konfiqo/storefront-sdk/error');\n\n/**\n * Every failure of a client call: an API error response, a throttle, a\n * timeout or a transport failure. Switch on `code`, never on `message`.\n *\n * To get `details` typed per code, narrow with {@link isStorefrontError}\n * (which yields the {@link AnyStorefrontError} union) and `switch (e.code)`,\n * or test one code with `e.is('cart_changed')`.\n */\nexport class StorefrontError<\n C extends StorefrontErrorCode = StorefrontErrorCode,\n> extends Error {\n /** The API `error` code, or one of the SDK's own codes. */\n readonly code: C;\n /** HTTP status; `0` when no response arrived (`network_error`, `timeout`). */\n readonly status: number;\n /** The code's extras (see {@link StorefrontErrorDetailsMap}). */\n readonly details: StorefrontErrorDetails<C>;\n\n /**\n * @param code - the error code\n * @param status - the HTTP status (`0` without a response)\n * @param message - a human-readable description (not for display logic)\n * @param details - the code's extras\n * @param options - `cause`: the underlying error, if any\n */\n constructor(\n code: C,\n status: number,\n message: string,\n details: StorefrontErrorDetails<C>,\n options?: { cause?: unknown },\n ) {\n super(message, options);\n this.name = 'StorefrontError';\n this.code = code;\n this.status = status;\n this.details = details;\n Object.defineProperty(this, ERROR_BRAND, { value: true });\n }\n\n /** Whether this error has `code`; narrows `details` to that code's extras. */\n is<K extends StorefrontErrorCode>(code: K): this is StorefrontError<K> {\n return (this.code as StorefrontErrorCode) === code;\n }\n}\n\n/**\n * The union of {@link StorefrontError} by code: after narrowing `code`\n * (e.g. in a `switch`), `details` has that code's type.\n */\nexport type AnyStorefrontError = {\n [C in StorefrontErrorCode]: StorefrontError<C>;\n}[StorefrontErrorCode];\n\n/**\n * Whether `e` is a {@link StorefrontError}, as the code-discriminated union.\n * Also true for an error from another copy of this SDK (checked by a global\n * brand, not only `instanceof`).\n */\nexport function isStorefrontError(e: unknown): e is AnyStorefrontError {\n return (\n e instanceof StorefrontError ||\n (typeof e === 'object' &&\n e !== null &&\n (e as Record<symbol, unknown>)[ERROR_BRAND] === true)\n );\n}\n\nconst isObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === 'object' && v !== null && !Array.isArray(v);\n\n/** Seconds from a `Retry-After` value (delta-seconds or an HTTP date). */\nfunction parseRetryAfter(value: string | null): number | undefined {\n if (value === null) return undefined;\n const trimmed = value.trim();\n if (/^\\d+$/.test(trimmed)) return Number(trimmed);\n const at = Date.parse(trimmed);\n if (Number.isNaN(at)) return undefined;\n return Math.max(0, Math.ceil((at - Date.now()) / 1000));\n}\n\n/**\n * Builds the error for a non-2xx response from its status, body (parsed\n * JSON, or undefined) and headers. Internal.\n */\nexport function errorFromResponse(\n status: number,\n body: unknown,\n headers: Headers,\n): AnyStorefrontError {\n const b = isObject(body) ? body : {};\n const message =\n typeof b.message === 'string' && b.message !== ''\n ? b.message\n : `Storefront API request failed (HTTP ${status})`;\n\n const error = typeof b.error === 'string' ? b.error : null;\n // A 429 with a known code (`too_many_open_orders`) is that code; the\n // throttler's 429 carries none.\n if (status === 429 && (error === null || !API_CODES.has(error))) {\n // The throttler names its header per limit (`Retry-After`,\n // `Retry-After-ip`); when both come, the longer wait is the real one.\n const waits = [\n parseRetryAfter(headers.get('retry-after')),\n parseRetryAfter(headers.get('retry-after-ip')),\n ].filter((w): w is number => w !== undefined);\n const retryAfter = waits.length > 0 ? Math.max(...waits) : undefined;\n return new StorefrontError(\n 'rate_limited',\n status,\n message,\n retryAfter === undefined ? {} : { retryAfter },\n );\n }\n\n if (error === null) {\n if (status === 401)\n return new StorefrontError('unauthorized', status, message, undefined);\n return new StorefrontError('http_error', status, message, undefined);\n }\n if (!API_CODES.has(error)) {\n return new StorefrontError('unknown_error', status, message, { error });\n }\n const code = error as StorefrontApiErrorCode;\n return apiError(code, status, message, b);\n}\n\nconst arr = <T>(v: unknown): T[] => (Array.isArray(v) ? (v as T[]) : []);\nconst n = (v: unknown): number => (typeof v === 'number' ? v : 0);\n\nfunction apiError(\n code: StorefrontApiErrorCode,\n status: number,\n message: string,\n b: Record<string, unknown>,\n): AnyStorefrontError {\n switch (code) {\n case 'cart_changed':\n return new StorefrontError(code, status, message, {\n lines: arr<CartLine>(b.lines),\n subtotalMinor: n(b.subtotalMinor),\n shippingMinor: n(b.shippingMinor),\n totalMinor: n(b.totalMinor),\n shippingOptions: arr<ShippingOption>(b.shippingOptions),\n });\n case 'invalid_personalization':\n return new StorefrontError(\n code,\n status,\n message,\n Array.isArray(b.lineIds) ? { lineIds: arr<string>(b.lineIds) } : {},\n );\n case 'out_of_stock':\n return new StorefrontError(code, status, message, {\n variantIds: arr<string>(b.variantIds),\n });\n case 'checkout_incomplete':\n return new StorefrontError(code, status, message, {\n missing: arr<CheckoutMissing>(b.missing),\n });\n case 'invalid_buyer_details':\n return new StorefrontError(code, status, message, {\n field: String(b.field ?? '') as BuyerDetailField,\n });\n case 'insufficient_stock':\n return new StorefrontError(code, status, message, {\n available: n(b.available),\n });\n case 'invalid_request':\n return new StorefrontError(code, status, message, {\n issues: arr<ValidationIssue>(b.issues),\n });\n case 'cart_read_only':\n return new StorefrontError(code, status, message, {\n status: b.status === 'ordered' ? 'ordered' : 'expired',\n });\n default:\n return new StorefrontError(\n code,\n status,\n message,\n undefined,\n ) as AnyStorefrontError;\n }\n}\n","import { StorefrontError, errorFromResponse } from './errors';\nimport type {\n AddLineInput,\n AddressInput,\n Account,\n AccountProfileInput,\n AccountSession,\n Cart,\n CategoryList,\n CheckoutResult,\n CustomerInput,\n Order,\n Product,\n ProductListQuery,\n ProductPage,\n SavedAddress,\n SavedAddressInput,\n ShippingOptionList,\n Store,\n StoreContent,\n UpdateLineInput,\n} from './models';\n\n/** Default request timeout, milliseconds. */\nexport const DEFAULT_TIMEOUT_MS = 15_000;\n\n/** Header carrying the publishable key on every request. */\nexport const PUBLISHABLE_KEY_HEADER = 'x-konfiqo-publishable-key';\n/** Header carrying the trusted storefront key (server-side only). */\nexport const STOREFRONT_KEY_HEADER = 'x-konfiqo-storefront-key';\n/** Header carrying the store's server key (server-side only). */\nexport const SERVER_KEY_HEADER = 'x-konfiqo-server-key';\n/** Header carrying the checkout challenge token (checkout only). */\nexport const TURNSTILE_TOKEN_HEADER = 'x-konfiqo-turnstile-token';\n/** Header carrying the buyer's IP (only with a server key or the trusted storefront key). */\nexport const BUYER_IP_HEADER = 'x-konfiqo-buyer-ip';\n\n/** Per-call options, accepted as the last argument of every method. */\nexport interface RequestOptions {\n /**\n * Aborts the request: it rejects with code `aborted`. Combined with the\n * client timeout (whichever comes first wins).\n */\n signal?: AbortSignal;\n /**\n * **Server-side only.** A `Cookie` header to forward, so a server-rendered\n * storefront can call the account routes as the buyer: pass the incoming\n * request's `cookie` header (or just `konfiqo_session=<value>`). Browsers\n * ignore a `Cookie` header set from script; there the session cookie rides\n * along automatically (`credentials: 'include'`).\n */\n cookie?: string;\n}\n\n/** Options of `account.requestCode`. */\nexport interface RequestCodeOptions extends RequestOptions {\n /**\n * The challenge token (Cloudflare Turnstile), required when the store\n * asks for one (`store.checkoutChallenge`). Single-use. Sent as\n * `x-konfiqo-turnstile-token`.\n */\n turnstileToken?: string;\n}\n\n/** Options of `carts.checkout`. */\nexport interface CheckoutOptions extends RequestOptions {\n /**\n * The checkout challenge token (Cloudflare Turnstile), required when\n * `store.checkoutChallenge` is set. Single-use: get a new one (reset the\n * widget) for every checkout call. Sent as `x-konfiqo-turnstile-token`.\n */\n turnstileToken?: string;\n}\n\n/** Options of {@link createStorefrontClient}. */\nexport interface StorefrontClientOptions {\n /**\n * The Storefront API base: `https://<store domain>/api` (or the relative\n * `/api` in a same-origin browser app). Requests go to `${baseUrl}/v1/...`,\n * so do not include `/v1`.\n */\n baseUrl: string;\n /** The store's publishable key (`pk_live_…` / `pk_test_…`). Public. */\n publishableKey: string;\n /** A `fetch` implementation; defaults to the global `fetch`. */\n fetch?: typeof fetch;\n /** Per-request timeout in milliseconds (default {@link DEFAULT_TIMEOUT_MS}). */\n timeoutMs?: number;\n /**\n * **Server-side only.** The shared storefront key that lets a server-side\n * renderer report the real buyer IP (`buyerIp`), so throttling and the\n * payment provider see the buyer instead of the server. Sent as\n * `x-konfiqo-storefront-key`. Constructing a client with it where\n * `window` exists throws: never ship this key to a browser.\n */\n trustedStorefrontKey?: string;\n /**\n * **Server-side only.** The store's own server key, minted by the store\n * operator. It lets the seller's server report the real buyer IP\n * (`buyerIp`). Sent as `x-konfiqo-server-key` next to the publishable\n * key. Needs `buyerIp`, cannot be combined with `trustedStorefrontKey`,\n * and constructing a client with it in a browser throws.\n */\n serverKey?: string;\n /**\n * The buyer's IP address, sent as `x-konfiqo-buyer-ip`. Required with\n * `serverKey` or `trustedStorefrontKey`, ignored without one. Create one\n * client per incoming request on the server.\n */\n buyerIp?: string;\n}\n\n/**\n * A typed client of the Storefront API (`/v1`).\n *\n * Every method returns the response body, or rejects with a\n * {@link StorefrontError}. Nothing is retried: whether to retry is the\n * caller's decision, because writes are not safely repeatable — in\n * particular `carts.checkout` on a cart whose order failed places a\n * **new** order, so a blind retry could open a second payment.\n */\nexport interface StorefrontClient {\n /**\n * `GET /v1/content/:key`: a piece of store content as a renderable\n * Markdoc tree. Rejects `content_not_found` (404) for an unknown key.\n */\n getContent(key: string, options?: RequestOptions): Promise<StoreContent>;\n /** Store information. */\n readonly store: {\n /** `GET /v1/store`: name, language, currency, logo, theme, contact, legal texts, shipping rules. */\n get(options?: RequestOptions): Promise<Store>;\n };\n /** Categories. */\n readonly categories: {\n /** `GET /v1/categories`: the active category tree. */\n list(options?: RequestOptions): Promise<CategoryList>;\n };\n /** Products. */\n readonly products: {\n /** `GET /v1/products`: a page of products, optionally filtered. */\n list(\n query?: ProductListQuery,\n options?: RequestOptions,\n ): Promise<ProductPage>;\n /** `GET /v1/products/:slug`. Rejects with `product_not_found`. */\n get(slug: string, options?: RequestOptions): Promise<Product>;\n };\n /** Carts. Every cart write answers the updated cart. */\n readonly carts: {\n /** `POST /v1/carts`: a new, empty cart. */\n create(options?: RequestOptions): Promise<Cart>;\n /**\n * `POST /v1/carts/recover`: turns the `t` token of an abandoned-cart\n * e-mail link into a **new** cart with the same lines (no buyer data).\n * Rejects `invalid_recovery_token` (400) or `cart_not_recoverable` (410:\n * the cart was ordered, expired or deleted).\n */\n recover(\n token: string,\n options?: RequestOptions,\n ): Promise<{ cartId: string }>;\n /** `GET /v1/carts/:id`. Also reopens a cart whose payment failed. */\n get(cartId: string, options?: RequestOptions): Promise<Cart>;\n /** `POST /v1/carts/:id/lines`: adds units of a variant. */\n addLine(\n cartId: string,\n input: AddLineInput,\n options?: RequestOptions,\n ): Promise<Cart>;\n /**\n * `PATCH /v1/carts/:id/lines/:lineId`: sets a line's quantity. `lineId`\n * is `CartLine.id`; a variant id still matches a line without text.\n */\n updateLine(\n cartId: string,\n lineId: string,\n input: UpdateLineInput,\n options?: RequestOptions,\n ): Promise<Cart>;\n /** `DELETE /v1/carts/:id/lines/:lineId`: removes a line (`CartLine.id`). */\n removeLine(\n cartId: string,\n lineId: string,\n options?: RequestOptions,\n ): Promise<Cart>;\n /** `PUT /v1/carts/:id/customer`: sets the buyer. */\n setCustomer(\n cartId: string,\n input: CustomerInput,\n options?: RequestOptions,\n ): Promise<Cart>;\n /** `PUT /v1/carts/:id/address`: sets the shipping (and billing) address. */\n setAddress(\n cartId: string,\n input: AddressInput,\n options?: RequestOptions,\n ): Promise<Cart>;\n /** `GET /v1/carts/:id/shipping-options`: the options this cart can use. */\n shippingOptions(\n cartId: string,\n options?: RequestOptions,\n ): Promise<ShippingOptionList>;\n /** `PUT /v1/carts/:id/shipping-option`: selects a shipping option by id. */\n setShippingOption(\n cartId: string,\n optionId: string,\n options?: RequestOptions,\n ): Promise<Cart>;\n /**\n * `POST /v1/carts/:id/checkout`: places the order (or re-opens payment\n * for the cart's order) and answers how to present payment. Keep the\n * returned `token`: it is returned only once. Not retried.\n *\n * Aborting (`signal`) only stops waiting: the server may still place\n * the order. Read the cart again before showing a result.\n *\n * When `store.checkoutChallenge` is set, pass a fresh\n * `turnstileToken` (see `renderTurnstile`); tokens are single-use, so\n * reset the widget after every call. Re-opening payment on an already\n * ordered cart needs no token.\n */\n checkout(\n cartId: string,\n options?: CheckoutOptions,\n ): Promise<CheckoutResult>;\n };\n /** Buyer order status. */\n readonly orders: {\n /** `GET /v1/orders/:id?token=`: the order, for the buyer holding its token. */\n get(\n orderId: string,\n token: string,\n options?: RequestOptions,\n ): Promise<Order>;\n };\n /**\n * The signed-in buyer's account. Sign-in is by an e-mailed one-time code;\n * the session is an HttpOnly cookie (`konfiqo_session`) the API sets on the\n * store origin, so these calls send `credentials: 'include'`. On a server,\n * forward the buyer's cookie with the `cookie` call option.\n */\n readonly account: {\n /**\n * `POST /v1/account/code`: e-mails a 6-digit code. Resolves the same for\n * any address (202); rejects `too_many_code_requests` (429),\n * `challenge_required` / `challenge_failed`, `invalid_request`.\n */\n requestCode(email: string, options?: RequestCodeOptions): Promise<void>;\n /**\n * `POST /v1/account/session`: signs in with the code. A wrong, spent or\n * expired code rejects `invalid_code` (401).\n */\n signIn(\n email: string,\n code: string,\n options?: RequestOptions,\n ): Promise<AccountSession>;\n /** `DELETE /v1/account/session`: signs out (always succeeds). */\n signOut(options?: RequestOptions): Promise<void>;\n /**\n * `GET /v1/account[?page=]`: profile, saved addresses and a page of\n * orders (20 per page, newest first). Rejects `not_signed_in` (401).\n */\n get(page?: number, options?: RequestOptions): Promise<Account>;\n /**\n * `PUT /v1/account/profile`: saves name, surname and a Turkish mobile\n * phone. Creates the buyer's record on first save.\n */\n updateProfile(\n profile: AccountProfileInput,\n options?: RequestOptions,\n ): Promise<void>;\n /**\n * `PUT /v1/account/addresses`: replaces the saved addresses (at most 5,\n * at most one default). Resolves the list as stored (ids filled in).\n * Rejects `profile_required` (409) until a profile is saved.\n */\n saveAddresses(\n addresses: SavedAddressInput[],\n options?: RequestOptions,\n ): Promise<SavedAddress[]>;\n };\n /** Catalog images. */\n readonly media: {\n /**\n * The absolute URL of a storage key (product `image`, store `logo`,\n * theme `logo` / `favicon` / section `image`), usable in `<img src>`:\n * `${baseUrl}/v1/media/<key, each segment encoded>?pk=<publishable key>`.\n *\n * @throws TypeError (`invalid_path_segment`) when a key segment is\n * empty, `.` or `..`.\n */\n url(key: string): string;\n };\n}\n\ntype Method = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n\n/**\n * One encoded path segment. `encodeURIComponent` leaves `.` and `..` as\n * they are, and URL normalisation would turn them into another route, so\n * those (and an empty segment) are refused.\n */\nfunction seg(v: string): string {\n if (typeof v !== 'string' || v === '' || v === '.' || v === '..') {\n throw new TypeError(\n `invalid_path_segment: ${JSON.stringify(v)} is not a valid path segment`,\n );\n }\n return encodeURIComponent(v);\n}\n\n/** Whether this host looks like a browser or a web worker. */\nfunction isBrowserLike(): boolean {\n const g = globalThis as { importScripts?: unknown };\n return (\n typeof window !== 'undefined' ||\n typeof document !== 'undefined' ||\n (typeof self !== 'undefined' && typeof g.importScripts === 'function')\n );\n}\n\n/**\n * Creates a Storefront API client.\n *\n * @throws TypeError when `baseUrl` or `publishableKey` is empty, when\n * `serverKey` or `trustedStorefrontKey` is given without `buyerIp`, when\n * both keys are given together, or when either key is given in a\n * browser-like host (`window` or `document` defined, or a web worker).\n * Hosts that define `window` on a server (jsdom, Electron renderers,\n * React Native) are refused too: keep these keys in a plain server process.\n */\nexport function createStorefrontClient(\n options: StorefrontClientOptions,\n): StorefrontClient {\n const baseUrl = options.baseUrl?.trim().replace(/\\/+$/, '');\n if (!baseUrl)\n throw new TypeError('createStorefrontClient: baseUrl is required');\n const publishableKey = options.publishableKey?.trim();\n if (!publishableKey)\n throw new TypeError('createStorefrontClient: publishableKey is required');\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n if (!(timeoutMs > 0) || !Number.isFinite(timeoutMs)) {\n throw new TypeError(\n 'createStorefrontClient: timeoutMs must be a positive number',\n );\n }\n\n const baseHeaders: Record<string, string> = {\n [PUBLISHABLE_KEY_HEADER]: publishableKey,\n };\n if (\n options.serverKey !== undefined &&\n options.trustedStorefrontKey !== undefined\n ) {\n throw new TypeError(\n 'createStorefrontClient: serverKey and trustedStorefrontKey cannot be used together',\n );\n }\n if (options.serverKey !== undefined) {\n if (isBrowserLike()) {\n throw new TypeError(\n 'createStorefrontClient: serverKey must never be used in a browser',\n );\n }\n const buyerIp = options.buyerIp?.trim();\n if (!buyerIp) {\n throw new TypeError(\n 'createStorefrontClient: buyerIp is required with serverKey',\n );\n }\n baseHeaders[SERVER_KEY_HEADER] = options.serverKey;\n baseHeaders[BUYER_IP_HEADER] = buyerIp;\n }\n if (options.trustedStorefrontKey !== undefined) {\n if (isBrowserLike()) {\n throw new TypeError(\n 'createStorefrontClient: trustedStorefrontKey is server-only and must never be used in a browser',\n );\n }\n const buyerIp = options.buyerIp?.trim();\n if (!buyerIp) {\n throw new TypeError(\n 'createStorefrontClient: buyerIp is required with trustedStorefrontKey',\n );\n }\n baseHeaders[STOREFRONT_KEY_HEADER] = options.trustedStorefrontKey;\n baseHeaders[BUYER_IP_HEADER] = buyerIp;\n }\n\n async function request<T>(\n method: Method,\n path: () => string,\n body?: unknown,\n callOptions?: RequestOptions,\n extraHeaders: Record<string, string> = {},\n flags: { credentials?: boolean; emptyOk?: boolean } = {},\n ): Promise<T> {\n const url = `${baseUrl}${path()}`;\n const callerSignal = callOptions?.signal;\n if (callerSignal?.aborted) throw abortError(callerSignal);\n // Resolved per call (not at construction) so a polyfilled global works.\n // Called detached: a browser `fetch` must not be invoked on another `this`.\n const doFetch = options.fetch ?? globalThis.fetch;\n const headers: Record<string, string> = {\n ...baseHeaders,\n ...extraHeaders,\n };\n if (callOptions?.cookie) headers.cookie = callOptions.cookie;\n const init: RequestInit = { method, headers };\n if (flags.credentials) init.credentials = 'include';\n if (body !== undefined) {\n headers['content-type'] = 'application/json';\n init.body = JSON.stringify(body);\n }\n const controller = new AbortController();\n init.signal = controller.signal;\n let timedOut = false;\n // Raced as well as aborted: a custom `fetch` that ignores the signal\n // still cannot hold the caller past the timeout.\n let onTimeout: (e: StorefrontError) => void = () => {};\n const deadline = new Promise<never>((_, reject) => {\n onTimeout = reject;\n });\n deadline.catch(() => {});\n const timer = setTimeout(() => {\n timedOut = true;\n onTimeout(transportError(undefined, true, timeoutMs));\n controller.abort();\n }, timeoutMs);\n const onCallerAbort = () => {\n onTimeout(abortError(callerSignal!));\n controller.abort();\n };\n callerSignal?.addEventListener('abort', onCallerAbort, { once: true });\n\n try {\n let res: Response;\n let text: string;\n try {\n res = await Promise.race([doFetch(url, init), deadline]);\n text = await Promise.race([res.text(), deadline]);\n } catch (e) {\n if (e instanceof StorefrontError) throw e;\n throw transportError(e, timedOut, timeoutMs);\n }\n let parsed: unknown;\n let isJson = false;\n if (text !== '') {\n try {\n parsed = JSON.parse(text);\n isJson = true;\n } catch {\n parsed = undefined;\n }\n }\n if (!res.ok) throw errorFromResponse(res.status, parsed, res.headers);\n if (!isJson && flags.emptyOk && text === '') return undefined as T;\n if (!isJson) {\n throw new StorefrontError(\n 'invalid_response',\n res.status,\n 'Storefront API answered a non-JSON body',\n undefined,\n );\n }\n return parsed as T;\n } finally {\n clearTimeout(timer);\n callerSignal?.removeEventListener('abort', onCallerAbort);\n }\n }\n\n const get = <T>(path: () => string, options?: RequestOptions) =>\n request<T>('GET', path, undefined, options);\n const acct = { credentials: true } as const;\n const send = <T>(\n method: Method,\n path: string,\n body: unknown,\n o?: RequestOptions,\n extra: Record<string, string> = {},\n emptyOk = false,\n ) => request<T>(method, () => path, body, o, extra, { ...acct, emptyOk });\n const cart = (id: string) => `/v1/carts/${seg(id)}`;\n\n return {\n getContent: (key, o) =>\n get<StoreContent>(() => `/v1/content/${seg(key)}`, o),\n store: {\n get: (o) => get<Store>(() => '/v1/store', o),\n },\n categories: {\n list: (o) => get<CategoryList>(() => '/v1/categories', o),\n },\n products: {\n list: (query = {}, o) =>\n get<ProductPage>(() => {\n const params = new URLSearchParams();\n if (query.category !== undefined)\n params.set('category', query.category);\n if (query.q !== undefined) params.set('q', query.q);\n if (query.page !== undefined) params.set('page', String(query.page));\n if (query.pageSize !== undefined)\n params.set('pageSize', String(query.pageSize));\n const qs = params.toString();\n return `/v1/products${qs ? `?${qs}` : ''}`;\n }, o),\n get: (slug, o) => get<Product>(() => `/v1/products/${seg(slug)}`, o),\n },\n carts: {\n create: (o) => request<Cart>('POST', () => '/v1/carts', undefined, o),\n recover: (token, o) =>\n request<{ cartId: string }>(\n 'POST',\n () => '/v1/carts/recover',\n { token },\n o,\n ),\n get: (cartId, o) => get<Cart>(() => cart(cartId), o),\n addLine: (cartId, input, o) =>\n request<Cart>(\n 'POST',\n () => `${cart(cartId)}/lines`,\n {\n variantId: input.variantId,\n quantity: input.quantity,\n ...(input.personalization !== undefined && {\n personalization: input.personalization,\n }),\n },\n o,\n ),\n updateLine: (cartId, lineId, input, o) =>\n request<Cart>(\n 'PATCH',\n () => `${cart(cartId)}/lines/${seg(lineId)}`,\n { quantity: input.quantity },\n o,\n ),\n removeLine: (cartId, lineId, o) =>\n request<Cart>(\n 'DELETE',\n () => `${cart(cartId)}/lines/${seg(lineId)}`,\n undefined,\n o,\n ),\n setCustomer: (cartId, input, o) =>\n request<Cart>('PUT', () => `${cart(cartId)}/customer`, input, o),\n setAddress: (cartId, input, o) =>\n request<Cart>('PUT', () => `${cart(cartId)}/address`, input, o),\n shippingOptions: (cartId, o) =>\n get<ShippingOptionList>(() => `${cart(cartId)}/shipping-options`, o),\n setShippingOption: (cartId, optionId, o) =>\n request<Cart>(\n 'PUT',\n () => `${cart(cartId)}/shipping-option`,\n { id: optionId },\n o,\n ),\n checkout: (cartId, o) =>\n request<CheckoutResult>(\n 'POST',\n () => `${cart(cartId)}/checkout`,\n undefined,\n o,\n o?.turnstileToken\n ? { [TURNSTILE_TOKEN_HEADER]: o.turnstileToken }\n : {},\n ),\n },\n orders: {\n get: (orderId, token, o) =>\n get<Order>(\n () => `/v1/orders/${seg(orderId)}?token=${encodeURIComponent(token)}`,\n o,\n ),\n },\n account: {\n requestCode: (email, o) =>\n send<void>(\n 'POST',\n '/v1/account/code',\n { email },\n o,\n o?.turnstileToken\n ? { [TURNSTILE_TOKEN_HEADER]: o.turnstileToken }\n : {},\n true,\n ),\n signIn: (email, code, o) =>\n send<AccountSession>('POST', '/v1/account/session', { email, code }, o),\n signOut: (o) =>\n send<void>('DELETE', '/v1/account/session', undefined, o, {}, true),\n get: (page, o) =>\n send<Account>(\n 'GET',\n page === undefined\n ? '/v1/account'\n : `/v1/account?page=${encodeURIComponent(String(page))}`,\n undefined,\n o,\n ),\n updateProfile: (profile, o) =>\n send<void>(\n 'PUT',\n '/v1/account/profile',\n {\n name: profile.name,\n surname: profile.surname,\n phone: profile.phone,\n },\n o,\n {},\n true,\n ),\n saveAddresses: async (addresses, o) =>\n (\n await send<{ addresses: SavedAddress[] }>(\n 'PUT',\n '/v1/account/addresses',\n { addresses },\n o,\n )\n ).addresses,\n },\n media: {\n url: (key) =>\n `${baseUrl}/v1/media/${key.split('/').map(seg).join('/')}?pk=${encodeURIComponent(publishableKey)}`,\n },\n };\n}\n\n/** The caller aborted the request (`options.signal`). */\nfunction abortError(signal: AbortSignal): StorefrontError {\n return new StorefrontError(\n 'aborted',\n 0,\n 'Storefront API request was aborted',\n undefined,\n { cause: signal.reason },\n );\n}\n\n/** A fetch / body-read failure as `timeout` or `network_error`. */\nfunction transportError(\n e: unknown,\n timedOut: boolean,\n timeoutMs: number,\n): StorefrontError {\n if (timedOut) {\n return new StorefrontError(\n 'timeout',\n 0,\n `Storefront API did not answer within ${timeoutMs} ms`,\n { timeoutMs },\n { cause: e },\n );\n }\n return new StorefrontError(\n 'network_error',\n 0,\n 'Storefront API could not be reached',\n undefined,\n {\n cause: e,\n },\n );\n}\n","/**\n * Store theme, `schemaVersion: 1` (the commerce module's \"Store settings\n * JSON\"). The Storefront API passes the theme through **as stored**: it is\n * not validated, so every field is optional and a renderer must tolerate\n * missing values, wrong types and keys it does not know. Image fields are\n * tenant storage keys — turn them into URLs with `client.media.url(key)`.\n */\nexport interface ThemeV1 {\n /** `1` for this shape. Anything else: render defaults. */\n schemaVersion?: number;\n /** Storage key of the logo (the same key as the store's `logo`). */\n logo?: string | null;\n /** Storage key of the favicon. */\n favicon?: string | null;\n /** Theme colors, CSS color strings (normally `#rrggbb`). */\n colors?: ThemeColors;\n /** One of {@link THEME_FONTS}; an unknown value means \"use the default font\". */\n font?: ThemeFont | (string & {});\n /** The homepage, as ordered sections. */\n homepage?: ThemeHomepage;\n /** Footer links and social profiles. */\n footer?: ThemeFooter;\n /** Keys this SDK version does not know are kept as stored. */\n [key: string]: unknown;\n}\n\n/** Theme colors. Each is a CSS color string; any may be missing. */\nexport interface ThemeColors {\n /** Primary brand color. */\n primary?: string;\n /** Accent (links, highlights). */\n accent?: string;\n /** Page background. */\n background?: string;\n /** Body text. */\n text?: string;\n /** Unknown color keys are kept as stored. */\n [key: string]: unknown;\n}\n\n/** The fonts a v1 theme may name. */\nexport const THEME_FONTS = [\n 'inter',\n 'roboto',\n 'open-sans',\n 'lato',\n 'poppins',\n] as const;\n\n/** A font a v1 theme may name. */\nexport type ThemeFont = (typeof THEME_FONTS)[number];\n\n/** The homepage: sections in display order. */\nexport interface ThemeHomepage {\n /**\n * Sections in display order. May contain section types this SDK does not\n * know (skip them) — narrow with {@link isKnownThemeSection}.\n */\n sections?: ThemeSection[];\n /** Unknown homepage keys are kept as stored. */\n [key: string]: unknown;\n}\n\n/** A call-to-action link. */\nexport interface ThemeLink {\n /** Visible text. */\n label?: string;\n /** Target URL or path. */\n href?: string;\n}\n\n/** `hero`: a large banner with an optional image and call to action. */\nexport interface HeroSection {\n /** Discriminator. */\n type: 'hero';\n /** Storage key of the banner image. */\n image?: string | null;\n /** Headline. */\n title?: string;\n /** Sub-headline. */\n subtitle?: string;\n /** Optional call-to-action button. */\n cta?: ThemeLink;\n}\n\n/** `featuredProducts`: a hand-picked list of products. */\nexport interface FeaturedProductsSection {\n /** Discriminator. */\n type: 'featuredProducts';\n /** Section heading. */\n title?: string;\n /** Product slugs, in display order. Slugs no longer sold are skipped. */\n productSlugs?: string[];\n}\n\n/** `categoryGrid`: a grid of category tiles. */\nexport interface CategoryGridSection {\n /** Discriminator. */\n type: 'categoryGrid';\n /** Category slugs, in display order. Unknown slugs are skipped. */\n categorySlugs?: string[];\n}\n\n/**\n * `richText`: seller-written text. Render it as text or sanitized\n * markdown — never as raw HTML.\n */\nexport interface RichTextSection {\n /** Discriminator. */\n type: 'richText';\n /** The text. */\n content?: string;\n}\n\n/** A section type this SDK knows how to describe. */\nexport type KnownThemeSection =\n HeroSection | FeaturedProductsSection | CategoryGridSection | RichTextSection;\n\n/** A section of a type this SDK version does not know; renderers skip it. */\nexport interface UnknownThemeSection {\n /** The stored type. */\n type: string;\n /** Other stored keys. */\n [key: string]: unknown;\n}\n\n/** A homepage section as stored: a known section or an unknown one. */\nexport type ThemeSection = KnownThemeSection | UnknownThemeSection;\n\nconst KNOWN_SECTION_TYPES: ReadonlySet<string> = new Set([\n 'hero',\n 'featuredProducts',\n 'categoryGrid',\n 'richText',\n]);\n\n/**\n * Whether a stored section is one of the known types. After this guard a\n * `switch (section.type)` narrows to the exact section shape.\n */\nexport function isKnownThemeSection(\n section: unknown,\n): section is KnownThemeSection {\n return (\n typeof section === 'object' &&\n section !== null &&\n typeof (section as { type?: unknown }).type === 'string' &&\n KNOWN_SECTION_TYPES.has((section as { type: string }).type)\n );\n}\n\n/** Social profile URLs; only filled ones are stored. */\nexport interface ThemeSocial {\n /** Instagram profile URL. */\n instagram?: string;\n /** Facebook page URL. */\n facebook?: string;\n /** X profile URL. */\n x?: string;\n /** TikTok profile URL. */\n tiktok?: string;\n /** YouTube channel URL. */\n youtube?: string;\n /** Unknown networks are kept as stored. */\n [key: string]: unknown;\n}\n\n/** Footer configuration. */\nexport interface ThemeFooter {\n /** Footer links, in display order. */\n links?: ThemeLink[];\n /** Social profiles. */\n social?: ThemeSocial;\n /** Unknown footer keys are kept as stored. */\n [key: string]: unknown;\n}\n","import type {\n CheckoutEmbed,\n CheckoutResult,\n ClosedCheckoutPage,\n EmbeddedCheckoutResult,\n RedirectCheckoutResult,\n ClosedCheckoutResult,\n} from './models';\n\n/**\n * What {@link mountPayment} renders: a checkout result, or just its\n * presentation part.\n */\nexport type PaymentPresentation =\n | Pick<EmbeddedCheckoutResult, 'presentation' | 'embed'>\n | Pick<RedirectCheckoutResult, 'presentation' | 'url'>\n | Pick<ClosedCheckoutResult, 'presentation' | 'page'>;\n\n/** Options of {@link mountPayment}. */\nexport interface MountPaymentOptions {\n /**\n * Called for `presentation: \"closed\"` with the page to show (`paid`,\n * `cancelled`, `processing`, …). Typically: go to the order status page.\n */\n onClosed?: (page: ClosedCheckoutPage) => void;\n}\n\n/** The provider form is in the element. */\nexport interface EmbeddedPaymentMount {\n /** Discriminator. */\n kind: 'embedded';\n /** Removes the form from the element. */\n unmount(): void;\n}\n\n/** The browser is navigating to the provider's payment page. */\nexport interface RedirectPaymentMount {\n /** Discriminator. */\n kind: 'redirect';\n /** Where the browser was sent. */\n url: string;\n}\n\n/** Payment cannot be opened; `onClosed` was called. */\nexport interface ClosedPaymentMount {\n /** Discriminator. */\n kind: 'closed';\n /** The page to show. */\n page: ClosedCheckoutPage;\n}\n\n/**\n * The embed has a `kind` this SDK version cannot render. Nothing was put\n * in the element; show a fallback (e.g. \"payment unavailable\").\n */\nexport interface UnsupportedPaymentMount {\n /** Discriminator. */\n kind: 'unsupported';\n /** The embed kind that was not understood. */\n embedKind: string;\n}\n\n/** The result of {@link mountPayment}, discriminated by `kind`. */\nexport type PaymentMount =\n | EmbeddedPaymentMount\n | RedirectPaymentMount\n | ClosedPaymentMount\n | UnsupportedPaymentMount;\n\ninterface MountedForm {\n content: string;\n nodes: Node[];\n unmount: () => void;\n}\n\n/** What each element currently holds, so a repeat mount is a no-op. */\nconst mounted = new WeakMap<Element, MountedForm>();\n\n/**\n * Presents payment from a checkout result. Card data never touches your\n * page's code: the form is the provider's own, or a redirect.\n *\n * - `embedded` (`iyzico-checkout-form`): puts the provider's HTML into\n * `element` and re-creates every `<script>` in it so it executes\n * (`innerHTML` alone never runs scripts). Idempotent per element:\n * mounting the same content again does nothing, other content replaces\n * the previous form — scripts are never injected twice.\n * - `redirect`: top-level navigation to the provider page\n * (`location.assign`). Only `http:` / `https:` URLs are followed.\n * - `closed`: calls `onClosed(page)`.\n *\n * Browser only (needs a DOM).\n *\n * @throws TypeError for a redirect URL that is not `http(s)`.\n */\nexport function mountPayment(\n element: HTMLElement,\n presentation: PaymentPresentation | CheckoutResult,\n options: MountPaymentOptions = {},\n): PaymentMount {\n switch (presentation.presentation) {\n case 'embedded':\n return mountEmbedded(element, presentation.embed);\n case 'redirect': {\n const url = presentation.url;\n let protocol: string;\n try {\n protocol = new URL(url).protocol;\n } catch {\n protocol = '';\n }\n if (protocol !== 'https:' && protocol !== 'http:') {\n throw new TypeError('mountPayment: redirect URL must be http(s)');\n }\n const view = element.ownerDocument.defaultView;\n if (!view) throw new TypeError('mountPayment: element has no window');\n view.location.assign(url);\n return { kind: 'redirect', url };\n }\n case 'closed':\n options.onClosed?.(presentation.page);\n return { kind: 'closed', page: presentation.page };\n }\n}\n\nfunction mountEmbedded(\n element: HTMLElement,\n embed: CheckoutEmbed,\n): EmbeddedPaymentMount | UnsupportedPaymentMount {\n if (\n embed.kind !== 'iyzico-checkout-form' ||\n typeof embed.content !== 'string'\n ) {\n return { kind: 'unsupported', embedKind: String(embed.kind) };\n }\n const content = embed.content;\n const current = mounted.get(element);\n if (\n current &&\n current.content === content &&\n current.nodes.every((n) => n.parentNode === element)\n ) {\n return { kind: 'embedded', unmount: current.unmount };\n }\n\n element.replaceChildren();\n // The provider's own checkout form (from the payments service). It must\n // run its scripts, so it cannot be sanitised; it is the only HTML this\n // SDK ever injects.\n element.innerHTML = content;\n const doc = element.ownerDocument;\n for (const inert of Array.from(element.querySelectorAll('script'))) {\n const live = doc.createElement('script');\n for (const attr of Array.from(inert.attributes)) {\n live.setAttribute(attr.name, attr.value);\n }\n // Dynamically inserted external scripts are async by default; keep\n // document order like the provider's markup expects.\n if (live.hasAttribute('src')) live.async = false;\n live.text = inert.text;\n inert.replaceWith(live);\n }\n const entry: MountedForm = {\n content,\n nodes: Array.from(element.childNodes),\n unmount: () => {\n // A stale handle never removes a newer form.\n if (mounted.get(element) !== entry) return;\n for (const node of entry.nodes) node.parentNode?.removeChild(node);\n mounted.delete(element);\n },\n };\n mounted.set(element, entry);\n return { kind: 'embedded', unmount: entry.unmount };\n}\n","/**\n * Formats an integer amount of minor units (kuruş, cents, …) as a\n * localised currency string with `Intl.NumberFormat`, using the currency's\n * own number of minor digits (2 for `TRY`, 0 for `JPY`).\n *\n * @example formatMoney(14990, 'TRY', 'tr-TR') // \"₺149,90\"\n * @throws TypeError when `minor` is not a finite number; RangeError for an\n * unknown currency code (from `Intl`).\n */\nexport function formatMoney(\n minor: number,\n currency: string,\n locale?: string | string[],\n): string {\n if (typeof minor !== 'number' || !Number.isFinite(minor)) {\n throw new TypeError('formatMoney: minor must be a finite number');\n }\n const format = new Intl.NumberFormat(locale, { style: 'currency', currency });\n const digits = format.resolvedOptions().maximumFractionDigits ?? 2;\n return format.format(minor / 10 ** digits);\n}\n","import type { AdPixels, CookieInfo } from './models';\n\n// Pure helpers for choosing what a store host may load and list. They touch\n// no browser API, so they run in server code (for example a Next.js server\n// component) as well as in the browser.\n\n/** Whether `host` is a default store domain (`suffix` or below it). */\nexport function onDefaultDomain(\n host: string,\n suffix: string | undefined,\n): boolean {\n if (!suffix) return false;\n const h = host.toLowerCase();\n const s = suffix.toLowerCase();\n return h === s || h.endsWith(`.${s}`);\n}\n\n/**\n * The pixels a host may load: Meta and TikTok write their cookies to the\n * registrable domain, which every default store domain shares, so they run\n * only on custom domains.\n */\nexport function pixelsForHost(\n p: AdPixels | undefined,\n defaultDomain: boolean,\n): AdPixels | undefined {\n if (!p || !defaultDomain) return p;\n return p.google ? { google: p.google } : {};\n}\n\n/**\n * The cookies a host lists: on a default domain without the\n * `customDomainOnly` ones, and none at all when no optional cookie is left.\n */\nexport function cookiesForHost(\n cookies: CookieInfo[],\n defaultDomain: boolean,\n): CookieInfo[] {\n if (!defaultDomain) return cookies;\n const kept = cookies.filter((c) => !c.customDomainOnly);\n return kept.some((c) => c.category !== 'necessary') ? kept : [];\n}\n","/**\n * The part of the Web Storage API the cart-id helpers use; `localStorage`,\n * `sessionStorage` or any object with these methods (a cookie adapter, a\n * test double).\n */\nexport interface CartIdStorage {\n /** Reads a value, or null. */\n getItem(key: string): string | null;\n /** Writes a value. */\n setItem(key: string, value: string): void;\n /** Deletes a value. */\n removeItem(key: string): void;\n}\n\n/** The storage key of a store's cart id. Namespaced per store. */\nexport function cartIdKey(storeId: string): string {\n return `storefront:cart:${storeId}`;\n}\n\n/**\n * The saved cart id of a store, or null. Never throws: a missing storage\n * (SSR), a storage that throws (Safari private mode, blocked cookies) or\n * an empty value all read as null.\n */\nexport function loadCartId(\n storage: CartIdStorage | null | undefined,\n storeId: string,\n): string | null {\n try {\n const v = storage?.getItem(cartIdKey(storeId));\n return typeof v === 'string' && v.trim() !== '' ? v.trim() : null;\n } catch {\n return null;\n }\n}\n\n/** Saves a store's cart id. Returns false when the storage refused. Never throws. */\nexport function saveCartId(\n storage: CartIdStorage | null | undefined,\n storeId: string,\n cartId: string,\n): boolean {\n if (!storage) return false;\n try {\n storage.setItem(cartIdKey(storeId), cartId);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Forgets a store's cart id (after `cart_not_found`, or `cart_read_only`\n * with `status: \"expired\"`). Returns false when the storage refused. Never throws.\n */\nexport function clearCartId(\n storage: CartIdStorage | null | undefined,\n storeId: string,\n): boolean {\n if (!storage) return false;\n try {\n storage.removeItem(cartIdKey(storeId));\n return true;\n } catch {\n return false;\n }\n}\n\n/** The part of `document` the cookie storage uses. */\nexport interface CookieJar {\n cookie: string;\n}\n\n/** The cookie carrying the cart ids. */\nconst CART_COOKIE = '__Host-konfiqo_cart';\n/** Largest encoded cookie value written (browsers drop a cookie over ~4 KB). */\nconst MAX_COOKIE_VALUE = 3500;\n/** One year, seconds. */\nconst COOKIE_MAX_AGE = 31_536_000;\n\nfunction readMap(doc: CookieJar): Record<string, string> {\n try {\n for (const part of doc.cookie.split(';')) {\n const p = part.trim();\n if (!p.startsWith(`${CART_COOKIE}=`)) continue;\n const parsed: unknown = JSON.parse(\n decodeURIComponent(p.slice(CART_COOKIE.length + 1)),\n );\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n return {};\n }\n const out: Record<string, string> = {};\n for (const [k, v] of Object.entries(parsed)) {\n if (typeof v === 'string') out[k] = v;\n }\n return out;\n }\n } catch {\n // Malformed cookie: ignored (and replaced by the next write).\n }\n return {};\n}\n\nfunction writeMap(doc: CookieJar, map: Record<string, string>): boolean {\n const attrs = '; Path=/; SameSite=Lax; Secure';\n const keys = Object.keys(map);\n if (keys.length === 0) {\n doc.cookie = `${CART_COOKIE}=; Max-Age=0${attrs}`;\n return true;\n }\n const value = encodeURIComponent(JSON.stringify(map));\n if (value.length > MAX_COOKIE_VALUE) return false;\n doc.cookie = `${CART_COOKIE}=${value}; Max-Age=${COOKIE_MAX_AGE}${attrs}`;\n return true;\n}\n\n/**\n * Cart ids in the first-party `__Host-konfiqo_cart` cookie (path\n * `/`, no `Domain`, `SameSite=Lax`, `Secure`). The `__Host-` prefix makes\n * browsers refuse a cookie of this name scoped to a parent domain, so a\n * sibling store subdomain cannot plant a cart; the old unprefixed\n * `konfiqo_cart` is never read. The value is a JSON map keyed by\n * {@link cartIdKey}, so a store's own frontend and the hosted checkout on the same domain share\n * the cart. `Secure` cookies are dropped by browsers on plain `http`\n * (other than `localhost`), so over http nothing is stored here; pair it\n * with a `localStorage` fallback. Without a document (SSR) it reads nothing and writes fail.\n * Never throws; a malformed or oversized cookie is ignored.\n *\n * @param doc Defaults to the global `document`; `null` disables it.\n */\nexport function cookieCartStorage(doc?: CookieJar | null): CartIdStorage {\n const jar = (): CookieJar | null =>\n doc === undefined\n ? ((globalThis as { document?: CookieJar }).document ?? null)\n : doc;\n return {\n getItem(key) {\n const d = jar();\n if (!d) return null;\n return readMap(d)[key] ?? null;\n },\n setItem(key, value) {\n const d = jar();\n if (!d) throw new Error('no document');\n const map = readMap(d);\n map[key] = value;\n if (!writeMap(d, map)) throw new Error('cart cookie too large');\n },\n removeItem(key) {\n const d = jar();\n if (!d) return;\n const map = readMap(d);\n if (!(key in map)) return;\n delete map[key];\n writeMap(d, map);\n },\n };\n}\n","/**\n * Cloudflare's official Turnstile script, explicit-render mode. The only\n * URL {@link loadTurnstile} ever injects.\n */\nexport const TURNSTILE_SCRIPT_URL =\n 'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit';\n\n/** The subset of Cloudflare's `window.turnstile` API the SDK uses. */\nexport interface TurnstileApi {\n /** Renders a widget into `container`; returns its widget id. */\n render(\n container: HTMLElement | string,\n params: {\n sitekey: string;\n callback?: (token: string) => void;\n 'expired-callback'?: () => void;\n 'error-callback'?: (code?: string) => void;\n [key: string]: unknown;\n },\n ): string | null | undefined;\n /** Resets a widget so it produces a new token. */\n reset(widgetId?: string): void;\n /** Removes a widget. */\n remove(widgetId?: string): void;\n}\n\ntype TurnstileWindow = Window & { turnstile?: TurnstileApi };\n\nconst loading = new WeakMap<Document, Promise<TurnstileApi>>();\n\n/**\n * Loads Cloudflare Turnstile into `document` (once: the script is injected\n * at most once per document, concurrent calls share one load) and resolves\n * with `window.turnstile`. Rejects when the script fails to load; the\n * failed `<script>` is removed, so calling again injects a fresh one.\n */\nexport function loadTurnstile(document: Document): Promise<TurnstileApi> {\n const view = document.defaultView as TurnstileWindow | null;\n if (!view)\n return Promise.reject(\n new TypeError('loadTurnstile: document has no window'),\n );\n if (view.turnstile) return Promise.resolve(view.turnstile);\n const pending = loading.get(document);\n if (pending) return pending;\n\n const promise = new Promise<TurnstileApi>((resolve, reject) => {\n let script = Array.from(document.scripts).find(\n (s) => s.src === TURNSTILE_SCRIPT_URL,\n );\n if (!script) {\n script = document.createElement('script');\n script.src = TURNSTILE_SCRIPT_URL;\n script.async = true;\n (document.head ?? document.documentElement).appendChild(script);\n }\n script.addEventListener('load', () => {\n if (view.turnstile) resolve(view.turnstile);\n else\n reject(\n new Error('loadTurnstile: script loaded without window.turnstile'),\n );\n });\n const tag = script;\n tag.addEventListener('error', () => {\n // A failed tag never loads again: remove it so a retry injects a\n // fresh one instead of waiting on the dead tag forever.\n tag.remove();\n reject(new Error('loadTurnstile: script failed to load'));\n });\n });\n loading.set(document, promise);\n // A failed load can be retried by calling again.\n promise.catch(() => {\n if (loading.get(document) === promise) loading.delete(document);\n });\n return promise;\n}\n\n/** Callbacks of {@link renderTurnstile}. */\nexport interface RenderTurnstileOptions {\n /** A token is ready: keep it for the next `carts.checkout` call. */\n onToken: (token: string) => void;\n /** The token expired unused (about 5 minutes): drop it; the widget refreshes. */\n onExpired?: () => void;\n /** The widget failed (network, unsupported browser, …). */\n onError?: (code?: string) => void;\n}\n\n/** A rendered Turnstile widget. */\nexport interface TurnstileWidget {\n /** The widget id. */\n readonly widgetId: string;\n /**\n * Gets a new token. Call it after every `carts.checkout` that used the\n * current token: tokens are **single-use**.\n */\n reset(): void;\n /** Removes the widget. */\n remove(): void;\n}\n\n/**\n * Renders a Turnstile widget with the store's `siteKey`\n * (`store.checkoutChallenge.siteKey`) into `element`, loading the script\n * first if needed. Pass each token from `onToken` to\n * `carts.checkout(id, { turnstileToken })`, then `reset()`.\n */\nexport async function renderTurnstile(\n element: HTMLElement,\n siteKey: string,\n options: RenderTurnstileOptions,\n): Promise<TurnstileWidget> {\n if (!siteKey) throw new TypeError('renderTurnstile: siteKey is required');\n const turnstile = await loadTurnstile(element.ownerDocument);\n const params: Parameters<TurnstileApi['render']>[1] = {\n sitekey: siteKey,\n callback: (token: string) => options.onToken(token),\n 'expired-callback': () => options.onExpired?.(),\n 'error-callback': (code?: string) => options.onError?.(code),\n };\n const widgetId = turnstile.render(element, params);\n if (!widgetId) throw new Error('renderTurnstile: the widget did not render');\n return {\n widgetId,\n reset: () => turnstile.reset(widgetId),\n remove: () => turnstile.remove(widgetId),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACkJA,IAAM,YAAiC,oBAAI,IAA4B;AAAA,EACrE;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,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,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAOD,IAAM,cAAc,uBAAO,IAAI,+BAA+B;AAUvD,IAAM,kBAAN,cAEG,MAAM;AAAA;AAAA,EAEL;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAST,YACE,MACA,QACA,SACA,SACA,SACA;AACA,UAAM,SAAS,OAAO;AACtB,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,SAAS;AACd,SAAK,UAAU;AACf,WAAO,eAAe,MAAM,aAAa,EAAE,OAAO,KAAK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AAkB,CAAC,SAAkB,QAAQ,UAAU,IAAI;AAAA,EAC7D;AACA,QAAM,WAAW,UAAU,OAAO,SAAS,MAAM;AACjD,MAAI,CAAC,SAAU,OAAM,IAAI,MAAM,4CAA4C;AAC3E,SAAO;AAAA,IACL;AAAA,IACA,OAAO,MAAM,UAAU,MAAM,QAAQ;AAAA,IACrC,QAAQ,MAAM,UAAU,OAAO,QAAQ;AAAA,EACzC;AACF;;;AR/HO,IAAM,cAAc;","names":["options","n","document"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/errors.ts","../src/client.ts","../src/theme.ts","../src/payment.ts","../src/money.ts","../src/host-pixels.ts","../src/cart-storage.ts","../src/turnstile.ts"],"sourcesContent":["/** Version of the Storefront SDK package. */\nexport const SDK_VERSION = '0.6.1';\n\nexport {\n createStorefrontClient,\n DEFAULT_TIMEOUT_MS,\n PUBLISHABLE_KEY_HEADER,\n STOREFRONT_KEY_HEADER,\n BUYER_IP_HEADER,\n TURNSTILE_TOKEN_HEADER,\n} from './client';\nexport type {\n CheckoutOptions,\n RequestCodeOptions,\n RequestOptions,\n StorefrontClient,\n StorefrontClientOptions,\n} from './client';\nexport { StorefrontError, isStorefrontError } from './errors';\nexport type {\n AnyStorefrontError,\n BuyerDetailField,\n CheckoutMissing,\n StorefrontApiErrorCode,\n StorefrontClientErrorCode,\n StorefrontErrorCode,\n StorefrontErrorDetails,\n StorefrontErrorDetailsMap,\n ValidationIssue,\n} from './errors';\nexport type * from './models';\nexport { THEME_FONTS, isKnownThemeSection } from './theme';\nexport type {\n CategoryGridSection,\n FeaturedProductsSection,\n HeroSection,\n KnownThemeSection,\n RichTextSection,\n ThemeColors,\n ThemeFont,\n ThemeFooter,\n ThemeHomepage,\n ThemeLink,\n ThemeSection,\n ThemeSocial,\n ThemeV1,\n UnknownThemeSection,\n} from './theme';\nexport { mountPayment } from './payment';\nexport type {\n ClosedPaymentMount,\n EmbeddedPaymentMount,\n MountPaymentOptions,\n PaymentMount,\n PaymentPresentation,\n RedirectPaymentMount,\n UnsupportedPaymentMount,\n} from './payment';\nexport { formatMoney } from './money';\nexport { cookiesForHost, onDefaultDomain, pixelsForHost } from './host-pixels';\nexport {\n cartIdKey,\n clearCartId,\n cookieCartStorage,\n loadCartId,\n saveCartId,\n} from './cart-storage';\nexport type { CartIdStorage, CookieJar } from './cart-storage';\nexport {\n TURNSTILE_SCRIPT_URL,\n loadTurnstile,\n renderTurnstile,\n} from './turnstile';\nexport type {\n RenderTurnstileOptions,\n TurnstileApi,\n TurnstileWidget,\n} from './turnstile';\n","import type { CartLine, ShippingOption } from './models';\n\n/** `checkout_incomplete`: what the cart still lacks. */\nexport type CheckoutMissing =\n | 'lines'\n | 'customer'\n | 'identityNumber'\n | 'shippingAddress'\n | 'shippingOption';\n\n/**\n * `invalid_buyer_details`: the buyer detail the payment provider refused.\n * Address fields come as `shippingAddress.<field>` / `billingAddress.<field>`.\n */\nexport type BuyerDetailField =\n | 'name'\n | 'surname'\n | 'email'\n | 'phone'\n | 'identityNumber'\n | `shippingAddress.${string}`\n | `billingAddress.${string}`;\n\n/** One validation problem of an `invalid_request`. */\nexport interface ValidationIssue {\n /** Dotted path of the field (`phone`, `shipping.city`, …). */\n path: string;\n /** What is wrong with it (never echoes the submitted value). */\n message: string;\n}\n\n/**\n * The extras each error code carries (`StorefrontError.details`). Codes\n * not listed here carry no details (`undefined`).\n */\nexport interface StorefrontErrorDetailsMap {\n /** Prices or shipping changed: show the new totals, then check out again. */\n cart_changed: {\n lines: CartLine[];\n subtotalMinor: number;\n shippingMinor: number;\n totalMinor: number;\n shippingOptions: ShippingOption[];\n };\n /**\n * A personalization text is refused (400, no details) or, at checkout\n * (409), a line's stored text no longer satisfies the product's rule:\n * `lineIds` are those lines. Remove the line and add it again with a\n * valid text.\n */\n invalid_personalization: { lineIds?: string[] };\n /** These variants cannot be bought (no longer sold, or not enough units). */\n out_of_stock: { variantIds: string[] };\n /** Collect what is missing, then check out again. */\n checkout_incomplete: { missing: CheckoutMissing[] };\n /** Let the buyer fix `field`, then check out again. */\n invalid_buyer_details: { field: BuyerDetailField };\n /** Only `available` units can be added. */\n insufficient_stock: { available: number };\n /** The request body or query failed validation. */\n invalid_request: { issues: ValidationIssue[] };\n /** The cart can no longer change: start a new cart. */\n cart_read_only: { status: 'ordered' | 'expired' };\n /** Throttled. `retryAfter` = seconds to wait, when the response said so. */\n rate_limited: { retryAfter?: number };\n /** No response within `timeoutMs`. */\n timeout: { timeoutMs: number };\n /** The server answered an error code this SDK version does not know. */\n unknown_error: { error: string | null };\n}\n\n/** Error codes of the Storefront API (the `error` field of an error response). */\nexport type StorefrontApiErrorCode =\n | 'store_not_found'\n | 'origin_not_allowed'\n | 'invalid_request'\n | 'invalid_buyer_ip'\n | 'catalog_unavailable'\n | 'product_not_found'\n | 'content_not_found'\n | 'cart_not_found'\n | 'variant_not_found'\n | 'line_not_found'\n | 'insufficient_stock'\n | 'quantity_out_of_range'\n | 'too_many_lines'\n | 'invalid_shipping_option'\n | 'cart_read_only'\n | 'checkout_in_progress'\n | 'checkout_incomplete'\n | 'cart_changed'\n | 'invalid_personalization'\n | 'out_of_stock'\n | 'amount_out_of_range'\n | 'nothing_to_pay'\n | 'invalid_buyer_details'\n | 'payment_unavailable'\n | 'checkout_unavailable'\n | 'order_not_found'\n | 'order_unavailable'\n | 'media_not_found'\n | 'media_unavailable'\n | 'challenge_required'\n | 'challenge_failed'\n | 'challenge_unavailable'\n | 'too_many_open_orders'\n | 'not_signed_in'\n | 'invalid_code'\n | 'profile_required'\n | 'too_many_code_requests'\n | 'invalid_recovery_token'\n | 'cart_not_recoverable'\n | 'unavailable';\n\n/**\n * Codes the SDK assigns itself:\n * - `rate_limited` — HTTP 429 without a known `error` code (the throttler);\n * - `unauthorized` — HTTP 401 without a code (a wrong `trustedStorefrontKey`);\n * - `http_error` — any other non-2xx response without an `error` code;\n * - `unknown_error` — an `error` code this SDK version does not know (in `details.error`);\n * - `invalid_response` — a 2xx response that is not JSON;\n * - `network_error` — no readable response: the API was unreachable (DNS,\n * TLS, offline), or, in a browser, the origin is allowed by no store;\n * - `timeout` — no response within `timeoutMs`;\n * - `aborted` — the caller's `signal` aborted the request.\n */\nexport type StorefrontClientErrorCode =\n | 'rate_limited'\n | 'unauthorized'\n | 'http_error'\n | 'unknown_error'\n | 'invalid_response'\n | 'network_error'\n | 'timeout'\n | 'aborted';\n\n/** Every code a {@link StorefrontError} can have. */\nexport type StorefrontErrorCode =\n StorefrontApiErrorCode | StorefrontClientErrorCode;\n\n/** The `details` type of an error code (`undefined` for codes without extras). */\nexport type StorefrontErrorDetails<C extends StorefrontErrorCode> =\n C extends keyof StorefrontErrorDetailsMap\n ? StorefrontErrorDetailsMap[C]\n : undefined;\n\nconst API_CODES: ReadonlySet<string> = new Set<StorefrontApiErrorCode>([\n 'store_not_found',\n 'origin_not_allowed',\n 'invalid_request',\n 'invalid_buyer_ip',\n 'catalog_unavailable',\n 'product_not_found',\n 'content_not_found',\n 'cart_not_found',\n 'variant_not_found',\n 'line_not_found',\n 'insufficient_stock',\n 'quantity_out_of_range',\n 'too_many_lines',\n 'invalid_shipping_option',\n 'cart_read_only',\n 'checkout_in_progress',\n 'checkout_incomplete',\n 'cart_changed',\n 'invalid_personalization',\n 'out_of_stock',\n 'amount_out_of_range',\n 'nothing_to_pay',\n 'invalid_buyer_details',\n 'payment_unavailable',\n 'checkout_unavailable',\n 'order_not_found',\n 'order_unavailable',\n 'media_not_found',\n 'media_unavailable',\n 'challenge_required',\n 'challenge_failed',\n 'challenge_unavailable',\n 'too_many_open_orders',\n 'not_signed_in',\n 'invalid_code',\n 'profile_required',\n 'too_many_code_requests',\n 'invalid_recovery_token',\n 'cart_not_recoverable',\n 'unavailable',\n]);\n\n/**\n * Marks every {@link StorefrontError}. A global (`Symbol.for`) symbol, so\n * an error thrown by one installed copy of the SDK is recognised by another\n * (e.g. the React package resolving its own copy), where `instanceof` fails.\n */\nconst ERROR_BRAND = Symbol.for('@konfiqo/storefront-sdk/error');\n\n/**\n * Every failure of a client call: an API error response, a throttle, a\n * timeout or a transport failure. Switch on `code`, never on `message`.\n *\n * To get `details` typed per code, narrow with {@link isStorefrontError}\n * (which yields the {@link AnyStorefrontError} union) and `switch (e.code)`,\n * or test one code with `e.is('cart_changed')`.\n */\nexport class StorefrontError<\n C extends StorefrontErrorCode = StorefrontErrorCode,\n> extends Error {\n /** The API `error` code, or one of the SDK's own codes. */\n readonly code: C;\n /** HTTP status; `0` when no response arrived (`network_error`, `timeout`). */\n readonly status: number;\n /** The code's extras (see {@link StorefrontErrorDetailsMap}). */\n readonly details: StorefrontErrorDetails<C>;\n\n /**\n * @param code - the error code\n * @param status - the HTTP status (`0` without a response)\n * @param message - a human-readable description (not for display logic)\n * @param details - the code's extras\n * @param options - `cause`: the underlying error, if any\n */\n constructor(\n code: C,\n status: number,\n message: string,\n details: StorefrontErrorDetails<C>,\n options?: { cause?: unknown },\n ) {\n super(message, options);\n this.name = 'StorefrontError';\n this.code = code;\n this.status = status;\n this.details = details;\n Object.defineProperty(this, ERROR_BRAND, { value: true });\n }\n\n /** Whether this error has `code`; narrows `details` to that code's extras. */\n is<K extends StorefrontErrorCode>(code: K): this is StorefrontError<K> {\n return (this.code as StorefrontErrorCode) === code;\n }\n}\n\n/**\n * The union of {@link StorefrontError} by code: after narrowing `code`\n * (e.g. in a `switch`), `details` has that code's type.\n */\nexport type AnyStorefrontError = {\n [C in StorefrontErrorCode]: StorefrontError<C>;\n}[StorefrontErrorCode];\n\n/**\n * Whether `e` is a {@link StorefrontError}, as the code-discriminated union.\n * Also true for an error from another copy of this SDK (checked by a global\n * brand, not only `instanceof`).\n */\nexport function isStorefrontError(e: unknown): e is AnyStorefrontError {\n return (\n e instanceof StorefrontError ||\n (typeof e === 'object' &&\n e !== null &&\n (e as Record<symbol, unknown>)[ERROR_BRAND] === true)\n );\n}\n\nconst isObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === 'object' && v !== null && !Array.isArray(v);\n\n/** Seconds from a `Retry-After` value (delta-seconds or an HTTP date). */\nfunction parseRetryAfter(value: string | null): number | undefined {\n if (value === null) return undefined;\n const trimmed = value.trim();\n if (/^\\d+$/.test(trimmed)) return Number(trimmed);\n const at = Date.parse(trimmed);\n if (Number.isNaN(at)) return undefined;\n return Math.max(0, Math.ceil((at - Date.now()) / 1000));\n}\n\n/**\n * Builds the error for a non-2xx response from its status, body (parsed\n * JSON, or undefined) and headers. Internal.\n */\nexport function errorFromResponse(\n status: number,\n body: unknown,\n headers: Headers,\n): AnyStorefrontError {\n const b = isObject(body) ? body : {};\n const message =\n typeof b.message === 'string' && b.message !== ''\n ? b.message\n : `Storefront API request failed (HTTP ${status})`;\n\n const error = typeof b.error === 'string' ? b.error : null;\n // A 429 with a known code (`too_many_open_orders`) is that code; the\n // throttler's 429 carries none.\n if (status === 429 && (error === null || !API_CODES.has(error))) {\n // The throttler names its header per limit (`Retry-After`,\n // `Retry-After-ip`); when both come, the longer wait is the real one.\n const waits = [\n parseRetryAfter(headers.get('retry-after')),\n parseRetryAfter(headers.get('retry-after-ip')),\n ].filter((w): w is number => w !== undefined);\n const retryAfter = waits.length > 0 ? Math.max(...waits) : undefined;\n return new StorefrontError(\n 'rate_limited',\n status,\n message,\n retryAfter === undefined ? {} : { retryAfter },\n );\n }\n\n if (error === null) {\n if (status === 401)\n return new StorefrontError('unauthorized', status, message, undefined);\n return new StorefrontError('http_error', status, message, undefined);\n }\n if (!API_CODES.has(error)) {\n return new StorefrontError('unknown_error', status, message, { error });\n }\n const code = error as StorefrontApiErrorCode;\n return apiError(code, status, message, b);\n}\n\nconst arr = <T>(v: unknown): T[] => (Array.isArray(v) ? (v as T[]) : []);\nconst n = (v: unknown): number => (typeof v === 'number' ? v : 0);\n\nfunction apiError(\n code: StorefrontApiErrorCode,\n status: number,\n message: string,\n b: Record<string, unknown>,\n): AnyStorefrontError {\n switch (code) {\n case 'cart_changed':\n return new StorefrontError(code, status, message, {\n lines: arr<CartLine>(b.lines),\n subtotalMinor: n(b.subtotalMinor),\n shippingMinor: n(b.shippingMinor),\n totalMinor: n(b.totalMinor),\n shippingOptions: arr<ShippingOption>(b.shippingOptions),\n });\n case 'invalid_personalization':\n return new StorefrontError(\n code,\n status,\n message,\n Array.isArray(b.lineIds) ? { lineIds: arr<string>(b.lineIds) } : {},\n );\n case 'out_of_stock':\n return new StorefrontError(code, status, message, {\n variantIds: arr<string>(b.variantIds),\n });\n case 'checkout_incomplete':\n return new StorefrontError(code, status, message, {\n missing: arr<CheckoutMissing>(b.missing),\n });\n case 'invalid_buyer_details':\n return new StorefrontError(code, status, message, {\n field: String(b.field ?? '') as BuyerDetailField,\n });\n case 'insufficient_stock':\n return new StorefrontError(code, status, message, {\n available: n(b.available),\n });\n case 'invalid_request':\n return new StorefrontError(code, status, message, {\n issues: arr<ValidationIssue>(b.issues),\n });\n case 'cart_read_only':\n return new StorefrontError(code, status, message, {\n status: b.status === 'ordered' ? 'ordered' : 'expired',\n });\n default:\n return new StorefrontError(\n code,\n status,\n message,\n undefined,\n ) as AnyStorefrontError;\n }\n}\n","import { StorefrontError, errorFromResponse } from './errors';\nimport type {\n AddLineInput,\n AddressInput,\n Account,\n AccountProfileInput,\n AccountSession,\n Cart,\n CategoryList,\n CheckoutResult,\n CustomerInput,\n Order,\n Product,\n ProductListQuery,\n ProductPage,\n SavedAddress,\n SavedAddressInput,\n ShippingOptionList,\n Store,\n StoreContent,\n UpdateLineInput,\n} from './models';\n\n/** Default request timeout, milliseconds. */\nexport const DEFAULT_TIMEOUT_MS = 15_000;\n\n/** Header carrying the publishable key on every request. */\nexport const PUBLISHABLE_KEY_HEADER = 'x-konfiqo-publishable-key';\n/** Header carrying the trusted storefront key (server-side only). */\nexport const STOREFRONT_KEY_HEADER = 'x-konfiqo-storefront-key';\n/** Header carrying the store's server key (server-side only). */\nexport const SERVER_KEY_HEADER = 'x-konfiqo-server-key';\n/** Header carrying the checkout challenge token (checkout only). */\nexport const TURNSTILE_TOKEN_HEADER = 'x-konfiqo-turnstile-token';\n/** Header carrying the buyer's IP (only with a server key or the trusted storefront key). */\nexport const BUYER_IP_HEADER = 'x-konfiqo-buyer-ip';\n\n/** Per-call options, accepted as the last argument of every method. */\nexport interface RequestOptions {\n /**\n * Aborts the request: it rejects with code `aborted`. Combined with the\n * client timeout (whichever comes first wins).\n */\n signal?: AbortSignal;\n /**\n * **Server-side only.** A `Cookie` header to forward, so a server-rendered\n * storefront can call the account routes as the buyer: pass the incoming\n * request's `cookie` header (or just `konfiqo_session=<value>`). Browsers\n * ignore a `Cookie` header set from script; there the session cookie rides\n * along automatically (`credentials: 'include'`).\n */\n cookie?: string;\n}\n\n/** Options of `account.requestCode`. */\nexport interface RequestCodeOptions extends RequestOptions {\n /**\n * The challenge token (Cloudflare Turnstile), required when the store\n * asks for one (`store.checkoutChallenge`). Single-use. Sent as\n * `x-konfiqo-turnstile-token`.\n */\n turnstileToken?: string;\n}\n\n/** Options of `carts.checkout`. */\nexport interface CheckoutOptions extends RequestOptions {\n /**\n * The checkout challenge token (Cloudflare Turnstile), required when\n * `store.checkoutChallenge` is set. Single-use: get a new one (reset the\n * widget) for every checkout call. Sent as `x-konfiqo-turnstile-token`.\n */\n turnstileToken?: string;\n}\n\n/** Options of {@link createStorefrontClient}. */\nexport interface StorefrontClientOptions {\n /**\n * The Storefront API base: `https://<store domain>/api` (or the relative\n * `/api` in a same-origin browser app). Requests go to `${baseUrl}/v1/...`,\n * so do not include `/v1`.\n */\n baseUrl: string;\n /** The store's publishable key (`pk_live_…` / `pk_test_…`). Public. */\n publishableKey: string;\n /** A `fetch` implementation; defaults to the global `fetch`. */\n fetch?: typeof fetch;\n /** Per-request timeout in milliseconds (default {@link DEFAULT_TIMEOUT_MS}). */\n timeoutMs?: number;\n /**\n * **Server-side only.** The shared storefront key that lets a server-side\n * renderer report the real buyer IP (`buyerIp`), so throttling and the\n * payment provider see the buyer instead of the server. Sent as\n * `x-konfiqo-storefront-key`. Constructing a client with it where\n * `window` exists throws: never ship this key to a browser.\n */\n trustedStorefrontKey?: string;\n /**\n * **Server-side only.** The store's own server key, minted by the store\n * operator. It lets the seller's server report the real buyer IP\n * (`buyerIp`). Sent as `x-konfiqo-server-key` next to the publishable\n * key. Needs `buyerIp`, cannot be combined with `trustedStorefrontKey`,\n * and constructing a client with it in a browser throws.\n */\n serverKey?: string;\n /**\n * The buyer's IP address, sent as `x-konfiqo-buyer-ip`. Required with\n * `serverKey` or `trustedStorefrontKey`, ignored without one. Create one\n * client per incoming request on the server.\n */\n buyerIp?: string;\n}\n\n/**\n * A typed client of the Storefront API (`/v1`).\n *\n * Every method returns the response body, or rejects with a\n * {@link StorefrontError}. Nothing is retried: whether to retry is the\n * caller's decision, because writes are not safely repeatable — in\n * particular `carts.checkout` on a cart whose order failed places a\n * **new** order, so a blind retry could open a second payment.\n */\nexport interface StorefrontClient {\n /**\n * `GET /v1/content/:key`: a piece of store content as a renderable\n * Markdoc tree. Rejects `content_not_found` (404) for an unknown key.\n */\n getContent(key: string, options?: RequestOptions): Promise<StoreContent>;\n /** Store information. */\n readonly store: {\n /** `GET /v1/store`: name, language, currency, logo, theme, contact, legal texts, shipping rules. */\n get(options?: RequestOptions): Promise<Store>;\n };\n /** Categories. */\n readonly categories: {\n /** `GET /v1/categories`: the active category tree. */\n list(options?: RequestOptions): Promise<CategoryList>;\n };\n /** Products. */\n readonly products: {\n /** `GET /v1/products`: a page of products, optionally filtered. */\n list(\n query?: ProductListQuery,\n options?: RequestOptions,\n ): Promise<ProductPage>;\n /** `GET /v1/products/:slug`. Rejects with `product_not_found`. */\n get(slug: string, options?: RequestOptions): Promise<Product>;\n };\n /** Carts. Every cart write answers the updated cart. */\n readonly carts: {\n /** `POST /v1/carts`: a new, empty cart. */\n create(options?: RequestOptions): Promise<Cart>;\n /**\n * `POST /v1/carts/recover`: turns the `t` token of an abandoned-cart\n * e-mail link into a **new** cart with the same lines (no buyer data).\n * Rejects `invalid_recovery_token` (400) or `cart_not_recoverable` (410:\n * the cart was ordered, expired or deleted).\n */\n recover(\n token: string,\n options?: RequestOptions,\n ): Promise<{ cartId: string }>;\n /** `GET /v1/carts/:id`. Also reopens a cart whose payment failed. */\n get(cartId: string, options?: RequestOptions): Promise<Cart>;\n /** `POST /v1/carts/:id/lines`: adds units of a variant. */\n addLine(\n cartId: string,\n input: AddLineInput,\n options?: RequestOptions,\n ): Promise<Cart>;\n /**\n * `PATCH /v1/carts/:id/lines/:lineId`: sets a line's quantity. `lineId`\n * is `CartLine.id`; a variant id still matches a line without text.\n */\n updateLine(\n cartId: string,\n lineId: string,\n input: UpdateLineInput,\n options?: RequestOptions,\n ): Promise<Cart>;\n /** `DELETE /v1/carts/:id/lines/:lineId`: removes a line (`CartLine.id`). */\n removeLine(\n cartId: string,\n lineId: string,\n options?: RequestOptions,\n ): Promise<Cart>;\n /** `PUT /v1/carts/:id/customer`: sets the buyer. */\n setCustomer(\n cartId: string,\n input: CustomerInput,\n options?: RequestOptions,\n ): Promise<Cart>;\n /** `PUT /v1/carts/:id/address`: sets the shipping (and billing) address. */\n setAddress(\n cartId: string,\n input: AddressInput,\n options?: RequestOptions,\n ): Promise<Cart>;\n /** `GET /v1/carts/:id/shipping-options`: the options this cart can use. */\n shippingOptions(\n cartId: string,\n options?: RequestOptions,\n ): Promise<ShippingOptionList>;\n /** `PUT /v1/carts/:id/shipping-option`: selects a shipping option by id. */\n setShippingOption(\n cartId: string,\n optionId: string,\n options?: RequestOptions,\n ): Promise<Cart>;\n /**\n * `POST /v1/carts/:id/checkout`: places the order (or re-opens payment\n * for the cart's order) and answers how to present payment. Keep the\n * returned `token`: it is returned only once. Not retried.\n *\n * Aborting (`signal`) only stops waiting: the server may still place\n * the order. Read the cart again before showing a result.\n *\n * When `store.checkoutChallenge` is set, pass a fresh\n * `turnstileToken` (see `renderTurnstile`); tokens are single-use, so\n * reset the widget after every call. Re-opening payment on an already\n * ordered cart needs no token.\n */\n checkout(\n cartId: string,\n options?: CheckoutOptions,\n ): Promise<CheckoutResult>;\n };\n /** Buyer order status. */\n readonly orders: {\n /** `GET /v1/orders/:id?token=`: the order, for the buyer holding its token. */\n get(\n orderId: string,\n token: string,\n options?: RequestOptions,\n ): Promise<Order>;\n };\n /**\n * The signed-in buyer's account. Sign-in is by an e-mailed one-time code;\n * the session is an HttpOnly cookie (`konfiqo_session`) the API sets on the\n * store origin, so these calls send `credentials: 'include'`. On a server,\n * forward the buyer's cookie with the `cookie` call option.\n */\n readonly account: {\n /**\n * `POST /v1/account/code`: e-mails a 6-digit code. Resolves the same for\n * any address (202); rejects `too_many_code_requests` (429),\n * `challenge_required` / `challenge_failed`, `invalid_request`.\n */\n requestCode(email: string, options?: RequestCodeOptions): Promise<void>;\n /**\n * `POST /v1/account/session`: signs in with the code. A wrong, spent or\n * expired code rejects `invalid_code` (401).\n */\n signIn(\n email: string,\n code: string,\n options?: RequestOptions,\n ): Promise<AccountSession>;\n /** `DELETE /v1/account/session`: signs out (always succeeds). */\n signOut(options?: RequestOptions): Promise<void>;\n /**\n * `GET /v1/account[?page=]`: profile, saved addresses and a page of\n * orders (20 per page, newest first). Rejects `not_signed_in` (401).\n */\n get(page?: number, options?: RequestOptions): Promise<Account>;\n /**\n * `PUT /v1/account/profile`: saves name, surname and a Turkish mobile\n * phone. Creates the buyer's record on first save.\n */\n updateProfile(\n profile: AccountProfileInput,\n options?: RequestOptions,\n ): Promise<void>;\n /**\n * `PUT /v1/account/addresses`: replaces the saved addresses (at most 5,\n * at most one default). Resolves the list as stored (ids filled in).\n * Rejects `profile_required` (409) until a profile is saved.\n */\n saveAddresses(\n addresses: SavedAddressInput[],\n options?: RequestOptions,\n ): Promise<SavedAddress[]>;\n };\n /** Catalog images. */\n readonly media: {\n /**\n * The absolute URL of a storage key (product `image`, store `logo`,\n * theme `logo` / `favicon` / section `image`), usable in `<img src>`:\n * `${baseUrl}/v1/media/<key, each segment encoded>?pk=<publishable key>`.\n *\n * @throws TypeError (`invalid_path_segment`) when a key segment is\n * empty, `.` or `..`.\n */\n url(key: string): string;\n };\n}\n\ntype Method = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n\n/**\n * One encoded path segment. `encodeURIComponent` leaves `.` and `..` as\n * they are, and URL normalisation would turn them into another route, so\n * those (and an empty segment) are refused.\n */\nfunction seg(v: string): string {\n if (typeof v !== 'string' || v === '' || v === '.' || v === '..') {\n throw new TypeError(\n `invalid_path_segment: ${JSON.stringify(v)} is not a valid path segment`,\n );\n }\n return encodeURIComponent(v);\n}\n\n/** Whether this host looks like a browser or a web worker. */\nfunction isBrowserLike(): boolean {\n const g = globalThis as { importScripts?: unknown };\n return (\n typeof window !== 'undefined' ||\n typeof document !== 'undefined' ||\n (typeof self !== 'undefined' && typeof g.importScripts === 'function')\n );\n}\n\n/**\n * Creates a Storefront API client.\n *\n * @throws TypeError when `baseUrl` or `publishableKey` is empty, when\n * `serverKey` or `trustedStorefrontKey` is given without `buyerIp`, when\n * both keys are given together, or when either key is given in a\n * browser-like host (`window` or `document` defined, or a web worker).\n * Hosts that define `window` on a server (jsdom, Electron renderers,\n * React Native) are refused too: keep these keys in a plain server process.\n */\nexport function createStorefrontClient(\n options: StorefrontClientOptions,\n): StorefrontClient {\n const baseUrl = options.baseUrl?.trim().replace(/\\/+$/, '');\n if (!baseUrl)\n throw new TypeError('createStorefrontClient: baseUrl is required');\n const publishableKey = options.publishableKey?.trim();\n if (!publishableKey)\n throw new TypeError('createStorefrontClient: publishableKey is required');\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n if (!(timeoutMs > 0) || !Number.isFinite(timeoutMs)) {\n throw new TypeError(\n 'createStorefrontClient: timeoutMs must be a positive number',\n );\n }\n\n const baseHeaders: Record<string, string> = {\n [PUBLISHABLE_KEY_HEADER]: publishableKey,\n };\n if (\n options.serverKey !== undefined &&\n options.trustedStorefrontKey !== undefined\n ) {\n throw new TypeError(\n 'createStorefrontClient: serverKey and trustedStorefrontKey cannot be used together',\n );\n }\n if (options.serverKey !== undefined) {\n if (isBrowserLike()) {\n throw new TypeError(\n 'createStorefrontClient: serverKey must never be used in a browser',\n );\n }\n const buyerIp = options.buyerIp?.trim();\n if (!buyerIp) {\n throw new TypeError(\n 'createStorefrontClient: buyerIp is required with serverKey',\n );\n }\n baseHeaders[SERVER_KEY_HEADER] = options.serverKey;\n baseHeaders[BUYER_IP_HEADER] = buyerIp;\n }\n if (options.trustedStorefrontKey !== undefined) {\n if (isBrowserLike()) {\n throw new TypeError(\n 'createStorefrontClient: trustedStorefrontKey is server-only and must never be used in a browser',\n );\n }\n const buyerIp = options.buyerIp?.trim();\n if (!buyerIp) {\n throw new TypeError(\n 'createStorefrontClient: buyerIp is required with trustedStorefrontKey',\n );\n }\n baseHeaders[STOREFRONT_KEY_HEADER] = options.trustedStorefrontKey;\n baseHeaders[BUYER_IP_HEADER] = buyerIp;\n }\n\n async function request<T>(\n method: Method,\n path: () => string,\n body?: unknown,\n callOptions?: RequestOptions,\n extraHeaders: Record<string, string> = {},\n flags: { credentials?: boolean; emptyOk?: boolean } = {},\n ): Promise<T> {\n const url = `${baseUrl}${path()}`;\n const callerSignal = callOptions?.signal;\n if (callerSignal?.aborted) throw abortError(callerSignal);\n // Resolved per call (not at construction) so a polyfilled global works.\n // Called detached: a browser `fetch` must not be invoked on another `this`.\n const doFetch = options.fetch ?? globalThis.fetch;\n const headers: Record<string, string> = {\n ...baseHeaders,\n ...extraHeaders,\n };\n if (callOptions?.cookie) headers.cookie = callOptions.cookie;\n const init: RequestInit = { method, headers };\n if (flags.credentials) init.credentials = 'include';\n if (body !== undefined) {\n headers['content-type'] = 'application/json';\n init.body = JSON.stringify(body);\n }\n const controller = new AbortController();\n init.signal = controller.signal;\n let timedOut = false;\n // Raced as well as aborted: a custom `fetch` that ignores the signal\n // still cannot hold the caller past the timeout.\n let onTimeout: (e: StorefrontError) => void = () => {};\n const deadline = new Promise<never>((_, reject) => {\n onTimeout = reject;\n });\n deadline.catch(() => {});\n const timer = setTimeout(() => {\n timedOut = true;\n onTimeout(transportError(undefined, true, timeoutMs));\n controller.abort();\n }, timeoutMs);\n const onCallerAbort = () => {\n onTimeout(abortError(callerSignal!));\n controller.abort();\n };\n callerSignal?.addEventListener('abort', onCallerAbort, { once: true });\n\n try {\n let res: Response;\n let text: string;\n try {\n res = await Promise.race([doFetch(url, init), deadline]);\n text = await Promise.race([res.text(), deadline]);\n } catch (e) {\n if (e instanceof StorefrontError) throw e;\n throw transportError(e, timedOut, timeoutMs);\n }\n let parsed: unknown;\n let isJson = false;\n if (text !== '') {\n try {\n parsed = JSON.parse(text);\n isJson = true;\n } catch {\n parsed = undefined;\n }\n }\n if (!res.ok) throw errorFromResponse(res.status, parsed, res.headers);\n if (!isJson && flags.emptyOk && text === '') return undefined as T;\n if (!isJson) {\n throw new StorefrontError(\n 'invalid_response',\n res.status,\n 'Storefront API answered a non-JSON body',\n undefined,\n );\n }\n return parsed as T;\n } finally {\n clearTimeout(timer);\n callerSignal?.removeEventListener('abort', onCallerAbort);\n }\n }\n\n const get = <T>(path: () => string, options?: RequestOptions) =>\n request<T>('GET', path, undefined, options);\n const acct = { credentials: true } as const;\n const send = <T>(\n method: Method,\n path: string,\n body: unknown,\n o?: RequestOptions,\n extra: Record<string, string> = {},\n emptyOk = false,\n ) => request<T>(method, () => path, body, o, extra, { ...acct, emptyOk });\n const cart = (id: string) => `/v1/carts/${seg(id)}`;\n\n return {\n getContent: (key, o) =>\n get<StoreContent>(() => `/v1/content/${seg(key)}`, o),\n store: {\n get: (o) => get<Store>(() => '/v1/store', o),\n },\n categories: {\n list: (o) => get<CategoryList>(() => '/v1/categories', o),\n },\n products: {\n list: (query = {}, o) =>\n get<ProductPage>(() => {\n const params = new URLSearchParams();\n if (query.category !== undefined)\n params.set('category', query.category);\n if (query.q !== undefined) params.set('q', query.q);\n if (query.page !== undefined) params.set('page', String(query.page));\n if (query.pageSize !== undefined)\n params.set('pageSize', String(query.pageSize));\n const qs = params.toString();\n return `/v1/products${qs ? `?${qs}` : ''}`;\n }, o),\n get: (slug, o) => get<Product>(() => `/v1/products/${seg(slug)}`, o),\n },\n carts: {\n create: (o) => request<Cart>('POST', () => '/v1/carts', undefined, o),\n recover: (token, o) =>\n request<{ cartId: string }>(\n 'POST',\n () => '/v1/carts/recover',\n { token },\n o,\n ),\n get: (cartId, o) => get<Cart>(() => cart(cartId), o),\n addLine: (cartId, input, o) =>\n request<Cart>(\n 'POST',\n () => `${cart(cartId)}/lines`,\n {\n variantId: input.variantId,\n quantity: input.quantity,\n ...(input.personalization !== undefined && {\n personalization: input.personalization,\n }),\n },\n o,\n ),\n updateLine: (cartId, lineId, input, o) =>\n request<Cart>(\n 'PATCH',\n () => `${cart(cartId)}/lines/${seg(lineId)}`,\n { quantity: input.quantity },\n o,\n ),\n removeLine: (cartId, lineId, o) =>\n request<Cart>(\n 'DELETE',\n () => `${cart(cartId)}/lines/${seg(lineId)}`,\n undefined,\n o,\n ),\n setCustomer: (cartId, input, o) =>\n request<Cart>('PUT', () => `${cart(cartId)}/customer`, input, o),\n setAddress: (cartId, input, o) =>\n request<Cart>('PUT', () => `${cart(cartId)}/address`, input, o),\n shippingOptions: (cartId, o) =>\n get<ShippingOptionList>(() => `${cart(cartId)}/shipping-options`, o),\n setShippingOption: (cartId, optionId, o) =>\n request<Cart>(\n 'PUT',\n () => `${cart(cartId)}/shipping-option`,\n { id: optionId },\n o,\n ),\n checkout: (cartId, o) =>\n request<CheckoutResult>(\n 'POST',\n () => `${cart(cartId)}/checkout`,\n undefined,\n o,\n o?.turnstileToken\n ? { [TURNSTILE_TOKEN_HEADER]: o.turnstileToken }\n : {},\n ),\n },\n orders: {\n get: (orderId, token, o) =>\n get<Order>(\n () => `/v1/orders/${seg(orderId)}?token=${encodeURIComponent(token)}`,\n o,\n ),\n },\n account: {\n requestCode: (email, o) =>\n send<void>(\n 'POST',\n '/v1/account/code',\n { email },\n o,\n o?.turnstileToken\n ? { [TURNSTILE_TOKEN_HEADER]: o.turnstileToken }\n : {},\n true,\n ),\n signIn: (email, code, o) =>\n send<AccountSession>('POST', '/v1/account/session', { email, code }, o),\n signOut: (o) =>\n send<void>('DELETE', '/v1/account/session', undefined, o, {}, true),\n get: (page, o) =>\n send<Account>(\n 'GET',\n page === undefined\n ? '/v1/account'\n : `/v1/account?page=${encodeURIComponent(String(page))}`,\n undefined,\n o,\n ),\n updateProfile: (profile, o) =>\n send<void>(\n 'PUT',\n '/v1/account/profile',\n {\n name: profile.name,\n surname: profile.surname,\n phone: profile.phone,\n },\n o,\n {},\n true,\n ),\n saveAddresses: async (addresses, o) =>\n (\n await send<{ addresses: SavedAddress[] }>(\n 'PUT',\n '/v1/account/addresses',\n { addresses },\n o,\n )\n ).addresses,\n },\n media: {\n url: (key) =>\n `${baseUrl}/v1/media/${key.split('/').map(seg).join('/')}?pk=${encodeURIComponent(publishableKey)}`,\n },\n };\n}\n\n/** The caller aborted the request (`options.signal`). */\nfunction abortError(signal: AbortSignal): StorefrontError {\n return new StorefrontError(\n 'aborted',\n 0,\n 'Storefront API request was aborted',\n undefined,\n { cause: signal.reason },\n );\n}\n\n/** A fetch / body-read failure as `timeout` or `network_error`. */\nfunction transportError(\n e: unknown,\n timedOut: boolean,\n timeoutMs: number,\n): StorefrontError {\n if (timedOut) {\n return new StorefrontError(\n 'timeout',\n 0,\n `Storefront API did not answer within ${timeoutMs} ms`,\n { timeoutMs },\n { cause: e },\n );\n }\n return new StorefrontError(\n 'network_error',\n 0,\n 'Storefront API could not be reached',\n undefined,\n {\n cause: e,\n },\n );\n}\n","/**\n * Store theme, `schemaVersion: 1` (the commerce module's \"Store settings\n * JSON\"). The Storefront API passes the theme through **as stored**: it is\n * not validated, so every field is optional and a renderer must tolerate\n * missing values, wrong types and keys it does not know. Image fields are\n * tenant storage keys — turn them into URLs with `client.media.url(key)`.\n */\nexport interface ThemeV1 {\n /** `1` for this shape. Anything else: render defaults. */\n schemaVersion?: number;\n /** Storage key of the logo (the same key as the store's `logo`). */\n logo?: string | null;\n /** Storage key of the favicon. */\n favicon?: string | null;\n /** Theme colors, CSS color strings (normally `#rrggbb`). */\n colors?: ThemeColors;\n /** One of {@link THEME_FONTS}; an unknown value means \"use the default font\". */\n font?: ThemeFont | (string & {});\n /** The homepage, as ordered sections. */\n homepage?: ThemeHomepage;\n /** Footer links and social profiles. */\n footer?: ThemeFooter;\n /** Keys this SDK version does not know are kept as stored. */\n [key: string]: unknown;\n}\n\n/** Theme colors. Each is a CSS color string; any may be missing. */\nexport interface ThemeColors {\n /** Primary brand color. */\n primary?: string;\n /** Accent (links, highlights). */\n accent?: string;\n /** Page background. */\n background?: string;\n /** Body text. */\n text?: string;\n /** Unknown color keys are kept as stored. */\n [key: string]: unknown;\n}\n\n/** The fonts a v1 theme may name. */\nexport const THEME_FONTS = [\n 'inter',\n 'roboto',\n 'open-sans',\n 'lato',\n 'poppins',\n] as const;\n\n/** A font a v1 theme may name. */\nexport type ThemeFont = (typeof THEME_FONTS)[number];\n\n/** The homepage: sections in display order. */\nexport interface ThemeHomepage {\n /**\n * Sections in display order. May contain section types this SDK does not\n * know (skip them) — narrow with {@link isKnownThemeSection}.\n */\n sections?: ThemeSection[];\n /** Unknown homepage keys are kept as stored. */\n [key: string]: unknown;\n}\n\n/** A call-to-action link. */\nexport interface ThemeLink {\n /** Visible text. */\n label?: string;\n /** Target URL or path. */\n href?: string;\n}\n\n/** `hero`: a large banner with an optional image and call to action. */\nexport interface HeroSection {\n /** Discriminator. */\n type: 'hero';\n /** Storage key of the banner image. */\n image?: string | null;\n /** Headline. */\n title?: string;\n /** Sub-headline. */\n subtitle?: string;\n /** Optional call-to-action button. */\n cta?: ThemeLink;\n}\n\n/** `featuredProducts`: a hand-picked list of products. */\nexport interface FeaturedProductsSection {\n /** Discriminator. */\n type: 'featuredProducts';\n /** Section heading. */\n title?: string;\n /** Product slugs, in display order. Slugs no longer sold are skipped. */\n productSlugs?: string[];\n}\n\n/** `categoryGrid`: a grid of category tiles. */\nexport interface CategoryGridSection {\n /** Discriminator. */\n type: 'categoryGrid';\n /** Category slugs, in display order. Unknown slugs are skipped. */\n categorySlugs?: string[];\n}\n\n/**\n * `richText`: seller-written text. Render it as text or sanitized\n * markdown — never as raw HTML.\n */\nexport interface RichTextSection {\n /** Discriminator. */\n type: 'richText';\n /** The text. */\n content?: string;\n}\n\n/** A section type this SDK knows how to describe. */\nexport type KnownThemeSection =\n HeroSection | FeaturedProductsSection | CategoryGridSection | RichTextSection;\n\n/** A section of a type this SDK version does not know; renderers skip it. */\nexport interface UnknownThemeSection {\n /** The stored type. */\n type: string;\n /** Other stored keys. */\n [key: string]: unknown;\n}\n\n/** A homepage section as stored: a known section or an unknown one. */\nexport type ThemeSection = KnownThemeSection | UnknownThemeSection;\n\nconst KNOWN_SECTION_TYPES: ReadonlySet<string> = new Set([\n 'hero',\n 'featuredProducts',\n 'categoryGrid',\n 'richText',\n]);\n\n/**\n * Whether a stored section is one of the known types. After this guard a\n * `switch (section.type)` narrows to the exact section shape.\n */\nexport function isKnownThemeSection(\n section: unknown,\n): section is KnownThemeSection {\n return (\n typeof section === 'object' &&\n section !== null &&\n typeof (section as { type?: unknown }).type === 'string' &&\n KNOWN_SECTION_TYPES.has((section as { type: string }).type)\n );\n}\n\n/** Social profile URLs; only filled ones are stored. */\nexport interface ThemeSocial {\n /** Instagram profile URL. */\n instagram?: string;\n /** Facebook page URL. */\n facebook?: string;\n /** X profile URL. */\n x?: string;\n /** TikTok profile URL. */\n tiktok?: string;\n /** YouTube channel URL. */\n youtube?: string;\n /** Unknown networks are kept as stored. */\n [key: string]: unknown;\n}\n\n/** Footer configuration. */\nexport interface ThemeFooter {\n /** Footer links, in display order. */\n links?: ThemeLink[];\n /** Social profiles. */\n social?: ThemeSocial;\n /** Unknown footer keys are kept as stored. */\n [key: string]: unknown;\n}\n","import type {\n CheckoutEmbed,\n CheckoutResult,\n ClosedCheckoutPage,\n EmbeddedCheckoutResult,\n RedirectCheckoutResult,\n ClosedCheckoutResult,\n} from './models';\n\n/**\n * What {@link mountPayment} renders: a checkout result, or just its\n * presentation part.\n */\nexport type PaymentPresentation =\n | Pick<EmbeddedCheckoutResult, 'presentation' | 'embed'>\n | Pick<RedirectCheckoutResult, 'presentation' | 'url'>\n | Pick<ClosedCheckoutResult, 'presentation' | 'page'>;\n\n/** Options of {@link mountPayment}. */\nexport interface MountPaymentOptions {\n /**\n * Called for `presentation: \"closed\"` with the page to show (`paid`,\n * `cancelled`, `processing`, …). Typically: go to the order status page.\n */\n onClosed?: (page: ClosedCheckoutPage) => void;\n}\n\n/** The provider form is in the element. */\nexport interface EmbeddedPaymentMount {\n /** Discriminator. */\n kind: 'embedded';\n /** Removes the form from the element. */\n unmount(): void;\n}\n\n/** The browser is navigating to the provider's payment page. */\nexport interface RedirectPaymentMount {\n /** Discriminator. */\n kind: 'redirect';\n /** Where the browser was sent. */\n url: string;\n}\n\n/** Payment cannot be opened; `onClosed` was called. */\nexport interface ClosedPaymentMount {\n /** Discriminator. */\n kind: 'closed';\n /** The page to show. */\n page: ClosedCheckoutPage;\n}\n\n/**\n * The embed has a `kind` this SDK version cannot render. Nothing was put\n * in the element; show a fallback (e.g. \"payment unavailable\").\n */\nexport interface UnsupportedPaymentMount {\n /** Discriminator. */\n kind: 'unsupported';\n /** The embed kind that was not understood. */\n embedKind: string;\n}\n\n/** The result of {@link mountPayment}, discriminated by `kind`. */\nexport type PaymentMount =\n | EmbeddedPaymentMount\n | RedirectPaymentMount\n | ClosedPaymentMount\n | UnsupportedPaymentMount;\n\ninterface MountedForm {\n content: string;\n nodes: Node[];\n unmount: () => void;\n}\n\n/** What each element currently holds, so a repeat mount is a no-op. */\nconst mounted = new WeakMap<Element, MountedForm>();\n\n/**\n * Presents payment from a checkout result. Card data never touches your\n * page's code: the form is the provider's own, or a redirect.\n *\n * - `embedded` (`iyzico-checkout-form`): puts the provider's HTML into\n * `element` and re-creates every `<script>` in it so it executes\n * (`innerHTML` alone never runs scripts). Idempotent per element:\n * mounting the same content again does nothing, other content replaces\n * the previous form — scripts are never injected twice.\n * - `redirect`: top-level navigation to the provider page\n * (`location.assign`). Only `http:` / `https:` URLs are followed.\n * - `closed`: calls `onClosed(page)`.\n *\n * Browser only (needs a DOM).\n *\n * @throws TypeError for a redirect URL that is not `http(s)`.\n */\nexport function mountPayment(\n element: HTMLElement,\n presentation: PaymentPresentation | CheckoutResult,\n options: MountPaymentOptions = {},\n): PaymentMount {\n switch (presentation.presentation) {\n case 'embedded':\n return mountEmbedded(element, presentation.embed);\n case 'redirect': {\n const url = presentation.url;\n let protocol: string;\n try {\n protocol = new URL(url).protocol;\n } catch {\n protocol = '';\n }\n if (protocol !== 'https:' && protocol !== 'http:') {\n throw new TypeError('mountPayment: redirect URL must be http(s)');\n }\n const view = element.ownerDocument.defaultView;\n if (!view) throw new TypeError('mountPayment: element has no window');\n view.location.assign(url);\n return { kind: 'redirect', url };\n }\n case 'closed':\n options.onClosed?.(presentation.page);\n return { kind: 'closed', page: presentation.page };\n }\n}\n\nfunction mountEmbedded(\n element: HTMLElement,\n embed: CheckoutEmbed,\n): EmbeddedPaymentMount | UnsupportedPaymentMount {\n if (\n embed.kind !== 'iyzico-checkout-form' ||\n typeof embed.content !== 'string'\n ) {\n return { kind: 'unsupported', embedKind: String(embed.kind) };\n }\n const content = embed.content;\n const current = mounted.get(element);\n if (\n current &&\n current.content === content &&\n current.nodes.every((n) => n.parentNode === element)\n ) {\n return { kind: 'embedded', unmount: current.unmount };\n }\n\n element.replaceChildren();\n // The provider's own checkout form (from the payments service). It must\n // run its scripts, so it cannot be sanitised; it is the only HTML this\n // SDK ever injects.\n element.innerHTML = content;\n const doc = element.ownerDocument;\n for (const inert of Array.from(element.querySelectorAll('script'))) {\n const live = doc.createElement('script');\n for (const attr of Array.from(inert.attributes)) {\n live.setAttribute(attr.name, attr.value);\n }\n // Dynamically inserted external scripts are async by default; keep\n // document order like the provider's markup expects.\n if (live.hasAttribute('src')) live.async = false;\n live.text = inert.text;\n inert.replaceWith(live);\n }\n const entry: MountedForm = {\n content,\n nodes: Array.from(element.childNodes),\n unmount: () => {\n // A stale handle never removes a newer form.\n if (mounted.get(element) !== entry) return;\n for (const node of entry.nodes) node.parentNode?.removeChild(node);\n mounted.delete(element);\n },\n };\n mounted.set(element, entry);\n return { kind: 'embedded', unmount: entry.unmount };\n}\n","/**\n * Formats an integer amount of minor units (kuruş, cents, …) as a\n * localised currency string with `Intl.NumberFormat`, using the currency's\n * own number of minor digits (2 for `TRY`, 0 for `JPY`).\n *\n * @example formatMoney(14990, 'TRY', 'tr-TR') // \"₺149,90\"\n * @throws TypeError when `minor` is not a finite number; RangeError for an\n * unknown currency code (from `Intl`).\n */\nexport function formatMoney(\n minor: number,\n currency: string,\n locale?: string | string[],\n): string {\n if (typeof minor !== 'number' || !Number.isFinite(minor)) {\n throw new TypeError('formatMoney: minor must be a finite number');\n }\n const format = new Intl.NumberFormat(locale, { style: 'currency', currency });\n const digits = format.resolvedOptions().maximumFractionDigits ?? 2;\n return format.format(minor / 10 ** digits);\n}\n","import type { AdPixels, CookieInfo } from './models';\n\n// Pure helpers for choosing what a store host may load and list. They touch\n// no browser API, so they run in server code (for example a Next.js server\n// component) as well as in the browser.\n\n/** Whether `host` is a default store domain (`suffix` or below it). */\nexport function onDefaultDomain(\n host: string,\n suffix: string | undefined,\n): boolean {\n if (!suffix) return false;\n const h = host.toLowerCase();\n const s = suffix.toLowerCase();\n return h === s || h.endsWith(`.${s}`);\n}\n\n/**\n * The pixels a host may load: Meta and TikTok write their cookies to the\n * registrable domain, which every default store domain shares, so they run\n * only on custom domains.\n */\nexport function pixelsForHost(\n p: AdPixels | undefined,\n defaultDomain: boolean,\n): AdPixels | undefined {\n if (!p || !defaultDomain) return p;\n return p.google ? { google: p.google } : {};\n}\n\n/**\n * The cookies a host lists: on a default domain without the\n * `customDomainOnly` ones, and none at all when no optional cookie is left.\n */\nexport function cookiesForHost(\n cookies: CookieInfo[],\n defaultDomain: boolean,\n): CookieInfo[] {\n if (!defaultDomain) return cookies;\n const kept = cookies.filter((c) => !c.customDomainOnly);\n return kept.some((c) => c.category !== 'necessary') ? kept : [];\n}\n","/**\n * The part of the Web Storage API the cart-id helpers use; `localStorage`,\n * `sessionStorage` or any object with these methods (a cookie adapter, a\n * test double).\n */\nexport interface CartIdStorage {\n /** Reads a value, or null. */\n getItem(key: string): string | null;\n /** Writes a value. */\n setItem(key: string, value: string): void;\n /** Deletes a value. */\n removeItem(key: string): void;\n}\n\n/** The storage key of a store's cart id. Namespaced per store. */\nexport function cartIdKey(storeId: string): string {\n return `storefront:cart:${storeId}`;\n}\n\n/**\n * The saved cart id of a store, or null. Never throws: a missing storage\n * (SSR), a storage that throws (Safari private mode, blocked cookies) or\n * an empty value all read as null.\n */\nexport function loadCartId(\n storage: CartIdStorage | null | undefined,\n storeId: string,\n): string | null {\n try {\n const v = storage?.getItem(cartIdKey(storeId));\n return typeof v === 'string' && v.trim() !== '' ? v.trim() : null;\n } catch {\n return null;\n }\n}\n\n/** Saves a store's cart id. Returns false when the storage refused. Never throws. */\nexport function saveCartId(\n storage: CartIdStorage | null | undefined,\n storeId: string,\n cartId: string,\n): boolean {\n if (!storage) return false;\n try {\n storage.setItem(cartIdKey(storeId), cartId);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Forgets a store's cart id (after `cart_not_found`, or `cart_read_only`\n * with `status: \"expired\"`). Returns false when the storage refused. Never throws.\n */\nexport function clearCartId(\n storage: CartIdStorage | null | undefined,\n storeId: string,\n): boolean {\n if (!storage) return false;\n try {\n storage.removeItem(cartIdKey(storeId));\n return true;\n } catch {\n return false;\n }\n}\n\n/** The part of `document` the cookie storage uses. */\nexport interface CookieJar {\n cookie: string;\n}\n\n/** The cookie carrying the cart ids. */\nconst CART_COOKIE = '__Host-konfiqo_cart';\n/** Largest encoded cookie value written (browsers drop a cookie over ~4 KB). */\nconst MAX_COOKIE_VALUE = 3500;\n/** One year, seconds. */\nconst COOKIE_MAX_AGE = 31_536_000;\n\nfunction readMap(doc: CookieJar): Record<string, string> {\n try {\n for (const part of doc.cookie.split(';')) {\n const p = part.trim();\n if (!p.startsWith(`${CART_COOKIE}=`)) continue;\n const parsed: unknown = JSON.parse(\n decodeURIComponent(p.slice(CART_COOKIE.length + 1)),\n );\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n return {};\n }\n const out: Record<string, string> = {};\n for (const [k, v] of Object.entries(parsed)) {\n if (typeof v === 'string') out[k] = v;\n }\n return out;\n }\n } catch {\n // Malformed cookie: ignored (and replaced by the next write).\n }\n return {};\n}\n\nfunction writeMap(doc: CookieJar, map: Record<string, string>): boolean {\n const attrs = '; Path=/; SameSite=Lax; Secure';\n const keys = Object.keys(map);\n if (keys.length === 0) {\n doc.cookie = `${CART_COOKIE}=; Max-Age=0${attrs}`;\n return true;\n }\n const value = encodeURIComponent(JSON.stringify(map));\n if (value.length > MAX_COOKIE_VALUE) return false;\n doc.cookie = `${CART_COOKIE}=${value}; Max-Age=${COOKIE_MAX_AGE}${attrs}`;\n return true;\n}\n\n/**\n * Cart ids in the first-party `__Host-konfiqo_cart` cookie (path\n * `/`, no `Domain`, `SameSite=Lax`, `Secure`). The `__Host-` prefix makes\n * browsers refuse a cookie of this name scoped to a parent domain, so a\n * sibling store subdomain cannot plant a cart; the old unprefixed\n * `konfiqo_cart` is never read. The value is a JSON map keyed by\n * {@link cartIdKey}, so a store's own frontend and the hosted checkout on the same domain share\n * the cart. `Secure` cookies are dropped by browsers on plain `http`\n * (other than `localhost`), so over http nothing is stored here; pair it\n * with a `localStorage` fallback. Without a document (SSR) it reads nothing and writes fail.\n * Never throws; a malformed or oversized cookie is ignored.\n *\n * @param doc Defaults to the global `document`; `null` disables it.\n */\nexport function cookieCartStorage(doc?: CookieJar | null): CartIdStorage {\n const jar = (): CookieJar | null =>\n doc === undefined\n ? ((globalThis as { document?: CookieJar }).document ?? null)\n : doc;\n return {\n getItem(key) {\n const d = jar();\n if (!d) return null;\n return readMap(d)[key] ?? null;\n },\n setItem(key, value) {\n const d = jar();\n if (!d) throw new Error('no document');\n const map = readMap(d);\n map[key] = value;\n if (!writeMap(d, map)) throw new Error('cart cookie too large');\n },\n removeItem(key) {\n const d = jar();\n if (!d) return;\n const map = readMap(d);\n if (!(key in map)) return;\n delete map[key];\n writeMap(d, map);\n },\n };\n}\n","/**\n * Cloudflare's official Turnstile script, explicit-render mode. The only\n * URL {@link loadTurnstile} ever injects.\n */\nexport const TURNSTILE_SCRIPT_URL =\n 'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit';\n\n/** The subset of Cloudflare's `window.turnstile` API the SDK uses. */\nexport interface TurnstileApi {\n /** Renders a widget into `container`; returns its widget id. */\n render(\n container: HTMLElement | string,\n params: {\n sitekey: string;\n callback?: (token: string) => void;\n 'expired-callback'?: () => void;\n 'error-callback'?: (code?: string) => void;\n [key: string]: unknown;\n },\n ): string | null | undefined;\n /** Resets a widget so it produces a new token. */\n reset(widgetId?: string): void;\n /** Removes a widget. */\n remove(widgetId?: string): void;\n}\n\ntype TurnstileWindow = Window & { turnstile?: TurnstileApi };\n\nconst loading = new WeakMap<Document, Promise<TurnstileApi>>();\n\n/**\n * Loads Cloudflare Turnstile into `document` (once: the script is injected\n * at most once per document, concurrent calls share one load) and resolves\n * with `window.turnstile`. Rejects when the script fails to load; the\n * failed `<script>` is removed, so calling again injects a fresh one.\n */\nexport function loadTurnstile(document: Document): Promise<TurnstileApi> {\n const view = document.defaultView as TurnstileWindow | null;\n if (!view)\n return Promise.reject(\n new TypeError('loadTurnstile: document has no window'),\n );\n if (view.turnstile) return Promise.resolve(view.turnstile);\n const pending = loading.get(document);\n if (pending) return pending;\n\n const promise = new Promise<TurnstileApi>((resolve, reject) => {\n let script = Array.from(document.scripts).find(\n (s) => s.src === TURNSTILE_SCRIPT_URL,\n );\n if (!script) {\n script = document.createElement('script');\n script.src = TURNSTILE_SCRIPT_URL;\n script.async = true;\n (document.head ?? document.documentElement).appendChild(script);\n }\n script.addEventListener('load', () => {\n if (view.turnstile) resolve(view.turnstile);\n else\n reject(\n new Error('loadTurnstile: script loaded without window.turnstile'),\n );\n });\n const tag = script;\n tag.addEventListener('error', () => {\n // A failed tag never loads again: remove it so a retry injects a\n // fresh one instead of waiting on the dead tag forever.\n tag.remove();\n reject(new Error('loadTurnstile: script failed to load'));\n });\n });\n loading.set(document, promise);\n // A failed load can be retried by calling again.\n promise.catch(() => {\n if (loading.get(document) === promise) loading.delete(document);\n });\n return promise;\n}\n\n/** Callbacks of {@link renderTurnstile}. */\nexport interface RenderTurnstileOptions {\n /** A token is ready: keep it for the next `carts.checkout` call. */\n onToken: (token: string) => void;\n /** The token expired unused (about 5 minutes): drop it; the widget refreshes. */\n onExpired?: () => void;\n /** The widget failed (network, unsupported browser, …). */\n onError?: (code?: string) => void;\n}\n\n/** A rendered Turnstile widget. */\nexport interface TurnstileWidget {\n /** The widget id. */\n readonly widgetId: string;\n /**\n * Gets a new token. Call it after every `carts.checkout` that used the\n * current token: tokens are **single-use**.\n */\n reset(): void;\n /** Removes the widget. */\n remove(): void;\n}\n\n/**\n * Renders a Turnstile widget with the store's `siteKey`\n * (`store.checkoutChallenge.siteKey`) into `element`, loading the script\n * first if needed. Pass each token from `onToken` to\n * `carts.checkout(id, { turnstileToken })`, then `reset()`.\n */\nexport async function renderTurnstile(\n element: HTMLElement,\n siteKey: string,\n options: RenderTurnstileOptions,\n): Promise<TurnstileWidget> {\n if (!siteKey) throw new TypeError('renderTurnstile: siteKey is required');\n const turnstile = await loadTurnstile(element.ownerDocument);\n const params: Parameters<TurnstileApi['render']>[1] = {\n sitekey: siteKey,\n callback: (token: string) => options.onToken(token),\n 'expired-callback': () => options.onExpired?.(),\n 'error-callback': (code?: string) => options.onError?.(code),\n };\n const widgetId = turnstile.render(element, params);\n if (!widgetId) throw new Error('renderTurnstile: the widget did not render');\n return {\n widgetId,\n reset: () => turnstile.reset(widgetId),\n remove: () => turnstile.remove(widgetId),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;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;;;AR/HO,IAAM,cAAc;","names":["options","n","document"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1296,6 +1296,6 @@ interface TurnstileWidget {
|
|
|
1296
1296
|
declare function renderTurnstile(element: HTMLElement, siteKey: string, options: RenderTurnstileOptions): Promise<TurnstileWidget>;
|
|
1297
1297
|
|
|
1298
1298
|
/** Version of the Storefront SDK package. */
|
|
1299
|
-
declare const SDK_VERSION = "0.6.
|
|
1299
|
+
declare const SDK_VERSION = "0.6.1";
|
|
1300
1300
|
|
|
1301
1301
|
export { type Account, type AccountOrder, type AccountProfileInput, type AccountSession, type AdPixels, type AddLineInput, type Address, type AddressInput, type AnyStorefrontError, BUYER_IP_HEADER, type BuyerDetailField, type Cart, type CartCustomer, type CartIdStorage, type CartLine, type CartStatus, type Category, type CategoryGridSection, type CategoryList, type CheckoutChallenge, type CheckoutEmbed, type CheckoutEmbedKind, type CheckoutMissing, type CheckoutOptions, type CheckoutResult, type CheckoutResultBase, type ClosedCheckoutPage, type ClosedCheckoutResult, type ClosedPaymentMount, type ContentNode, type CookieCategory, type CookieInfo, type CookieJar, type CustomerInput, DEFAULT_TIMEOUT_MS, type EmbeddedCheckoutResult, type EmbeddedPaymentMount, type FeaturedProductsSection, type HeroSection, type KnownThemeSection, type MountPaymentOptions, type Order, type OrderLine, type OrderShipment, type OrderStatus, PUBLISHABLE_KEY_HEADER, type Pagination, type PaymentMount, type PaymentPresentation, type PaymentStatus, type Product, type ProductListQuery, type ProductPage, type ProductPersonalization, type ProductVariant, type RedirectCheckoutResult, type RedirectPaymentMount, type RenderTurnstileOptions, type RequestCodeOptions, type RequestOptions, type RichTextSection, SDK_VERSION, STOREFRONT_KEY_HEADER, type SavedAddress, type SavedAddressInput, type ShipmentStatus, type ShippingOption, type ShippingOptionList, type ShippingRules, type Store, type StoreContact, type StoreContent, type StoreLegal, type StorefrontApiErrorCode, type StorefrontClient, type StorefrontClientErrorCode, type StorefrontClientOptions, StorefrontError, type StorefrontErrorCode, type StorefrontErrorDetails, type StorefrontErrorDetailsMap, THEME_FONTS, TURNSTILE_SCRIPT_URL, TURNSTILE_TOKEN_HEADER, type ThemeColors, type ThemeFont, type ThemeFooter, type ThemeHomepage, type ThemeLink, type ThemeSection, type ThemeSocial, type ThemeV1, type TurnstileApi, type TurnstileWidget, type UnknownThemeSection, type UnsupportedPaymentMount, type UpdateLineInput, type ValidationIssue, cartIdKey, clearCartId, cookieCartStorage, cookiesForHost, createStorefrontClient, formatMoney, isKnownThemeSection, isStorefrontError, loadCartId, loadTurnstile, mountPayment, onDefaultDomain, pixelsForHost, renderTurnstile, saveCartId };
|
package/dist/index.d.ts
CHANGED
|
@@ -1296,6 +1296,6 @@ interface TurnstileWidget {
|
|
|
1296
1296
|
declare function renderTurnstile(element: HTMLElement, siteKey: string, options: RenderTurnstileOptions): Promise<TurnstileWidget>;
|
|
1297
1297
|
|
|
1298
1298
|
/** Version of the Storefront SDK package. */
|
|
1299
|
-
declare const SDK_VERSION = "0.6.
|
|
1299
|
+
declare const SDK_VERSION = "0.6.1";
|
|
1300
1300
|
|
|
1301
1301
|
export { type Account, type AccountOrder, type AccountProfileInput, type AccountSession, type AdPixels, type AddLineInput, type Address, type AddressInput, type AnyStorefrontError, BUYER_IP_HEADER, type BuyerDetailField, type Cart, type CartCustomer, type CartIdStorage, type CartLine, type CartStatus, type Category, type CategoryGridSection, type CategoryList, type CheckoutChallenge, type CheckoutEmbed, type CheckoutEmbedKind, type CheckoutMissing, type CheckoutOptions, type CheckoutResult, type CheckoutResultBase, type ClosedCheckoutPage, type ClosedCheckoutResult, type ClosedPaymentMount, type ContentNode, type CookieCategory, type CookieInfo, type CookieJar, type CustomerInput, DEFAULT_TIMEOUT_MS, type EmbeddedCheckoutResult, type EmbeddedPaymentMount, type FeaturedProductsSection, type HeroSection, type KnownThemeSection, type MountPaymentOptions, type Order, type OrderLine, type OrderShipment, type OrderStatus, PUBLISHABLE_KEY_HEADER, type Pagination, type PaymentMount, type PaymentPresentation, type PaymentStatus, type Product, type ProductListQuery, type ProductPage, type ProductPersonalization, type ProductVariant, type RedirectCheckoutResult, type RedirectPaymentMount, type RenderTurnstileOptions, type RequestCodeOptions, type RequestOptions, type RichTextSection, SDK_VERSION, STOREFRONT_KEY_HEADER, type SavedAddress, type SavedAddressInput, type ShipmentStatus, type ShippingOption, type ShippingOptionList, type ShippingRules, type Store, type StoreContact, type StoreContent, type StoreLegal, type StorefrontApiErrorCode, type StorefrontClient, type StorefrontClientErrorCode, type StorefrontClientOptions, StorefrontError, type StorefrontErrorCode, type StorefrontErrorDetails, type StorefrontErrorDetailsMap, THEME_FONTS, TURNSTILE_SCRIPT_URL, TURNSTILE_TOKEN_HEADER, type ThemeColors, type ThemeFont, type ThemeFooter, type ThemeHomepage, type ThemeLink, type ThemeSection, type ThemeSocial, type ThemeV1, type TurnstileApi, type TurnstileWidget, type UnknownThemeSection, type UnsupportedPaymentMount, type UpdateLineInput, type ValidationIssue, cartIdKey, clearCartId, cookieCartStorage, cookiesForHost, createStorefrontClient, formatMoney, isKnownThemeSection, isStorefrontError, loadCartId, loadTurnstile, mountPayment, onDefaultDomain, pixelsForHost, renderTurnstile, saveCartId };
|
package/dist/index.js
CHANGED
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors.ts","../src/client.ts","../src/theme.ts","../src/payment.ts","../src/money.ts","../src/host-pixels.ts","../src/cart-storage.ts","../src/turnstile.ts","../src/index.ts"],"sourcesContent":["import type { CartLine, ShippingOption } from './models';\n\n/** `checkout_incomplete`: what the cart still lacks. */\nexport type CheckoutMissing =\n | 'lines'\n | 'customer'\n | 'identityNumber'\n | 'shippingAddress'\n | 'shippingOption';\n\n/**\n * `invalid_buyer_details`: the buyer detail the payment provider refused.\n * Address fields come as `shippingAddress.<field>` / `billingAddress.<field>`.\n */\nexport type BuyerDetailField =\n | 'name'\n | 'surname'\n | 'email'\n | 'phone'\n | 'identityNumber'\n | `shippingAddress.${string}`\n | `billingAddress.${string}`;\n\n/** One validation problem of an `invalid_request`. */\nexport interface ValidationIssue {\n /** Dotted path of the field (`phone`, `shipping.city`, …). */\n path: string;\n /** What is wrong with it (never echoes the submitted value). */\n message: string;\n}\n\n/**\n * The extras each error code carries (`StorefrontError.details`). Codes\n * not listed here carry no details (`undefined`).\n */\nexport interface StorefrontErrorDetailsMap {\n /** Prices or shipping changed: show the new totals, then check out again. */\n cart_changed: {\n lines: CartLine[];\n subtotalMinor: number;\n shippingMinor: number;\n totalMinor: number;\n shippingOptions: ShippingOption[];\n };\n /**\n * A personalization text is refused (400, no details) or, at checkout\n * (409), a line's stored text no longer satisfies the product's rule:\n * `lineIds` are those lines. Remove the line and add it again with a\n * valid text.\n */\n invalid_personalization: { lineIds?: string[] };\n /** These variants cannot be bought (no longer sold, or not enough units). */\n out_of_stock: { variantIds: string[] };\n /** Collect what is missing, then check out again. */\n checkout_incomplete: { missing: CheckoutMissing[] };\n /** Let the buyer fix `field`, then check out again. */\n invalid_buyer_details: { field: BuyerDetailField };\n /** Only `available` units can be added. */\n insufficient_stock: { available: number };\n /** The request body or query failed validation. */\n invalid_request: { issues: ValidationIssue[] };\n /** The cart can no longer change: start a new cart. */\n cart_read_only: { status: 'ordered' | 'expired' };\n /** Throttled. `retryAfter` = seconds to wait, when the response said so. */\n rate_limited: { retryAfter?: number };\n /** No response within `timeoutMs`. */\n timeout: { timeoutMs: number };\n /** The server answered an error code this SDK version does not know. */\n unknown_error: { error: string | null };\n}\n\n/** Error codes of the Storefront API (the `error` field of an error response). */\nexport type StorefrontApiErrorCode =\n | 'store_not_found'\n | 'origin_not_allowed'\n | 'invalid_request'\n | 'invalid_buyer_ip'\n | 'catalog_unavailable'\n | 'product_not_found'\n | 'content_not_found'\n | 'cart_not_found'\n | 'variant_not_found'\n | 'line_not_found'\n | 'insufficient_stock'\n | 'quantity_out_of_range'\n | 'too_many_lines'\n | 'invalid_shipping_option'\n | 'cart_read_only'\n | 'checkout_in_progress'\n | 'checkout_incomplete'\n | 'cart_changed'\n | 'invalid_personalization'\n | 'out_of_stock'\n | 'amount_out_of_range'\n | 'nothing_to_pay'\n | 'invalid_buyer_details'\n | 'payment_unavailable'\n | 'checkout_unavailable'\n | 'order_not_found'\n | 'order_unavailable'\n | 'media_not_found'\n | 'media_unavailable'\n | 'challenge_required'\n | 'challenge_failed'\n | 'challenge_unavailable'\n | 'too_many_open_orders'\n | 'not_signed_in'\n | 'invalid_code'\n | 'profile_required'\n | 'too_many_code_requests'\n | 'invalid_recovery_token'\n | 'cart_not_recoverable'\n | 'unavailable';\n\n/**\n * Codes the SDK assigns itself:\n * - `rate_limited` — HTTP 429 without a known `error` code (the throttler);\n * - `unauthorized` — HTTP 401 without a code (a wrong `trustedStorefrontKey`);\n * - `http_error` — any other non-2xx response without an `error` code;\n * - `unknown_error` — an `error` code this SDK version does not know (in `details.error`);\n * - `invalid_response` — a 2xx response that is not JSON;\n * - `network_error` — no readable response: the API was unreachable (DNS,\n * TLS, offline), or, in a browser, the origin is allowed by no store;\n * - `timeout` — no response within `timeoutMs`;\n * - `aborted` — the caller's `signal` aborted the request.\n */\nexport type StorefrontClientErrorCode =\n | 'rate_limited'\n | 'unauthorized'\n | 'http_error'\n | 'unknown_error'\n | 'invalid_response'\n | 'network_error'\n | 'timeout'\n | 'aborted';\n\n/** Every code a {@link StorefrontError} can have. */\nexport type StorefrontErrorCode =\n StorefrontApiErrorCode | StorefrontClientErrorCode;\n\n/** The `details` type of an error code (`undefined` for codes without extras). */\nexport type StorefrontErrorDetails<C extends StorefrontErrorCode> =\n C extends keyof StorefrontErrorDetailsMap\n ? StorefrontErrorDetailsMap[C]\n : undefined;\n\nconst API_CODES: ReadonlySet<string> = new Set<StorefrontApiErrorCode>([\n 'store_not_found',\n 'origin_not_allowed',\n 'invalid_request',\n 'invalid_buyer_ip',\n 'catalog_unavailable',\n 'product_not_found',\n 'content_not_found',\n 'cart_not_found',\n 'variant_not_found',\n 'line_not_found',\n 'insufficient_stock',\n 'quantity_out_of_range',\n 'too_many_lines',\n 'invalid_shipping_option',\n 'cart_read_only',\n 'checkout_in_progress',\n 'checkout_incomplete',\n 'cart_changed',\n 'invalid_personalization',\n 'out_of_stock',\n 'amount_out_of_range',\n 'nothing_to_pay',\n 'invalid_buyer_details',\n 'payment_unavailable',\n 'checkout_unavailable',\n 'order_not_found',\n 'order_unavailable',\n 'media_not_found',\n 'media_unavailable',\n 'challenge_required',\n 'challenge_failed',\n 'challenge_unavailable',\n 'too_many_open_orders',\n 'not_signed_in',\n 'invalid_code',\n 'profile_required',\n 'too_many_code_requests',\n 'invalid_recovery_token',\n 'cart_not_recoverable',\n 'unavailable',\n]);\n\n/**\n * Marks every {@link StorefrontError}. A global (`Symbol.for`) symbol, so\n * an error thrown by one installed copy of the SDK is recognised by another\n * (e.g. the React package resolving its own copy), where `instanceof` fails.\n */\nconst ERROR_BRAND = Symbol.for('@konfiqo/storefront-sdk/error');\n\n/**\n * Every failure of a client call: an API error response, a throttle, a\n * timeout or a transport failure. Switch on `code`, never on `message`.\n *\n * To get `details` typed per code, narrow with {@link isStorefrontError}\n * (which yields the {@link AnyStorefrontError} union) and `switch (e.code)`,\n * or test one code with `e.is('cart_changed')`.\n */\nexport class StorefrontError<\n C extends StorefrontErrorCode = StorefrontErrorCode,\n> extends Error {\n /** The API `error` code, or one of the SDK's own codes. */\n readonly code: C;\n /** HTTP status; `0` when no response arrived (`network_error`, `timeout`). */\n readonly status: number;\n /** The code's extras (see {@link StorefrontErrorDetailsMap}). */\n readonly details: StorefrontErrorDetails<C>;\n\n /**\n * @param code - the error code\n * @param status - the HTTP status (`0` without a response)\n * @param message - a human-readable description (not for display logic)\n * @param details - the code's extras\n * @param options - `cause`: the underlying error, if any\n */\n constructor(\n code: C,\n status: number,\n message: string,\n details: StorefrontErrorDetails<C>,\n options?: { cause?: unknown },\n ) {\n super(message, options);\n this.name = 'StorefrontError';\n this.code = code;\n this.status = status;\n this.details = details;\n Object.defineProperty(this, ERROR_BRAND, { value: true });\n }\n\n /** Whether this error has `code`; narrows `details` to that code's extras. */\n is<K extends StorefrontErrorCode>(code: K): this is StorefrontError<K> {\n return (this.code as StorefrontErrorCode) === code;\n }\n}\n\n/**\n * The union of {@link StorefrontError} by code: after narrowing `code`\n * (e.g. in a `switch`), `details` has that code's type.\n */\nexport type AnyStorefrontError = {\n [C in StorefrontErrorCode]: StorefrontError<C>;\n}[StorefrontErrorCode];\n\n/**\n * Whether `e` is a {@link StorefrontError}, as the code-discriminated union.\n * Also true for an error from another copy of this SDK (checked by a global\n * brand, not only `instanceof`).\n */\nexport function isStorefrontError(e: unknown): e is AnyStorefrontError {\n return (\n e instanceof StorefrontError ||\n (typeof e === 'object' &&\n e !== null &&\n (e as Record<symbol, unknown>)[ERROR_BRAND] === true)\n );\n}\n\nconst isObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === 'object' && v !== null && !Array.isArray(v);\n\n/** Seconds from a `Retry-After` value (delta-seconds or an HTTP date). */\nfunction parseRetryAfter(value: string | null): number | undefined {\n if (value === null) return undefined;\n const trimmed = value.trim();\n if (/^\\d+$/.test(trimmed)) return Number(trimmed);\n const at = Date.parse(trimmed);\n if (Number.isNaN(at)) return undefined;\n return Math.max(0, Math.ceil((at - Date.now()) / 1000));\n}\n\n/**\n * Builds the error for a non-2xx response from its status, body (parsed\n * JSON, or undefined) and headers. Internal.\n */\nexport function errorFromResponse(\n status: number,\n body: unknown,\n headers: Headers,\n): AnyStorefrontError {\n const b = isObject(body) ? body : {};\n const message =\n typeof b.message === 'string' && b.message !== ''\n ? b.message\n : `Storefront API request failed (HTTP ${status})`;\n\n const error = typeof b.error === 'string' ? b.error : null;\n // A 429 with a known code (`too_many_open_orders`) is that code; the\n // throttler's 429 carries none.\n if (status === 429 && (error === null || !API_CODES.has(error))) {\n // The throttler names its header per limit (`Retry-After`,\n // `Retry-After-ip`); when both come, the longer wait is the real one.\n const waits = [\n parseRetryAfter(headers.get('retry-after')),\n parseRetryAfter(headers.get('retry-after-ip')),\n ].filter((w): w is number => w !== undefined);\n const retryAfter = waits.length > 0 ? Math.max(...waits) : undefined;\n return new StorefrontError(\n 'rate_limited',\n status,\n message,\n retryAfter === undefined ? {} : { retryAfter },\n );\n }\n\n if (error === null) {\n if (status === 401)\n return new StorefrontError('unauthorized', status, message, undefined);\n return new StorefrontError('http_error', status, message, undefined);\n }\n if (!API_CODES.has(error)) {\n return new StorefrontError('unknown_error', status, message, { error });\n }\n const code = error as StorefrontApiErrorCode;\n return apiError(code, status, message, b);\n}\n\nconst arr = <T>(v: unknown): T[] => (Array.isArray(v) ? (v as T[]) : []);\nconst n = (v: unknown): number => (typeof v === 'number' ? v : 0);\n\nfunction apiError(\n code: StorefrontApiErrorCode,\n status: number,\n message: string,\n b: Record<string, unknown>,\n): AnyStorefrontError {\n switch (code) {\n case 'cart_changed':\n return new StorefrontError(code, status, message, {\n lines: arr<CartLine>(b.lines),\n subtotalMinor: n(b.subtotalMinor),\n shippingMinor: n(b.shippingMinor),\n totalMinor: n(b.totalMinor),\n shippingOptions: arr<ShippingOption>(b.shippingOptions),\n });\n case 'invalid_personalization':\n return new StorefrontError(\n code,\n status,\n message,\n Array.isArray(b.lineIds) ? { lineIds: arr<string>(b.lineIds) } : {},\n );\n case 'out_of_stock':\n return new StorefrontError(code, status, message, {\n variantIds: arr<string>(b.variantIds),\n });\n case 'checkout_incomplete':\n return new StorefrontError(code, status, message, {\n missing: arr<CheckoutMissing>(b.missing),\n });\n case 'invalid_buyer_details':\n return new StorefrontError(code, status, message, {\n field: String(b.field ?? '') as BuyerDetailField,\n });\n case 'insufficient_stock':\n return new StorefrontError(code, status, message, {\n available: n(b.available),\n });\n case 'invalid_request':\n return new StorefrontError(code, status, message, {\n issues: arr<ValidationIssue>(b.issues),\n });\n case 'cart_read_only':\n return new StorefrontError(code, status, message, {\n status: b.status === 'ordered' ? 'ordered' : 'expired',\n });\n default:\n return new StorefrontError(\n code,\n status,\n message,\n undefined,\n ) as AnyStorefrontError;\n }\n}\n","import { StorefrontError, errorFromResponse } from './errors';\nimport type {\n AddLineInput,\n AddressInput,\n Account,\n AccountProfileInput,\n AccountSession,\n Cart,\n CategoryList,\n CheckoutResult,\n CustomerInput,\n Order,\n Product,\n ProductListQuery,\n ProductPage,\n SavedAddress,\n SavedAddressInput,\n ShippingOptionList,\n Store,\n StoreContent,\n UpdateLineInput,\n} from './models';\n\n/** Default request timeout, milliseconds. */\nexport const DEFAULT_TIMEOUT_MS = 15_000;\n\n/** Header carrying the publishable key on every request. */\nexport const PUBLISHABLE_KEY_HEADER = 'x-konfiqo-publishable-key';\n/** Header carrying the trusted storefront key (server-side only). */\nexport const STOREFRONT_KEY_HEADER = 'x-konfiqo-storefront-key';\n/** Header carrying the store's server key (server-side only). */\nexport const SERVER_KEY_HEADER = 'x-konfiqo-server-key';\n/** Header carrying the checkout challenge token (checkout only). */\nexport const TURNSTILE_TOKEN_HEADER = 'x-konfiqo-turnstile-token';\n/** Header carrying the buyer's IP (only with a server key or the trusted storefront key). */\nexport const BUYER_IP_HEADER = 'x-konfiqo-buyer-ip';\n\n/** Per-call options, accepted as the last argument of every method. */\nexport interface RequestOptions {\n /**\n * Aborts the request: it rejects with code `aborted`. Combined with the\n * client timeout (whichever comes first wins).\n */\n signal?: AbortSignal;\n /**\n * **Server-side only.** A `Cookie` header to forward, so a server-rendered\n * storefront can call the account routes as the buyer: pass the incoming\n * request's `cookie` header (or just `konfiqo_session=<value>`). Browsers\n * ignore a `Cookie` header set from script; there the session cookie rides\n * along automatically (`credentials: 'include'`).\n */\n cookie?: string;\n}\n\n/** Options of `account.requestCode`. */\nexport interface RequestCodeOptions extends RequestOptions {\n /**\n * The challenge token (Cloudflare Turnstile), required when the store\n * asks for one (`store.checkoutChallenge`). Single-use. Sent as\n * `x-konfiqo-turnstile-token`.\n */\n turnstileToken?: string;\n}\n\n/** Options of `carts.checkout`. */\nexport interface CheckoutOptions extends RequestOptions {\n /**\n * The checkout challenge token (Cloudflare Turnstile), required when\n * `store.checkoutChallenge` is set. Single-use: get a new one (reset the\n * widget) for every checkout call. Sent as `x-konfiqo-turnstile-token`.\n */\n turnstileToken?: string;\n}\n\n/** Options of {@link createStorefrontClient}. */\nexport interface StorefrontClientOptions {\n /**\n * The Storefront API base: `https://<store domain>/api` (or the relative\n * `/api` in a same-origin browser app). Requests go to `${baseUrl}/v1/...`,\n * so do not include `/v1`.\n */\n baseUrl: string;\n /** The store's publishable key (`pk_live_…` / `pk_test_…`). Public. */\n publishableKey: string;\n /** A `fetch` implementation; defaults to the global `fetch`. */\n fetch?: typeof fetch;\n /** Per-request timeout in milliseconds (default {@link DEFAULT_TIMEOUT_MS}). */\n timeoutMs?: number;\n /**\n * **Server-side only.** The shared storefront key that lets a server-side\n * renderer report the real buyer IP (`buyerIp`), so throttling and the\n * payment provider see the buyer instead of the server. Sent as\n * `x-konfiqo-storefront-key`. Constructing a client with it where\n * `window` exists throws: never ship this key to a browser.\n */\n trustedStorefrontKey?: string;\n /**\n * **Server-side only.** The store's own server key, minted by the store\n * operator. It lets the seller's server report the real buyer IP\n * (`buyerIp`). Sent as `x-konfiqo-server-key` next to the publishable\n * key. Needs `buyerIp`, cannot be combined with `trustedStorefrontKey`,\n * and constructing a client with it in a browser throws.\n */\n serverKey?: string;\n /**\n * The buyer's IP address, sent as `x-konfiqo-buyer-ip`. Required with\n * `serverKey` or `trustedStorefrontKey`, ignored without one. Create one\n * client per incoming request on the server.\n */\n buyerIp?: string;\n}\n\n/**\n * A typed client of the Storefront API (`/v1`).\n *\n * Every method returns the response body, or rejects with a\n * {@link StorefrontError}. Nothing is retried: whether to retry is the\n * caller's decision, because writes are not safely repeatable — in\n * particular `carts.checkout` on a cart whose order failed places a\n * **new** order, so a blind retry could open a second payment.\n */\nexport interface StorefrontClient {\n /**\n * `GET /v1/content/:key`: a piece of store content as a renderable\n * Markdoc tree. Rejects `content_not_found` (404) for an unknown key.\n */\n getContent(key: string, options?: RequestOptions): Promise<StoreContent>;\n /** Store information. */\n readonly store: {\n /** `GET /v1/store`: name, language, currency, logo, theme, contact, legal texts, shipping rules. */\n get(options?: RequestOptions): Promise<Store>;\n };\n /** Categories. */\n readonly categories: {\n /** `GET /v1/categories`: the active category tree. */\n list(options?: RequestOptions): Promise<CategoryList>;\n };\n /** Products. */\n readonly products: {\n /** `GET /v1/products`: a page of products, optionally filtered. */\n list(\n query?: ProductListQuery,\n options?: RequestOptions,\n ): Promise<ProductPage>;\n /** `GET /v1/products/:slug`. Rejects with `product_not_found`. */\n get(slug: string, options?: RequestOptions): Promise<Product>;\n };\n /** Carts. Every cart write answers the updated cart. */\n readonly carts: {\n /** `POST /v1/carts`: a new, empty cart. */\n create(options?: RequestOptions): Promise<Cart>;\n /**\n * `POST /v1/carts/recover`: turns the `t` token of an abandoned-cart\n * e-mail link into a **new** cart with the same lines (no buyer data).\n * Rejects `invalid_recovery_token` (400) or `cart_not_recoverable` (410:\n * the cart was ordered, expired or deleted).\n */\n recover(\n token: string,\n options?: RequestOptions,\n ): Promise<{ cartId: string }>;\n /** `GET /v1/carts/:id`. Also reopens a cart whose payment failed. */\n get(cartId: string, options?: RequestOptions): Promise<Cart>;\n /** `POST /v1/carts/:id/lines`: adds units of a variant. */\n addLine(\n cartId: string,\n input: AddLineInput,\n options?: RequestOptions,\n ): Promise<Cart>;\n /**\n * `PATCH /v1/carts/:id/lines/:lineId`: sets a line's quantity. `lineId`\n * is `CartLine.id`; a variant id still matches a line without text.\n */\n updateLine(\n cartId: string,\n lineId: string,\n input: UpdateLineInput,\n options?: RequestOptions,\n ): Promise<Cart>;\n /** `DELETE /v1/carts/:id/lines/:lineId`: removes a line (`CartLine.id`). */\n removeLine(\n cartId: string,\n lineId: string,\n options?: RequestOptions,\n ): Promise<Cart>;\n /** `PUT /v1/carts/:id/customer`: sets the buyer. */\n setCustomer(\n cartId: string,\n input: CustomerInput,\n options?: RequestOptions,\n ): Promise<Cart>;\n /** `PUT /v1/carts/:id/address`: sets the shipping (and billing) address. */\n setAddress(\n cartId: string,\n input: AddressInput,\n options?: RequestOptions,\n ): Promise<Cart>;\n /** `GET /v1/carts/:id/shipping-options`: the options this cart can use. */\n shippingOptions(\n cartId: string,\n options?: RequestOptions,\n ): Promise<ShippingOptionList>;\n /** `PUT /v1/carts/:id/shipping-option`: selects a shipping option by id. */\n setShippingOption(\n cartId: string,\n optionId: string,\n options?: RequestOptions,\n ): Promise<Cart>;\n /**\n * `POST /v1/carts/:id/checkout`: places the order (or re-opens payment\n * for the cart's order) and answers how to present payment. Keep the\n * returned `token`: it is returned only once. Not retried.\n *\n * Aborting (`signal`) only stops waiting: the server may still place\n * the order. Read the cart again before showing a result.\n *\n * When `store.checkoutChallenge` is set, pass a fresh\n * `turnstileToken` (see `renderTurnstile`); tokens are single-use, so\n * reset the widget after every call. Re-opening payment on an already\n * ordered cart needs no token.\n */\n checkout(\n cartId: string,\n options?: CheckoutOptions,\n ): Promise<CheckoutResult>;\n };\n /** Buyer order status. */\n readonly orders: {\n /** `GET /v1/orders/:id?token=`: the order, for the buyer holding its token. */\n get(\n orderId: string,\n token: string,\n options?: RequestOptions,\n ): Promise<Order>;\n };\n /**\n * The signed-in buyer's account. Sign-in is by an e-mailed one-time code;\n * the session is an HttpOnly cookie (`konfiqo_session`) the API sets on the\n * store origin, so these calls send `credentials: 'include'`. On a server,\n * forward the buyer's cookie with the `cookie` call option.\n */\n readonly account: {\n /**\n * `POST /v1/account/code`: e-mails a 6-digit code. Resolves the same for\n * any address (202); rejects `too_many_code_requests` (429),\n * `challenge_required` / `challenge_failed`, `invalid_request`.\n */\n requestCode(email: string, options?: RequestCodeOptions): Promise<void>;\n /**\n * `POST /v1/account/session`: signs in with the code. A wrong, spent or\n * expired code rejects `invalid_code` (401).\n */\n signIn(\n email: string,\n code: string,\n options?: RequestOptions,\n ): Promise<AccountSession>;\n /** `DELETE /v1/account/session`: signs out (always succeeds). */\n signOut(options?: RequestOptions): Promise<void>;\n /**\n * `GET /v1/account[?page=]`: profile, saved addresses and a page of\n * orders (20 per page, newest first). Rejects `not_signed_in` (401).\n */\n get(page?: number, options?: RequestOptions): Promise<Account>;\n /**\n * `PUT /v1/account/profile`: saves name, surname and a Turkish mobile\n * phone. Creates the buyer's record on first save.\n */\n updateProfile(\n profile: AccountProfileInput,\n options?: RequestOptions,\n ): Promise<void>;\n /**\n * `PUT /v1/account/addresses`: replaces the saved addresses (at most 5,\n * at most one default). Resolves the list as stored (ids filled in).\n * Rejects `profile_required` (409) until a profile is saved.\n */\n saveAddresses(\n addresses: SavedAddressInput[],\n options?: RequestOptions,\n ): Promise<SavedAddress[]>;\n };\n /** Catalog images. */\n readonly media: {\n /**\n * The absolute URL of a storage key (product `image`, store `logo`,\n * theme `logo` / `favicon` / section `image`), usable in `<img src>`:\n * `${baseUrl}/v1/media/<key, each segment encoded>?pk=<publishable key>`.\n *\n * @throws TypeError (`invalid_path_segment`) when a key segment is\n * empty, `.` or `..`.\n */\n url(key: string): string;\n };\n}\n\ntype Method = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n\n/**\n * One encoded path segment. `encodeURIComponent` leaves `.` and `..` as\n * they are, and URL normalisation would turn them into another route, so\n * those (and an empty segment) are refused.\n */\nfunction seg(v: string): string {\n if (typeof v !== 'string' || v === '' || v === '.' || v === '..') {\n throw new TypeError(\n `invalid_path_segment: ${JSON.stringify(v)} is not a valid path segment`,\n );\n }\n return encodeURIComponent(v);\n}\n\n/** Whether this host looks like a browser or a web worker. */\nfunction isBrowserLike(): boolean {\n const g = globalThis as { importScripts?: unknown };\n return (\n typeof window !== 'undefined' ||\n typeof document !== 'undefined' ||\n (typeof self !== 'undefined' && typeof g.importScripts === 'function')\n );\n}\n\n/**\n * Creates a Storefront API client.\n *\n * @throws TypeError when `baseUrl` or `publishableKey` is empty, when\n * `serverKey` or `trustedStorefrontKey` is given without `buyerIp`, when\n * both keys are given together, or when either key is given in a\n * browser-like host (`window` or `document` defined, or a web worker).\n * Hosts that define `window` on a server (jsdom, Electron renderers,\n * React Native) are refused too: keep these keys in a plain server process.\n */\nexport function createStorefrontClient(\n options: StorefrontClientOptions,\n): StorefrontClient {\n const baseUrl = options.baseUrl?.trim().replace(/\\/+$/, '');\n if (!baseUrl)\n throw new TypeError('createStorefrontClient: baseUrl is required');\n const publishableKey = options.publishableKey?.trim();\n if (!publishableKey)\n throw new TypeError('createStorefrontClient: publishableKey is required');\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n if (!(timeoutMs > 0) || !Number.isFinite(timeoutMs)) {\n throw new TypeError(\n 'createStorefrontClient: timeoutMs must be a positive number',\n );\n }\n\n const baseHeaders: Record<string, string> = {\n [PUBLISHABLE_KEY_HEADER]: publishableKey,\n };\n if (\n options.serverKey !== undefined &&\n options.trustedStorefrontKey !== undefined\n ) {\n throw new TypeError(\n 'createStorefrontClient: serverKey and trustedStorefrontKey cannot be used together',\n );\n }\n if (options.serverKey !== undefined) {\n if (isBrowserLike()) {\n throw new TypeError(\n 'createStorefrontClient: serverKey must never be used in a browser',\n );\n }\n const buyerIp = options.buyerIp?.trim();\n if (!buyerIp) {\n throw new TypeError(\n 'createStorefrontClient: buyerIp is required with serverKey',\n );\n }\n baseHeaders[SERVER_KEY_HEADER] = options.serverKey;\n baseHeaders[BUYER_IP_HEADER] = buyerIp;\n }\n if (options.trustedStorefrontKey !== undefined) {\n if (isBrowserLike()) {\n throw new TypeError(\n 'createStorefrontClient: trustedStorefrontKey is server-only and must never be used in a browser',\n );\n }\n const buyerIp = options.buyerIp?.trim();\n if (!buyerIp) {\n throw new TypeError(\n 'createStorefrontClient: buyerIp is required with trustedStorefrontKey',\n );\n }\n baseHeaders[STOREFRONT_KEY_HEADER] = options.trustedStorefrontKey;\n baseHeaders[BUYER_IP_HEADER] = buyerIp;\n }\n\n async function request<T>(\n method: Method,\n path: () => string,\n body?: unknown,\n callOptions?: RequestOptions,\n extraHeaders: Record<string, string> = {},\n flags: { credentials?: boolean; emptyOk?: boolean } = {},\n ): Promise<T> {\n const url = `${baseUrl}${path()}`;\n const callerSignal = callOptions?.signal;\n if (callerSignal?.aborted) throw abortError(callerSignal);\n // Resolved per call (not at construction) so a polyfilled global works.\n // Called detached: a browser `fetch` must not be invoked on another `this`.\n const doFetch = options.fetch ?? globalThis.fetch;\n const headers: Record<string, string> = {\n ...baseHeaders,\n ...extraHeaders,\n };\n if (callOptions?.cookie) headers.cookie = callOptions.cookie;\n const init: RequestInit = { method, headers };\n if (flags.credentials) init.credentials = 'include';\n if (body !== undefined) {\n headers['content-type'] = 'application/json';\n init.body = JSON.stringify(body);\n }\n const controller = new AbortController();\n init.signal = controller.signal;\n let timedOut = false;\n // Raced as well as aborted: a custom `fetch` that ignores the signal\n // still cannot hold the caller past the timeout.\n let onTimeout: (e: StorefrontError) => void = () => {};\n const deadline = new Promise<never>((_, reject) => {\n onTimeout = reject;\n });\n deadline.catch(() => {});\n const timer = setTimeout(() => {\n timedOut = true;\n onTimeout(transportError(undefined, true, timeoutMs));\n controller.abort();\n }, timeoutMs);\n const onCallerAbort = () => {\n onTimeout(abortError(callerSignal!));\n controller.abort();\n };\n callerSignal?.addEventListener('abort', onCallerAbort, { once: true });\n\n try {\n let res: Response;\n let text: string;\n try {\n res = await Promise.race([doFetch(url, init), deadline]);\n text = await Promise.race([res.text(), deadline]);\n } catch (e) {\n if (e instanceof StorefrontError) throw e;\n throw transportError(e, timedOut, timeoutMs);\n }\n let parsed: unknown;\n let isJson = false;\n if (text !== '') {\n try {\n parsed = JSON.parse(text);\n isJson = true;\n } catch {\n parsed = undefined;\n }\n }\n if (!res.ok) throw errorFromResponse(res.status, parsed, res.headers);\n if (!isJson && flags.emptyOk && text === '') return undefined as T;\n if (!isJson) {\n throw new StorefrontError(\n 'invalid_response',\n res.status,\n 'Storefront API answered a non-JSON body',\n undefined,\n );\n }\n return parsed as T;\n } finally {\n clearTimeout(timer);\n callerSignal?.removeEventListener('abort', onCallerAbort);\n }\n }\n\n const get = <T>(path: () => string, options?: RequestOptions) =>\n request<T>('GET', path, undefined, options);\n const acct = { credentials: true } as const;\n const send = <T>(\n method: Method,\n path: string,\n body: unknown,\n o?: RequestOptions,\n extra: Record<string, string> = {},\n emptyOk = false,\n ) => request<T>(method, () => path, body, o, extra, { ...acct, emptyOk });\n const cart = (id: string) => `/v1/carts/${seg(id)}`;\n\n return {\n getContent: (key, o) =>\n get<StoreContent>(() => `/v1/content/${seg(key)}`, o),\n store: {\n get: (o) => get<Store>(() => '/v1/store', o),\n },\n categories: {\n list: (o) => get<CategoryList>(() => '/v1/categories', o),\n },\n products: {\n list: (query = {}, o) =>\n get<ProductPage>(() => {\n const params = new URLSearchParams();\n if (query.category !== undefined)\n params.set('category', query.category);\n if (query.q !== undefined) params.set('q', query.q);\n if (query.page !== undefined) params.set('page', String(query.page));\n if (query.pageSize !== undefined)\n params.set('pageSize', String(query.pageSize));\n const qs = params.toString();\n return `/v1/products${qs ? `?${qs}` : ''}`;\n }, o),\n get: (slug, o) => get<Product>(() => `/v1/products/${seg(slug)}`, o),\n },\n carts: {\n create: (o) => request<Cart>('POST', () => '/v1/carts', undefined, o),\n recover: (token, o) =>\n request<{ cartId: string }>(\n 'POST',\n () => '/v1/carts/recover',\n { token },\n o,\n ),\n get: (cartId, o) => get<Cart>(() => cart(cartId), o),\n addLine: (cartId, input, o) =>\n request<Cart>(\n 'POST',\n () => `${cart(cartId)}/lines`,\n {\n variantId: input.variantId,\n quantity: input.quantity,\n ...(input.personalization !== undefined && {\n personalization: input.personalization,\n }),\n },\n o,\n ),\n updateLine: (cartId, lineId, input, o) =>\n request<Cart>(\n 'PATCH',\n () => `${cart(cartId)}/lines/${seg(lineId)}`,\n { quantity: input.quantity },\n o,\n ),\n removeLine: (cartId, lineId, o) =>\n request<Cart>(\n 'DELETE',\n () => `${cart(cartId)}/lines/${seg(lineId)}`,\n undefined,\n o,\n ),\n setCustomer: (cartId, input, o) =>\n request<Cart>('PUT', () => `${cart(cartId)}/customer`, input, o),\n setAddress: (cartId, input, o) =>\n request<Cart>('PUT', () => `${cart(cartId)}/address`, input, o),\n shippingOptions: (cartId, o) =>\n get<ShippingOptionList>(() => `${cart(cartId)}/shipping-options`, o),\n setShippingOption: (cartId, optionId, o) =>\n request<Cart>(\n 'PUT',\n () => `${cart(cartId)}/shipping-option`,\n { id: optionId },\n o,\n ),\n checkout: (cartId, o) =>\n request<CheckoutResult>(\n 'POST',\n () => `${cart(cartId)}/checkout`,\n undefined,\n o,\n o?.turnstileToken\n ? { [TURNSTILE_TOKEN_HEADER]: o.turnstileToken }\n : {},\n ),\n },\n orders: {\n get: (orderId, token, o) =>\n get<Order>(\n () => `/v1/orders/${seg(orderId)}?token=${encodeURIComponent(token)}`,\n o,\n ),\n },\n account: {\n requestCode: (email, o) =>\n send<void>(\n 'POST',\n '/v1/account/code',\n { email },\n o,\n o?.turnstileToken\n ? { [TURNSTILE_TOKEN_HEADER]: o.turnstileToken }\n : {},\n true,\n ),\n signIn: (email, code, o) =>\n send<AccountSession>('POST', '/v1/account/session', { email, code }, o),\n signOut: (o) =>\n send<void>('DELETE', '/v1/account/session', undefined, o, {}, true),\n get: (page, o) =>\n send<Account>(\n 'GET',\n page === undefined\n ? '/v1/account'\n : `/v1/account?page=${encodeURIComponent(String(page))}`,\n undefined,\n o,\n ),\n updateProfile: (profile, o) =>\n send<void>(\n 'PUT',\n '/v1/account/profile',\n {\n name: profile.name,\n surname: profile.surname,\n phone: profile.phone,\n },\n o,\n {},\n true,\n ),\n saveAddresses: async (addresses, o) =>\n (\n await send<{ addresses: SavedAddress[] }>(\n 'PUT',\n '/v1/account/addresses',\n { addresses },\n o,\n )\n ).addresses,\n },\n media: {\n url: (key) =>\n `${baseUrl}/v1/media/${key.split('/').map(seg).join('/')}?pk=${encodeURIComponent(publishableKey)}`,\n },\n };\n}\n\n/** The caller aborted the request (`options.signal`). */\nfunction abortError(signal: AbortSignal): StorefrontError {\n return new StorefrontError(\n 'aborted',\n 0,\n 'Storefront API request was aborted',\n undefined,\n { cause: signal.reason },\n );\n}\n\n/** A fetch / body-read failure as `timeout` or `network_error`. */\nfunction transportError(\n e: unknown,\n timedOut: boolean,\n timeoutMs: number,\n): StorefrontError {\n if (timedOut) {\n return new StorefrontError(\n 'timeout',\n 0,\n `Storefront API did not answer within ${timeoutMs} ms`,\n { timeoutMs },\n { cause: e },\n );\n }\n return new StorefrontError(\n 'network_error',\n 0,\n 'Storefront API could not be reached',\n undefined,\n {\n cause: e,\n },\n );\n}\n","/**\n * Store theme, `schemaVersion: 1` (the commerce module's \"Store settings\n * JSON\"). The Storefront API passes the theme through **as stored**: it is\n * not validated, so every field is optional and a renderer must tolerate\n * missing values, wrong types and keys it does not know. Image fields are\n * tenant storage keys — turn them into URLs with `client.media.url(key)`.\n */\nexport interface ThemeV1 {\n /** `1` for this shape. Anything else: render defaults. */\n schemaVersion?: number;\n /** Storage key of the logo (the same key as the store's `logo`). */\n logo?: string | null;\n /** Storage key of the favicon. */\n favicon?: string | null;\n /** Theme colors, CSS color strings (normally `#rrggbb`). */\n colors?: ThemeColors;\n /** One of {@link THEME_FONTS}; an unknown value means \"use the default font\". */\n font?: ThemeFont | (string & {});\n /** The homepage, as ordered sections. */\n homepage?: ThemeHomepage;\n /** Footer links and social profiles. */\n footer?: ThemeFooter;\n /** Keys this SDK version does not know are kept as stored. */\n [key: string]: unknown;\n}\n\n/** Theme colors. Each is a CSS color string; any may be missing. */\nexport interface ThemeColors {\n /** Primary brand color. */\n primary?: string;\n /** Accent (links, highlights). */\n accent?: string;\n /** Page background. */\n background?: string;\n /** Body text. */\n text?: string;\n /** Unknown color keys are kept as stored. */\n [key: string]: unknown;\n}\n\n/** The fonts a v1 theme may name. */\nexport const THEME_FONTS = [\n 'inter',\n 'roboto',\n 'open-sans',\n 'lato',\n 'poppins',\n] as const;\n\n/** A font a v1 theme may name. */\nexport type ThemeFont = (typeof THEME_FONTS)[number];\n\n/** The homepage: sections in display order. */\nexport interface ThemeHomepage {\n /**\n * Sections in display order. May contain section types this SDK does not\n * know (skip them) — narrow with {@link isKnownThemeSection}.\n */\n sections?: ThemeSection[];\n /** Unknown homepage keys are kept as stored. */\n [key: string]: unknown;\n}\n\n/** A call-to-action link. */\nexport interface ThemeLink {\n /** Visible text. */\n label?: string;\n /** Target URL or path. */\n href?: string;\n}\n\n/** `hero`: a large banner with an optional image and call to action. */\nexport interface HeroSection {\n /** Discriminator. */\n type: 'hero';\n /** Storage key of the banner image. */\n image?: string | null;\n /** Headline. */\n title?: string;\n /** Sub-headline. */\n subtitle?: string;\n /** Optional call-to-action button. */\n cta?: ThemeLink;\n}\n\n/** `featuredProducts`: a hand-picked list of products. */\nexport interface FeaturedProductsSection {\n /** Discriminator. */\n type: 'featuredProducts';\n /** Section heading. */\n title?: string;\n /** Product slugs, in display order. Slugs no longer sold are skipped. */\n productSlugs?: string[];\n}\n\n/** `categoryGrid`: a grid of category tiles. */\nexport interface CategoryGridSection {\n /** Discriminator. */\n type: 'categoryGrid';\n /** Category slugs, in display order. Unknown slugs are skipped. */\n categorySlugs?: string[];\n}\n\n/**\n * `richText`: seller-written text. Render it as text or sanitized\n * markdown — never as raw HTML.\n */\nexport interface RichTextSection {\n /** Discriminator. */\n type: 'richText';\n /** The text. */\n content?: string;\n}\n\n/** A section type this SDK knows how to describe. */\nexport type KnownThemeSection =\n HeroSection | FeaturedProductsSection | CategoryGridSection | RichTextSection;\n\n/** A section of a type this SDK version does not know; renderers skip it. */\nexport interface UnknownThemeSection {\n /** The stored type. */\n type: string;\n /** Other stored keys. */\n [key: string]: unknown;\n}\n\n/** A homepage section as stored: a known section or an unknown one. */\nexport type ThemeSection = KnownThemeSection | UnknownThemeSection;\n\nconst KNOWN_SECTION_TYPES: ReadonlySet<string> = new Set([\n 'hero',\n 'featuredProducts',\n 'categoryGrid',\n 'richText',\n]);\n\n/**\n * Whether a stored section is one of the known types. After this guard a\n * `switch (section.type)` narrows to the exact section shape.\n */\nexport function isKnownThemeSection(\n section: unknown,\n): section is KnownThemeSection {\n return (\n typeof section === 'object' &&\n section !== null &&\n typeof (section as { type?: unknown }).type === 'string' &&\n KNOWN_SECTION_TYPES.has((section as { type: string }).type)\n );\n}\n\n/** Social profile URLs; only filled ones are stored. */\nexport interface ThemeSocial {\n /** Instagram profile URL. */\n instagram?: string;\n /** Facebook page URL. */\n facebook?: string;\n /** X profile URL. */\n x?: string;\n /** TikTok profile URL. */\n tiktok?: string;\n /** YouTube channel URL. */\n youtube?: string;\n /** Unknown networks are kept as stored. */\n [key: string]: unknown;\n}\n\n/** Footer configuration. */\nexport interface ThemeFooter {\n /** Footer links, in display order. */\n links?: ThemeLink[];\n /** Social profiles. */\n social?: ThemeSocial;\n /** Unknown footer keys are kept as stored. */\n [key: string]: unknown;\n}\n","import type {\n CheckoutEmbed,\n CheckoutResult,\n ClosedCheckoutPage,\n EmbeddedCheckoutResult,\n RedirectCheckoutResult,\n ClosedCheckoutResult,\n} from './models';\n\n/**\n * What {@link mountPayment} renders: a checkout result, or just its\n * presentation part.\n */\nexport type PaymentPresentation =\n | Pick<EmbeddedCheckoutResult, 'presentation' | 'embed'>\n | Pick<RedirectCheckoutResult, 'presentation' | 'url'>\n | Pick<ClosedCheckoutResult, 'presentation' | 'page'>;\n\n/** Options of {@link mountPayment}. */\nexport interface MountPaymentOptions {\n /**\n * Called for `presentation: \"closed\"` with the page to show (`paid`,\n * `cancelled`, `processing`, …). Typically: go to the order status page.\n */\n onClosed?: (page: ClosedCheckoutPage) => void;\n}\n\n/** The provider form is in the element. */\nexport interface EmbeddedPaymentMount {\n /** Discriminator. */\n kind: 'embedded';\n /** Removes the form from the element. */\n unmount(): void;\n}\n\n/** The browser is navigating to the provider's payment page. */\nexport interface RedirectPaymentMount {\n /** Discriminator. */\n kind: 'redirect';\n /** Where the browser was sent. */\n url: string;\n}\n\n/** Payment cannot be opened; `onClosed` was called. */\nexport interface ClosedPaymentMount {\n /** Discriminator. */\n kind: 'closed';\n /** The page to show. */\n page: ClosedCheckoutPage;\n}\n\n/**\n * The embed has a `kind` this SDK version cannot render. Nothing was put\n * in the element; show a fallback (e.g. \"payment unavailable\").\n */\nexport interface UnsupportedPaymentMount {\n /** Discriminator. */\n kind: 'unsupported';\n /** The embed kind that was not understood. */\n embedKind: string;\n}\n\n/** The result of {@link mountPayment}, discriminated by `kind`. */\nexport type PaymentMount =\n | EmbeddedPaymentMount\n | RedirectPaymentMount\n | ClosedPaymentMount\n | UnsupportedPaymentMount;\n\ninterface MountedForm {\n content: string;\n nodes: Node[];\n unmount: () => void;\n}\n\n/** What each element currently holds, so a repeat mount is a no-op. */\nconst mounted = new WeakMap<Element, MountedForm>();\n\n/**\n * Presents payment from a checkout result. Card data never touches your\n * page's code: the form is the provider's own, or a redirect.\n *\n * - `embedded` (`iyzico-checkout-form`): puts the provider's HTML into\n * `element` and re-creates every `<script>` in it so it executes\n * (`innerHTML` alone never runs scripts). Idempotent per element:\n * mounting the same content again does nothing, other content replaces\n * the previous form — scripts are never injected twice.\n * - `redirect`: top-level navigation to the provider page\n * (`location.assign`). Only `http:` / `https:` URLs are followed.\n * - `closed`: calls `onClosed(page)`.\n *\n * Browser only (needs a DOM).\n *\n * @throws TypeError for a redirect URL that is not `http(s)`.\n */\nexport function mountPayment(\n element: HTMLElement,\n presentation: PaymentPresentation | CheckoutResult,\n options: MountPaymentOptions = {},\n): PaymentMount {\n switch (presentation.presentation) {\n case 'embedded':\n return mountEmbedded(element, presentation.embed);\n case 'redirect': {\n const url = presentation.url;\n let protocol: string;\n try {\n protocol = new URL(url).protocol;\n } catch {\n protocol = '';\n }\n if (protocol !== 'https:' && protocol !== 'http:') {\n throw new TypeError('mountPayment: redirect URL must be http(s)');\n }\n const view = element.ownerDocument.defaultView;\n if (!view) throw new TypeError('mountPayment: element has no window');\n view.location.assign(url);\n return { kind: 'redirect', url };\n }\n case 'closed':\n options.onClosed?.(presentation.page);\n return { kind: 'closed', page: presentation.page };\n }\n}\n\nfunction mountEmbedded(\n element: HTMLElement,\n embed: CheckoutEmbed,\n): EmbeddedPaymentMount | UnsupportedPaymentMount {\n if (\n embed.kind !== 'iyzico-checkout-form' ||\n typeof embed.content !== 'string'\n ) {\n return { kind: 'unsupported', embedKind: String(embed.kind) };\n }\n const content = embed.content;\n const current = mounted.get(element);\n if (\n current &&\n current.content === content &&\n current.nodes.every((n) => n.parentNode === element)\n ) {\n return { kind: 'embedded', unmount: current.unmount };\n }\n\n element.replaceChildren();\n // The provider's own checkout form (from the payments service). It must\n // run its scripts, so it cannot be sanitised; it is the only HTML this\n // SDK ever injects.\n element.innerHTML = content;\n const doc = element.ownerDocument;\n for (const inert of Array.from(element.querySelectorAll('script'))) {\n const live = doc.createElement('script');\n for (const attr of Array.from(inert.attributes)) {\n live.setAttribute(attr.name, attr.value);\n }\n // Dynamically inserted external scripts are async by default; keep\n // document order like the provider's markup expects.\n if (live.hasAttribute('src')) live.async = false;\n live.text = inert.text;\n inert.replaceWith(live);\n }\n const entry: MountedForm = {\n content,\n nodes: Array.from(element.childNodes),\n unmount: () => {\n // A stale handle never removes a newer form.\n if (mounted.get(element) !== entry) return;\n for (const node of entry.nodes) node.parentNode?.removeChild(node);\n mounted.delete(element);\n },\n };\n mounted.set(element, entry);\n return { kind: 'embedded', unmount: entry.unmount };\n}\n","/**\n * Formats an integer amount of minor units (kuruş, cents, …) as a\n * localised currency string with `Intl.NumberFormat`, using the currency's\n * own number of minor digits (2 for `TRY`, 0 for `JPY`).\n *\n * @example formatMoney(14990, 'TRY', 'tr-TR') // \"₺149,90\"\n * @throws TypeError when `minor` is not a finite number; RangeError for an\n * unknown currency code (from `Intl`).\n */\nexport function formatMoney(\n minor: number,\n currency: string,\n locale?: string | string[],\n): string {\n if (typeof minor !== 'number' || !Number.isFinite(minor)) {\n throw new TypeError('formatMoney: minor must be a finite number');\n }\n const format = new Intl.NumberFormat(locale, { style: 'currency', currency });\n const digits = format.resolvedOptions().maximumFractionDigits ?? 2;\n return format.format(minor / 10 ** digits);\n}\n","import type { AdPixels, CookieInfo } from './models';\n\n// Pure helpers for choosing what a store host may load and list. They touch\n// no browser API, so they run in server code (for example a Next.js server\n// component) as well as in the browser.\n\n/** Whether `host` is a default store domain (`suffix` or below it). */\nexport function onDefaultDomain(\n host: string,\n suffix: string | undefined,\n): boolean {\n if (!suffix) return false;\n const h = host.toLowerCase();\n const s = suffix.toLowerCase();\n return h === s || h.endsWith(`.${s}`);\n}\n\n/**\n * The pixels a host may load: Meta and TikTok write their cookies to the\n * registrable domain, which every default store domain shares, so they run\n * only on custom domains.\n */\nexport function pixelsForHost(\n p: AdPixels | undefined,\n defaultDomain: boolean,\n): AdPixels | undefined {\n if (!p || !defaultDomain) return p;\n return p.google ? { google: p.google } : {};\n}\n\n/**\n * The cookies a host lists: on a default domain without the\n * `customDomainOnly` ones, and none at all when no optional cookie is left.\n */\nexport function cookiesForHost(\n cookies: CookieInfo[],\n defaultDomain: boolean,\n): CookieInfo[] {\n if (!defaultDomain) return cookies;\n const kept = cookies.filter((c) => !c.customDomainOnly);\n return kept.some((c) => c.category !== 'necessary') ? kept : [];\n}\n","/**\n * The part of the Web Storage API the cart-id helpers use; `localStorage`,\n * `sessionStorage` or any object with these methods (a cookie adapter, a\n * test double).\n */\nexport interface CartIdStorage {\n /** Reads a value, or null. */\n getItem(key: string): string | null;\n /** Writes a value. */\n setItem(key: string, value: string): void;\n /** Deletes a value. */\n removeItem(key: string): void;\n}\n\n/** The storage key of a store's cart id. Namespaced per store. */\nexport function cartIdKey(storeId: string): string {\n return `storefront:cart:${storeId}`;\n}\n\n/**\n * The saved cart id of a store, or null. Never throws: a missing storage\n * (SSR), a storage that throws (Safari private mode, blocked cookies) or\n * an empty value all read as null.\n */\nexport function loadCartId(\n storage: CartIdStorage | null | undefined,\n storeId: string,\n): string | null {\n try {\n const v = storage?.getItem(cartIdKey(storeId));\n return typeof v === 'string' && v.trim() !== '' ? v.trim() : null;\n } catch {\n return null;\n }\n}\n\n/** Saves a store's cart id. Returns false when the storage refused. Never throws. */\nexport function saveCartId(\n storage: CartIdStorage | null | undefined,\n storeId: string,\n cartId: string,\n): boolean {\n if (!storage) return false;\n try {\n storage.setItem(cartIdKey(storeId), cartId);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Forgets a store's cart id (after `cart_not_found`, or `cart_read_only`\n * with `status: \"expired\"`). Returns false when the storage refused. Never throws.\n */\nexport function clearCartId(\n storage: CartIdStorage | null | undefined,\n storeId: string,\n): boolean {\n if (!storage) return false;\n try {\n storage.removeItem(cartIdKey(storeId));\n return true;\n } catch {\n return false;\n }\n}\n\n/** The part of `document` the cookie storage uses. */\nexport interface CookieJar {\n cookie: string;\n}\n\n/** The cookie carrying the cart ids. */\nconst CART_COOKIE = '__Host-konfiqo_cart';\n/** Largest encoded cookie value written (browsers drop a cookie over ~4 KB). */\nconst MAX_COOKIE_VALUE = 3500;\n/** One year, seconds. */\nconst COOKIE_MAX_AGE = 31_536_000;\n\nfunction readMap(doc: CookieJar): Record<string, string> {\n try {\n for (const part of doc.cookie.split(';')) {\n const p = part.trim();\n if (!p.startsWith(`${CART_COOKIE}=`)) continue;\n const parsed: unknown = JSON.parse(\n decodeURIComponent(p.slice(CART_COOKIE.length + 1)),\n );\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n return {};\n }\n const out: Record<string, string> = {};\n for (const [k, v] of Object.entries(parsed)) {\n if (typeof v === 'string') out[k] = v;\n }\n return out;\n }\n } catch {\n // Malformed cookie: ignored (and replaced by the next write).\n }\n return {};\n}\n\nfunction writeMap(doc: CookieJar, map: Record<string, string>): boolean {\n const attrs = '; Path=/; SameSite=Lax; Secure';\n const keys = Object.keys(map);\n if (keys.length === 0) {\n doc.cookie = `${CART_COOKIE}=; Max-Age=0${attrs}`;\n return true;\n }\n const value = encodeURIComponent(JSON.stringify(map));\n if (value.length > MAX_COOKIE_VALUE) return false;\n doc.cookie = `${CART_COOKIE}=${value}; Max-Age=${COOKIE_MAX_AGE}${attrs}`;\n return true;\n}\n\n/**\n * Cart ids in the first-party `__Host-konfiqo_cart` cookie (path\n * `/`, no `Domain`, `SameSite=Lax`, `Secure`). The `__Host-` prefix makes\n * browsers refuse a cookie of this name scoped to a parent domain, so a\n * sibling store subdomain cannot plant a cart; the old unprefixed\n * `konfiqo_cart` is never read. The value is a JSON map keyed by\n * {@link cartIdKey}, so a store's own frontend and the hosted checkout on the same domain share\n * the cart. `Secure` cookies are dropped by browsers on plain `http`\n * (other than `localhost`), so over http nothing is stored here; pair it\n * with a `localStorage` fallback. Without a document (SSR) it reads nothing and writes fail.\n * Never throws; a malformed or oversized cookie is ignored.\n *\n * @param doc Defaults to the global `document`; `null` disables it.\n */\nexport function cookieCartStorage(doc?: CookieJar | null): CartIdStorage {\n const jar = (): CookieJar | null =>\n doc === undefined\n ? ((globalThis as { document?: CookieJar }).document ?? null)\n : doc;\n return {\n getItem(key) {\n const d = jar();\n if (!d) return null;\n return readMap(d)[key] ?? null;\n },\n setItem(key, value) {\n const d = jar();\n if (!d) throw new Error('no document');\n const map = readMap(d);\n map[key] = value;\n if (!writeMap(d, map)) throw new Error('cart cookie too large');\n },\n removeItem(key) {\n const d = jar();\n if (!d) return;\n const map = readMap(d);\n if (!(key in map)) return;\n delete map[key];\n writeMap(d, map);\n },\n };\n}\n","/**\n * Cloudflare's official Turnstile script, explicit-render mode. The only\n * URL {@link loadTurnstile} ever injects.\n */\nexport const TURNSTILE_SCRIPT_URL =\n 'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit';\n\n/** The subset of Cloudflare's `window.turnstile` API the SDK uses. */\nexport interface TurnstileApi {\n /** Renders a widget into `container`; returns its widget id. */\n render(\n container: HTMLElement | string,\n params: {\n sitekey: string;\n callback?: (token: string) => void;\n 'expired-callback'?: () => void;\n 'error-callback'?: (code?: string) => void;\n [key: string]: unknown;\n },\n ): string | null | undefined;\n /** Resets a widget so it produces a new token. */\n reset(widgetId?: string): void;\n /** Removes a widget. */\n remove(widgetId?: string): void;\n}\n\ntype TurnstileWindow = Window & { turnstile?: TurnstileApi };\n\nconst loading = new WeakMap<Document, Promise<TurnstileApi>>();\n\n/**\n * Loads Cloudflare Turnstile into `document` (once: the script is injected\n * at most once per document, concurrent calls share one load) and resolves\n * with `window.turnstile`. Rejects when the script fails to load; the\n * failed `<script>` is removed, so calling again injects a fresh one.\n */\nexport function loadTurnstile(document: Document): Promise<TurnstileApi> {\n const view = document.defaultView as TurnstileWindow | null;\n if (!view)\n return Promise.reject(\n new TypeError('loadTurnstile: document has no window'),\n );\n if (view.turnstile) return Promise.resolve(view.turnstile);\n const pending = loading.get(document);\n if (pending) return pending;\n\n const promise = new Promise<TurnstileApi>((resolve, reject) => {\n let script = Array.from(document.scripts).find(\n (s) => s.src === TURNSTILE_SCRIPT_URL,\n );\n if (!script) {\n script = document.createElement('script');\n script.src = TURNSTILE_SCRIPT_URL;\n script.async = true;\n (document.head ?? document.documentElement).appendChild(script);\n }\n script.addEventListener('load', () => {\n if (view.turnstile) resolve(view.turnstile);\n else\n reject(\n new Error('loadTurnstile: script loaded without window.turnstile'),\n );\n });\n const tag = script;\n tag.addEventListener('error', () => {\n // A failed tag never loads again: remove it so a retry injects a\n // fresh one instead of waiting on the dead tag forever.\n tag.remove();\n reject(new Error('loadTurnstile: script failed to load'));\n });\n });\n loading.set(document, promise);\n // A failed load can be retried by calling again.\n promise.catch(() => {\n if (loading.get(document) === promise) loading.delete(document);\n });\n return promise;\n}\n\n/** Callbacks of {@link renderTurnstile}. */\nexport interface RenderTurnstileOptions {\n /** A token is ready: keep it for the next `carts.checkout` call. */\n onToken: (token: string) => void;\n /** The token expired unused (about 5 minutes): drop it; the widget refreshes. */\n onExpired?: () => void;\n /** The widget failed (network, unsupported browser, …). */\n onError?: (code?: string) => void;\n}\n\n/** A rendered Turnstile widget. */\nexport interface TurnstileWidget {\n /** The widget id. */\n readonly widgetId: string;\n /**\n * Gets a new token. Call it after every `carts.checkout` that used the\n * current token: tokens are **single-use**.\n */\n reset(): void;\n /** Removes the widget. */\n remove(): void;\n}\n\n/**\n * Renders a Turnstile widget with the store's `siteKey`\n * (`store.checkoutChallenge.siteKey`) into `element`, loading the script\n * first if needed. Pass each token from `onToken` to\n * `carts.checkout(id, { turnstileToken })`, then `reset()`.\n */\nexport async function renderTurnstile(\n element: HTMLElement,\n siteKey: string,\n options: RenderTurnstileOptions,\n): Promise<TurnstileWidget> {\n if (!siteKey) throw new TypeError('renderTurnstile: siteKey is required');\n const turnstile = await loadTurnstile(element.ownerDocument);\n const params: Parameters<TurnstileApi['render']>[1] = {\n sitekey: siteKey,\n callback: (token: string) => options.onToken(token),\n 'expired-callback': () => options.onExpired?.(),\n 'error-callback': (code?: string) => options.onError?.(code),\n };\n const widgetId = turnstile.render(element, params);\n if (!widgetId) throw new Error('renderTurnstile: the widget did not render');\n return {\n widgetId,\n reset: () => turnstile.reset(widgetId),\n remove: () => turnstile.remove(widgetId),\n };\n}\n","/** Version of the Storefront SDK package. */\nexport const SDK_VERSION = '0.6.0';\n\nexport {\n createStorefrontClient,\n DEFAULT_TIMEOUT_MS,\n PUBLISHABLE_KEY_HEADER,\n STOREFRONT_KEY_HEADER,\n BUYER_IP_HEADER,\n TURNSTILE_TOKEN_HEADER,\n} from './client';\nexport type {\n CheckoutOptions,\n RequestCodeOptions,\n RequestOptions,\n StorefrontClient,\n StorefrontClientOptions,\n} from './client';\nexport { StorefrontError, isStorefrontError } from './errors';\nexport type {\n AnyStorefrontError,\n BuyerDetailField,\n CheckoutMissing,\n StorefrontApiErrorCode,\n StorefrontClientErrorCode,\n StorefrontErrorCode,\n StorefrontErrorDetails,\n StorefrontErrorDetailsMap,\n ValidationIssue,\n} from './errors';\nexport type * from './models';\nexport { THEME_FONTS, isKnownThemeSection } from './theme';\nexport type {\n CategoryGridSection,\n FeaturedProductsSection,\n HeroSection,\n KnownThemeSection,\n RichTextSection,\n ThemeColors,\n ThemeFont,\n ThemeFooter,\n ThemeHomepage,\n ThemeLink,\n ThemeSection,\n ThemeSocial,\n ThemeV1,\n UnknownThemeSection,\n} from './theme';\nexport { mountPayment } from './payment';\nexport type {\n ClosedPaymentMount,\n EmbeddedPaymentMount,\n MountPaymentOptions,\n PaymentMount,\n PaymentPresentation,\n RedirectPaymentMount,\n UnsupportedPaymentMount,\n} from './payment';\nexport { formatMoney } from './money';\nexport { cookiesForHost, onDefaultDomain, pixelsForHost } from './host-pixels';\nexport {\n cartIdKey,\n clearCartId,\n cookieCartStorage,\n loadCartId,\n saveCartId,\n} from './cart-storage';\nexport type { CartIdStorage, CookieJar } from './cart-storage';\nexport {\n TURNSTILE_SCRIPT_URL,\n loadTurnstile,\n renderTurnstile,\n} from './turnstile';\nexport type {\n RenderTurnstileOptions,\n TurnstileApi,\n TurnstileWidget,\n} from './turnstile';\n"],"mappings":";AAkJA,IAAM,YAAiC,oBAAI,IAA4B;AAAA,EACrE;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,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,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAOD,IAAM,cAAc,uBAAO,IAAI,+BAA+B;AAUvD,IAAM,kBAAN,cAEG,MAAM;AAAA;AAAA,EAEL;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAST,YACE,MACA,QACA,SACA,SACA,SACA;AACA,UAAM,SAAS,OAAO;AACtB,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,SAAS;AACd,SAAK,UAAU;AACf,WAAO,eAAe,MAAM,aAAa,EAA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AA,IAC9C,kBAAkB,CAAC,SAAkB,QAAQ,UAAU,IAAI;AAAA,EAC7D;AACA,QAAM,WAAW,UAAU,OAAO,SAAS,MAAM;AACjD,MAAI,CAAC,SAAU,OAAM,IAAI,MAAM,4CAA4C;AAC3E,SAAO;AAAA,IACL;AAAA,IACA,OAAO,MAAM,UAAU,MAAM,QAAQ;AAAA,IACrC,QAAQ,MAAM,UAAU,OAAO,QAAQ;AAAA,EACzC;AACF;;;AC/HO,IAAM,cAAc;","names":["options","n","document"]}
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/client.ts","../src/theme.ts","../src/payment.ts","../src/money.ts","../src/host-pixels.ts","../src/cart-storage.ts","../src/turnstile.ts","../src/index.ts"],"sourcesContent":["import type { CartLine, ShippingOption } from './models';\n\n/** `checkout_incomplete`: what the cart still lacks. */\nexport type CheckoutMissing =\n | 'lines'\n | 'customer'\n | 'identityNumber'\n | 'shippingAddress'\n | 'shippingOption';\n\n/**\n * `invalid_buyer_details`: the buyer detail the payment provider refused.\n * Address fields come as `shippingAddress.<field>` / `billingAddress.<field>`.\n */\nexport type BuyerDetailField =\n | 'name'\n | 'surname'\n | 'email'\n | 'phone'\n | 'identityNumber'\n | `shippingAddress.${string}`\n | `billingAddress.${string}`;\n\n/** One validation problem of an `invalid_request`. */\nexport interface ValidationIssue {\n /** Dotted path of the field (`phone`, `shipping.city`, …). */\n path: string;\n /** What is wrong with it (never echoes the submitted value). */\n message: string;\n}\n\n/**\n * The extras each error code carries (`StorefrontError.details`). Codes\n * not listed here carry no details (`undefined`).\n */\nexport interface StorefrontErrorDetailsMap {\n /** Prices or shipping changed: show the new totals, then check out again. */\n cart_changed: {\n lines: CartLine[];\n subtotalMinor: number;\n shippingMinor: number;\n totalMinor: number;\n shippingOptions: ShippingOption[];\n };\n /**\n * A personalization text is refused (400, no details) or, at checkout\n * (409), a line's stored text no longer satisfies the product's rule:\n * `lineIds` are those lines. Remove the line and add it again with a\n * valid text.\n */\n invalid_personalization: { lineIds?: string[] };\n /** These variants cannot be bought (no longer sold, or not enough units). */\n out_of_stock: { variantIds: string[] };\n /** Collect what is missing, then check out again. */\n checkout_incomplete: { missing: CheckoutMissing[] };\n /** Let the buyer fix `field`, then check out again. */\n invalid_buyer_details: { field: BuyerDetailField };\n /** Only `available` units can be added. */\n insufficient_stock: { available: number };\n /** The request body or query failed validation. */\n invalid_request: { issues: ValidationIssue[] };\n /** The cart can no longer change: start a new cart. */\n cart_read_only: { status: 'ordered' | 'expired' };\n /** Throttled. `retryAfter` = seconds to wait, when the response said so. */\n rate_limited: { retryAfter?: number };\n /** No response within `timeoutMs`. */\n timeout: { timeoutMs: number };\n /** The server answered an error code this SDK version does not know. */\n unknown_error: { error: string | null };\n}\n\n/** Error codes of the Storefront API (the `error` field of an error response). */\nexport type StorefrontApiErrorCode =\n | 'store_not_found'\n | 'origin_not_allowed'\n | 'invalid_request'\n | 'invalid_buyer_ip'\n | 'catalog_unavailable'\n | 'product_not_found'\n | 'content_not_found'\n | 'cart_not_found'\n | 'variant_not_found'\n | 'line_not_found'\n | 'insufficient_stock'\n | 'quantity_out_of_range'\n | 'too_many_lines'\n | 'invalid_shipping_option'\n | 'cart_read_only'\n | 'checkout_in_progress'\n | 'checkout_incomplete'\n | 'cart_changed'\n | 'invalid_personalization'\n | 'out_of_stock'\n | 'amount_out_of_range'\n | 'nothing_to_pay'\n | 'invalid_buyer_details'\n | 'payment_unavailable'\n | 'checkout_unavailable'\n | 'order_not_found'\n | 'order_unavailable'\n | 'media_not_found'\n | 'media_unavailable'\n | 'challenge_required'\n | 'challenge_failed'\n | 'challenge_unavailable'\n | 'too_many_open_orders'\n | 'not_signed_in'\n | 'invalid_code'\n | 'profile_required'\n | 'too_many_code_requests'\n | 'invalid_recovery_token'\n | 'cart_not_recoverable'\n | 'unavailable';\n\n/**\n * Codes the SDK assigns itself:\n * - `rate_limited` — HTTP 429 without a known `error` code (the throttler);\n * - `unauthorized` — HTTP 401 without a code (a wrong `trustedStorefrontKey`);\n * - `http_error` — any other non-2xx response without an `error` code;\n * - `unknown_error` — an `error` code this SDK version does not know (in `details.error`);\n * - `invalid_response` — a 2xx response that is not JSON;\n * - `network_error` — no readable response: the API was unreachable (DNS,\n * TLS, offline), or, in a browser, the origin is allowed by no store;\n * - `timeout` — no response within `timeoutMs`;\n * - `aborted` — the caller's `signal` aborted the request.\n */\nexport type StorefrontClientErrorCode =\n | 'rate_limited'\n | 'unauthorized'\n | 'http_error'\n | 'unknown_error'\n | 'invalid_response'\n | 'network_error'\n | 'timeout'\n | 'aborted';\n\n/** Every code a {@link StorefrontError} can have. */\nexport type StorefrontErrorCode =\n StorefrontApiErrorCode | StorefrontClientErrorCode;\n\n/** The `details` type of an error code (`undefined` for codes without extras). */\nexport type StorefrontErrorDetails<C extends StorefrontErrorCode> =\n C extends keyof StorefrontErrorDetailsMap\n ? StorefrontErrorDetailsMap[C]\n : undefined;\n\nconst API_CODES: ReadonlySet<string> = new Set<StorefrontApiErrorCode>([\n 'store_not_found',\n 'origin_not_allowed',\n 'invalid_request',\n 'invalid_buyer_ip',\n 'catalog_unavailable',\n 'product_not_found',\n 'content_not_found',\n 'cart_not_found',\n 'variant_not_found',\n 'line_not_found',\n 'insufficient_stock',\n 'quantity_out_of_range',\n 'too_many_lines',\n 'invalid_shipping_option',\n 'cart_read_only',\n 'checkout_in_progress',\n 'checkout_incomplete',\n 'cart_changed',\n 'invalid_personalization',\n 'out_of_stock',\n 'amount_out_of_range',\n 'nothing_to_pay',\n 'invalid_buyer_details',\n 'payment_unavailable',\n 'checkout_unavailable',\n 'order_not_found',\n 'order_unavailable',\n 'media_not_found',\n 'media_unavailable',\n 'challenge_required',\n 'challenge_failed',\n 'challenge_unavailable',\n 'too_many_open_orders',\n 'not_signed_in',\n 'invalid_code',\n 'profile_required',\n 'too_many_code_requests',\n 'invalid_recovery_token',\n 'cart_not_recoverable',\n 'unavailable',\n]);\n\n/**\n * Marks every {@link StorefrontError}. A global (`Symbol.for`) symbol, so\n * an error thrown by one installed copy of the SDK is recognised by another\n * (e.g. the React package resolving its own copy), where `instanceof` fails.\n */\nconst ERROR_BRAND = Symbol.for('@konfiqo/storefront-sdk/error');\n\n/**\n * Every failure of a client call: an API error response, a throttle, a\n * timeout or a transport failure. Switch on `code`, never on `message`.\n *\n * To get `details` typed per code, narrow with {@link isStorefrontError}\n * (which yields the {@link AnyStorefrontError} union) and `switch (e.code)`,\n * or test one code with `e.is('cart_changed')`.\n */\nexport class StorefrontError<\n C extends StorefrontErrorCode = StorefrontErrorCode,\n> extends Error {\n /** The API `error` code, or one of the SDK's own codes. */\n readonly code: C;\n /** HTTP status; `0` when no response arrived (`network_error`, `timeout`). */\n readonly status: number;\n /** The code's extras (see {@link StorefrontErrorDetailsMap}). */\n readonly details: StorefrontErrorDetails<C>;\n\n /**\n * @param code - the error code\n * @param status - the HTTP status (`0` without a response)\n * @param message - a human-readable description (not for display logic)\n * @param details - the code's extras\n * @param options - `cause`: the underlying error, if any\n */\n constructor(\n code: C,\n status: number,\n message: string,\n details: StorefrontErrorDetails<C>,\n options?: { cause?: unknown },\n ) {\n super(message, options);\n this.name = 'StorefrontError';\n this.code = code;\n this.status = status;\n this.details = details;\n Object.defineProperty(this, ERROR_BRAND, { value: true });\n }\n\n /** Whether this error has `code`; narrows `details` to that code's extras. */\n is<K extends StorefrontErrorCode>(code: K): this is StorefrontError<K> {\n return (this.code as StorefrontErrorCode) === code;\n }\n}\n\n/**\n * The union of {@link StorefrontError} by code: after narrowing `code`\n * (e.g. in a `switch`), `details` has that code's type.\n */\nexport type AnyStorefrontError = {\n [C in StorefrontErrorCode]: StorefrontError<C>;\n}[StorefrontErrorCode];\n\n/**\n * Whether `e` is a {@link StorefrontError}, as the code-discriminated union.\n * Also true for an error from another copy of this SDK (checked by a global\n * brand, not only `instanceof`).\n */\nexport function isStorefrontError(e: unknown): e is AnyStorefrontError {\n return (\n e instanceof StorefrontError ||\n (typeof e === 'object' &&\n e !== null &&\n (e as Record<symbol, unknown>)[ERROR_BRAND] === true)\n );\n}\n\nconst isObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === 'object' && v !== null && !Array.isArray(v);\n\n/** Seconds from a `Retry-After` value (delta-seconds or an HTTP date). */\nfunction parseRetryAfter(value: string | null): number | undefined {\n if (value === null) return undefined;\n const trimmed = value.trim();\n if (/^\\d+$/.test(trimmed)) return Number(trimmed);\n const at = Date.parse(trimmed);\n if (Number.isNaN(at)) return undefined;\n return Math.max(0, Math.ceil((at - Date.now()) / 1000));\n}\n\n/**\n * Builds the error for a non-2xx response from its status, body (parsed\n * JSON, or undefined) and headers. Internal.\n */\nexport function errorFromResponse(\n status: number,\n body: unknown,\n headers: Headers,\n): AnyStorefrontError {\n const b = isObject(body) ? body : {};\n const message =\n typeof b.message === 'string' && b.message !== ''\n ? b.message\n : `Storefront API request failed (HTTP ${status})`;\n\n const error = typeof b.error === 'string' ? b.error : null;\n // A 429 with a known code (`too_many_open_orders`) is that code; the\n // throttler's 429 carries none.\n if (status === 429 && (error === null || !API_CODES.has(error))) {\n // The throttler names its header per limit (`Retry-After`,\n // `Retry-After-ip`); when both come, the longer wait is the real one.\n const waits = [\n parseRetryAfter(headers.get('retry-after')),\n parseRetryAfter(headers.get('retry-after-ip')),\n ].filter((w): w is number => w !== undefined);\n const retryAfter = waits.length > 0 ? Math.max(...waits) : undefined;\n return new StorefrontError(\n 'rate_limited',\n status,\n message,\n retryAfter === undefined ? {} : { retryAfter },\n );\n }\n\n if (error === null) {\n if (status === 401)\n return new StorefrontError('unauthorized', status, message, undefined);\n return new StorefrontError('http_error', status, message, undefined);\n }\n if (!API_CODES.has(error)) {\n return new StorefrontError('unknown_error', status, message, { error });\n }\n const code = error as StorefrontApiErrorCode;\n return apiError(code, status, message, b);\n}\n\nconst arr = <T>(v: unknown): T[] => (Array.isArray(v) ? (v as T[]) : []);\nconst n = (v: unknown): number => (typeof v === 'number' ? v : 0);\n\nfunction apiError(\n code: StorefrontApiErrorCode,\n status: number,\n message: string,\n b: Record<string, unknown>,\n): AnyStorefrontError {\n switch (code) {\n case 'cart_changed':\n return new StorefrontError(code, status, message, {\n lines: arr<CartLine>(b.lines),\n subtotalMinor: n(b.subtotalMinor),\n shippingMinor: n(b.shippingMinor),\n totalMinor: n(b.totalMinor),\n shippingOptions: arr<ShippingOption>(b.shippingOptions),\n });\n case 'invalid_personalization':\n return new StorefrontError(\n code,\n status,\n message,\n Array.isArray(b.lineIds) ? { lineIds: arr<string>(b.lineIds) } : {},\n );\n case 'out_of_stock':\n return new StorefrontError(code, status, message, {\n variantIds: arr<string>(b.variantIds),\n });\n case 'checkout_incomplete':\n return new StorefrontError(code, status, message, {\n missing: arr<CheckoutMissing>(b.missing),\n });\n case 'invalid_buyer_details':\n return new StorefrontError(code, status, message, {\n field: String(b.field ?? '') as BuyerDetailField,\n });\n case 'insufficient_stock':\n return new StorefrontError(code, status, message, {\n available: n(b.available),\n });\n case 'invalid_request':\n return new StorefrontError(code, status, message, {\n issues: arr<ValidationIssue>(b.issues),\n });\n case 'cart_read_only':\n return new StorefrontError(code, status, message, {\n status: b.status === 'ordered' ? 'ordered' : 'expired',\n });\n default:\n return new StorefrontError(\n code,\n status,\n message,\n undefined,\n ) as AnyStorefrontError;\n }\n}\n","import { StorefrontError, errorFromResponse } from './errors';\nimport type {\n AddLineInput,\n AddressInput,\n Account,\n AccountProfileInput,\n AccountSession,\n Cart,\n CategoryList,\n CheckoutResult,\n CustomerInput,\n Order,\n Product,\n ProductListQuery,\n ProductPage,\n SavedAddress,\n SavedAddressInput,\n ShippingOptionList,\n Store,\n StoreContent,\n UpdateLineInput,\n} from './models';\n\n/** Default request timeout, milliseconds. */\nexport const DEFAULT_TIMEOUT_MS = 15_000;\n\n/** Header carrying the publishable key on every request. */\nexport const PUBLISHABLE_KEY_HEADER = 'x-konfiqo-publishable-key';\n/** Header carrying the trusted storefront key (server-side only). */\nexport const STOREFRONT_KEY_HEADER = 'x-konfiqo-storefront-key';\n/** Header carrying the store's server key (server-side only). */\nexport const SERVER_KEY_HEADER = 'x-konfiqo-server-key';\n/** Header carrying the checkout challenge token (checkout only). */\nexport const TURNSTILE_TOKEN_HEADER = 'x-konfiqo-turnstile-token';\n/** Header carrying the buyer's IP (only with a server key or the trusted storefront key). */\nexport const BUYER_IP_HEADER = 'x-konfiqo-buyer-ip';\n\n/** Per-call options, accepted as the last argument of every method. */\nexport interface RequestOptions {\n /**\n * Aborts the request: it rejects with code `aborted`. Combined with the\n * client timeout (whichever comes first wins).\n */\n signal?: AbortSignal;\n /**\n * **Server-side only.** A `Cookie` header to forward, so a server-rendered\n * storefront can call the account routes as the buyer: pass the incoming\n * request's `cookie` header (or just `konfiqo_session=<value>`). Browsers\n * ignore a `Cookie` header set from script; there the session cookie rides\n * along automatically (`credentials: 'include'`).\n */\n cookie?: string;\n}\n\n/** Options of `account.requestCode`. */\nexport interface RequestCodeOptions extends RequestOptions {\n /**\n * The challenge token (Cloudflare Turnstile), required when the store\n * asks for one (`store.checkoutChallenge`). Single-use. Sent as\n * `x-konfiqo-turnstile-token`.\n */\n turnstileToken?: string;\n}\n\n/** Options of `carts.checkout`. */\nexport interface CheckoutOptions extends RequestOptions {\n /**\n * The checkout challenge token (Cloudflare Turnstile), required when\n * `store.checkoutChallenge` is set. Single-use: get a new one (reset the\n * widget) for every checkout call. Sent as `x-konfiqo-turnstile-token`.\n */\n turnstileToken?: string;\n}\n\n/** Options of {@link createStorefrontClient}. */\nexport interface StorefrontClientOptions {\n /**\n * The Storefront API base: `https://<store domain>/api` (or the relative\n * `/api` in a same-origin browser app). Requests go to `${baseUrl}/v1/...`,\n * so do not include `/v1`.\n */\n baseUrl: string;\n /** The store's publishable key (`pk_live_…` / `pk_test_…`). Public. */\n publishableKey: string;\n /** A `fetch` implementation; defaults to the global `fetch`. */\n fetch?: typeof fetch;\n /** Per-request timeout in milliseconds (default {@link DEFAULT_TIMEOUT_MS}). */\n timeoutMs?: number;\n /**\n * **Server-side only.** The shared storefront key that lets a server-side\n * renderer report the real buyer IP (`buyerIp`), so throttling and the\n * payment provider see the buyer instead of the server. Sent as\n * `x-konfiqo-storefront-key`. Constructing a client with it where\n * `window` exists throws: never ship this key to a browser.\n */\n trustedStorefrontKey?: string;\n /**\n * **Server-side only.** The store's own server key, minted by the store\n * operator. It lets the seller's server report the real buyer IP\n * (`buyerIp`). Sent as `x-konfiqo-server-key` next to the publishable\n * key. Needs `buyerIp`, cannot be combined with `trustedStorefrontKey`,\n * and constructing a client with it in a browser throws.\n */\n serverKey?: string;\n /**\n * The buyer's IP address, sent as `x-konfiqo-buyer-ip`. Required with\n * `serverKey` or `trustedStorefrontKey`, ignored without one. Create one\n * client per incoming request on the server.\n */\n buyerIp?: string;\n}\n\n/**\n * A typed client of the Storefront API (`/v1`).\n *\n * Every method returns the response body, or rejects with a\n * {@link StorefrontError}. Nothing is retried: whether to retry is the\n * caller's decision, because writes are not safely repeatable — in\n * particular `carts.checkout` on a cart whose order failed places a\n * **new** order, so a blind retry could open a second payment.\n */\nexport interface StorefrontClient {\n /**\n * `GET /v1/content/:key`: a piece of store content as a renderable\n * Markdoc tree. Rejects `content_not_found` (404) for an unknown key.\n */\n getContent(key: string, options?: RequestOptions): Promise<StoreContent>;\n /** Store information. */\n readonly store: {\n /** `GET /v1/store`: name, language, currency, logo, theme, contact, legal texts, shipping rules. */\n get(options?: RequestOptions): Promise<Store>;\n };\n /** Categories. */\n readonly categories: {\n /** `GET /v1/categories`: the active category tree. */\n list(options?: RequestOptions): Promise<CategoryList>;\n };\n /** Products. */\n readonly products: {\n /** `GET /v1/products`: a page of products, optionally filtered. */\n list(\n query?: ProductListQuery,\n options?: RequestOptions,\n ): Promise<ProductPage>;\n /** `GET /v1/products/:slug`. Rejects with `product_not_found`. */\n get(slug: string, options?: RequestOptions): Promise<Product>;\n };\n /** Carts. Every cart write answers the updated cart. */\n readonly carts: {\n /** `POST /v1/carts`: a new, empty cart. */\n create(options?: RequestOptions): Promise<Cart>;\n /**\n * `POST /v1/carts/recover`: turns the `t` token of an abandoned-cart\n * e-mail link into a **new** cart with the same lines (no buyer data).\n * Rejects `invalid_recovery_token` (400) or `cart_not_recoverable` (410:\n * the cart was ordered, expired or deleted).\n */\n recover(\n token: string,\n options?: RequestOptions,\n ): Promise<{ cartId: string }>;\n /** `GET /v1/carts/:id`. Also reopens a cart whose payment failed. */\n get(cartId: string, options?: RequestOptions): Promise<Cart>;\n /** `POST /v1/carts/:id/lines`: adds units of a variant. */\n addLine(\n cartId: string,\n input: AddLineInput,\n options?: RequestOptions,\n ): Promise<Cart>;\n /**\n * `PATCH /v1/carts/:id/lines/:lineId`: sets a line's quantity. `lineId`\n * is `CartLine.id`; a variant id still matches a line without text.\n */\n updateLine(\n cartId: string,\n lineId: string,\n input: UpdateLineInput,\n options?: RequestOptions,\n ): Promise<Cart>;\n /** `DELETE /v1/carts/:id/lines/:lineId`: removes a line (`CartLine.id`). */\n removeLine(\n cartId: string,\n lineId: string,\n options?: RequestOptions,\n ): Promise<Cart>;\n /** `PUT /v1/carts/:id/customer`: sets the buyer. */\n setCustomer(\n cartId: string,\n input: CustomerInput,\n options?: RequestOptions,\n ): Promise<Cart>;\n /** `PUT /v1/carts/:id/address`: sets the shipping (and billing) address. */\n setAddress(\n cartId: string,\n input: AddressInput,\n options?: RequestOptions,\n ): Promise<Cart>;\n /** `GET /v1/carts/:id/shipping-options`: the options this cart can use. */\n shippingOptions(\n cartId: string,\n options?: RequestOptions,\n ): Promise<ShippingOptionList>;\n /** `PUT /v1/carts/:id/shipping-option`: selects a shipping option by id. */\n setShippingOption(\n cartId: string,\n optionId: string,\n options?: RequestOptions,\n ): Promise<Cart>;\n /**\n * `POST /v1/carts/:id/checkout`: places the order (or re-opens payment\n * for the cart's order) and answers how to present payment. Keep the\n * returned `token`: it is returned only once. Not retried.\n *\n * Aborting (`signal`) only stops waiting: the server may still place\n * the order. Read the cart again before showing a result.\n *\n * When `store.checkoutChallenge` is set, pass a fresh\n * `turnstileToken` (see `renderTurnstile`); tokens are single-use, so\n * reset the widget after every call. Re-opening payment on an already\n * ordered cart needs no token.\n */\n checkout(\n cartId: string,\n options?: CheckoutOptions,\n ): Promise<CheckoutResult>;\n };\n /** Buyer order status. */\n readonly orders: {\n /** `GET /v1/orders/:id?token=`: the order, for the buyer holding its token. */\n get(\n orderId: string,\n token: string,\n options?: RequestOptions,\n ): Promise<Order>;\n };\n /**\n * The signed-in buyer's account. Sign-in is by an e-mailed one-time code;\n * the session is an HttpOnly cookie (`konfiqo_session`) the API sets on the\n * store origin, so these calls send `credentials: 'include'`. On a server,\n * forward the buyer's cookie with the `cookie` call option.\n */\n readonly account: {\n /**\n * `POST /v1/account/code`: e-mails a 6-digit code. Resolves the same for\n * any address (202); rejects `too_many_code_requests` (429),\n * `challenge_required` / `challenge_failed`, `invalid_request`.\n */\n requestCode(email: string, options?: RequestCodeOptions): Promise<void>;\n /**\n * `POST /v1/account/session`: signs in with the code. A wrong, spent or\n * expired code rejects `invalid_code` (401).\n */\n signIn(\n email: string,\n code: string,\n options?: RequestOptions,\n ): Promise<AccountSession>;\n /** `DELETE /v1/account/session`: signs out (always succeeds). */\n signOut(options?: RequestOptions): Promise<void>;\n /**\n * `GET /v1/account[?page=]`: profile, saved addresses and a page of\n * orders (20 per page, newest first). Rejects `not_signed_in` (401).\n */\n get(page?: number, options?: RequestOptions): Promise<Account>;\n /**\n * `PUT /v1/account/profile`: saves name, surname and a Turkish mobile\n * phone. Creates the buyer's record on first save.\n */\n updateProfile(\n profile: AccountProfileInput,\n options?: RequestOptions,\n ): Promise<void>;\n /**\n * `PUT /v1/account/addresses`: replaces the saved addresses (at most 5,\n * at most one default). Resolves the list as stored (ids filled in).\n * Rejects `profile_required` (409) until a profile is saved.\n */\n saveAddresses(\n addresses: SavedAddressInput[],\n options?: RequestOptions,\n ): Promise<SavedAddress[]>;\n };\n /** Catalog images. */\n readonly media: {\n /**\n * The absolute URL of a storage key (product `image`, store `logo`,\n * theme `logo` / `favicon` / section `image`), usable in `<img src>`:\n * `${baseUrl}/v1/media/<key, each segment encoded>?pk=<publishable key>`.\n *\n * @throws TypeError (`invalid_path_segment`) when a key segment is\n * empty, `.` or `..`.\n */\n url(key: string): string;\n };\n}\n\ntype Method = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n\n/**\n * One encoded path segment. `encodeURIComponent` leaves `.` and `..` as\n * they are, and URL normalisation would turn them into another route, so\n * those (and an empty segment) are refused.\n */\nfunction seg(v: string): string {\n if (typeof v !== 'string' || v === '' || v === '.' || v === '..') {\n throw new TypeError(\n `invalid_path_segment: ${JSON.stringify(v)} is not a valid path segment`,\n );\n }\n return encodeURIComponent(v);\n}\n\n/** Whether this host looks like a browser or a web worker. */\nfunction isBrowserLike(): boolean {\n const g = globalThis as { importScripts?: unknown };\n return (\n typeof window !== 'undefined' ||\n typeof document !== 'undefined' ||\n (typeof self !== 'undefined' && typeof g.importScripts === 'function')\n );\n}\n\n/**\n * Creates a Storefront API client.\n *\n * @throws TypeError when `baseUrl` or `publishableKey` is empty, when\n * `serverKey` or `trustedStorefrontKey` is given without `buyerIp`, when\n * both keys are given together, or when either key is given in a\n * browser-like host (`window` or `document` defined, or a web worker).\n * Hosts that define `window` on a server (jsdom, Electron renderers,\n * React Native) are refused too: keep these keys in a plain server process.\n */\nexport function createStorefrontClient(\n options: StorefrontClientOptions,\n): StorefrontClient {\n const baseUrl = options.baseUrl?.trim().replace(/\\/+$/, '');\n if (!baseUrl)\n throw new TypeError('createStorefrontClient: baseUrl is required');\n const publishableKey = options.publishableKey?.trim();\n if (!publishableKey)\n throw new TypeError('createStorefrontClient: publishableKey is required');\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n if (!(timeoutMs > 0) || !Number.isFinite(timeoutMs)) {\n throw new TypeError(\n 'createStorefrontClient: timeoutMs must be a positive number',\n );\n }\n\n const baseHeaders: Record<string, string> = {\n [PUBLISHABLE_KEY_HEADER]: publishableKey,\n };\n if (\n options.serverKey !== undefined &&\n options.trustedStorefrontKey !== undefined\n ) {\n throw new TypeError(\n 'createStorefrontClient: serverKey and trustedStorefrontKey cannot be used together',\n );\n }\n if (options.serverKey !== undefined) {\n if (isBrowserLike()) {\n throw new TypeError(\n 'createStorefrontClient: serverKey must never be used in a browser',\n );\n }\n const buyerIp = options.buyerIp?.trim();\n if (!buyerIp) {\n throw new TypeError(\n 'createStorefrontClient: buyerIp is required with serverKey',\n );\n }\n baseHeaders[SERVER_KEY_HEADER] = options.serverKey;\n baseHeaders[BUYER_IP_HEADER] = buyerIp;\n }\n if (options.trustedStorefrontKey !== undefined) {\n if (isBrowserLike()) {\n throw new TypeError(\n 'createStorefrontClient: trustedStorefrontKey is server-only and must never be used in a browser',\n );\n }\n const buyerIp = options.buyerIp?.trim();\n if (!buyerIp) {\n throw new TypeError(\n 'createStorefrontClient: buyerIp is required with trustedStorefrontKey',\n );\n }\n baseHeaders[STOREFRONT_KEY_HEADER] = options.trustedStorefrontKey;\n baseHeaders[BUYER_IP_HEADER] = buyerIp;\n }\n\n async function request<T>(\n method: Method,\n path: () => string,\n body?: unknown,\n callOptions?: RequestOptions,\n extraHeaders: Record<string, string> = {},\n flags: { credentials?: boolean; emptyOk?: boolean } = {},\n ): Promise<T> {\n const url = `${baseUrl}${path()}`;\n const callerSignal = callOptions?.signal;\n if (callerSignal?.aborted) throw abortError(callerSignal);\n // Resolved per call (not at construction) so a polyfilled global works.\n // Called detached: a browser `fetch` must not be invoked on another `this`.\n const doFetch = options.fetch ?? globalThis.fetch;\n const headers: Record<string, string> = {\n ...baseHeaders,\n ...extraHeaders,\n };\n if (callOptions?.cookie) headers.cookie = callOptions.cookie;\n const init: RequestInit = { method, headers };\n if (flags.credentials) init.credentials = 'include';\n if (body !== undefined) {\n headers['content-type'] = 'application/json';\n init.body = JSON.stringify(body);\n }\n const controller = new AbortController();\n init.signal = controller.signal;\n let timedOut = false;\n // Raced as well as aborted: a custom `fetch` that ignores the signal\n // still cannot hold the caller past the timeout.\n let onTimeout: (e: StorefrontError) => void = () => {};\n const deadline = new Promise<never>((_, reject) => {\n onTimeout = reject;\n });\n deadline.catch(() => {});\n const timer = setTimeout(() => {\n timedOut = true;\n onTimeout(transportError(undefined, true, timeoutMs));\n controller.abort();\n }, timeoutMs);\n const onCallerAbort = () => {\n onTimeout(abortError(callerSignal!));\n controller.abort();\n };\n callerSignal?.addEventListener('abort', onCallerAbort, { once: true });\n\n try {\n let res: Response;\n let text: string;\n try {\n res = await Promise.race([doFetch(url, init), deadline]);\n text = await Promise.race([res.text(), deadline]);\n } catch (e) {\n if (e instanceof StorefrontError) throw e;\n throw transportError(e, timedOut, timeoutMs);\n }\n let parsed: unknown;\n let isJson = false;\n if (text !== '') {\n try {\n parsed = JSON.parse(text);\n isJson = true;\n } catch {\n parsed = undefined;\n }\n }\n if (!res.ok) throw errorFromResponse(res.status, parsed, res.headers);\n if (!isJson && flags.emptyOk && text === '') return undefined as T;\n if (!isJson) {\n throw new StorefrontError(\n 'invalid_response',\n res.status,\n 'Storefront API answered a non-JSON body',\n undefined,\n );\n }\n return parsed as T;\n } finally {\n clearTimeout(timer);\n callerSignal?.removeEventListener('abort', onCallerAbort);\n }\n }\n\n const get = <T>(path: () => string, options?: RequestOptions) =>\n request<T>('GET', path, undefined, options);\n const acct = { credentials: true } as const;\n const send = <T>(\n method: Method,\n path: string,\n body: unknown,\n o?: RequestOptions,\n extra: Record<string, string> = {},\n emptyOk = false,\n ) => request<T>(method, () => path, body, o, extra, { ...acct, emptyOk });\n const cart = (id: string) => `/v1/carts/${seg(id)}`;\n\n return {\n getContent: (key, o) =>\n get<StoreContent>(() => `/v1/content/${seg(key)}`, o),\n store: {\n get: (o) => get<Store>(() => '/v1/store', o),\n },\n categories: {\n list: (o) => get<CategoryList>(() => '/v1/categories', o),\n },\n products: {\n list: (query = {}, o) =>\n get<ProductPage>(() => {\n const params = new URLSearchParams();\n if (query.category !== undefined)\n params.set('category', query.category);\n if (query.q !== undefined) params.set('q', query.q);\n if (query.page !== undefined) params.set('page', String(query.page));\n if (query.pageSize !== undefined)\n params.set('pageSize', String(query.pageSize));\n const qs = params.toString();\n return `/v1/products${qs ? `?${qs}` : ''}`;\n }, o),\n get: (slug, o) => get<Product>(() => `/v1/products/${seg(slug)}`, o),\n },\n carts: {\n create: (o) => request<Cart>('POST', () => '/v1/carts', undefined, o),\n recover: (token, o) =>\n request<{ cartId: string }>(\n 'POST',\n () => '/v1/carts/recover',\n { token },\n o,\n ),\n get: (cartId, o) => get<Cart>(() => cart(cartId), o),\n addLine: (cartId, input, o) =>\n request<Cart>(\n 'POST',\n () => `${cart(cartId)}/lines`,\n {\n variantId: input.variantId,\n quantity: input.quantity,\n ...(input.personalization !== undefined && {\n personalization: input.personalization,\n }),\n },\n o,\n ),\n updateLine: (cartId, lineId, input, o) =>\n request<Cart>(\n 'PATCH',\n () => `${cart(cartId)}/lines/${seg(lineId)}`,\n { quantity: input.quantity },\n o,\n ),\n removeLine: (cartId, lineId, o) =>\n request<Cart>(\n 'DELETE',\n () => `${cart(cartId)}/lines/${seg(lineId)}`,\n undefined,\n o,\n ),\n setCustomer: (cartId, input, o) =>\n request<Cart>('PUT', () => `${cart(cartId)}/customer`, input, o),\n setAddress: (cartId, input, o) =>\n request<Cart>('PUT', () => `${cart(cartId)}/address`, input, o),\n shippingOptions: (cartId, o) =>\n get<ShippingOptionList>(() => `${cart(cartId)}/shipping-options`, o),\n setShippingOption: (cartId, optionId, o) =>\n request<Cart>(\n 'PUT',\n () => `${cart(cartId)}/shipping-option`,\n { id: optionId },\n o,\n ),\n checkout: (cartId, o) =>\n request<CheckoutResult>(\n 'POST',\n () => `${cart(cartId)}/checkout`,\n undefined,\n o,\n o?.turnstileToken\n ? { [TURNSTILE_TOKEN_HEADER]: o.turnstileToken }\n : {},\n ),\n },\n orders: {\n get: (orderId, token, o) =>\n get<Order>(\n () => `/v1/orders/${seg(orderId)}?token=${encodeURIComponent(token)}`,\n o,\n ),\n },\n account: {\n requestCode: (email, o) =>\n send<void>(\n 'POST',\n '/v1/account/code',\n { email },\n o,\n o?.turnstileToken\n ? { [TURNSTILE_TOKEN_HEADER]: o.turnstileToken }\n : {},\n true,\n ),\n signIn: (email, code, o) =>\n send<AccountSession>('POST', '/v1/account/session', { email, code }, o),\n signOut: (o) =>\n send<void>('DELETE', '/v1/account/session', undefined, o, {}, true),\n get: (page, o) =>\n send<Account>(\n 'GET',\n page === undefined\n ? '/v1/account'\n : `/v1/account?page=${encodeURIComponent(String(page))}`,\n undefined,\n o,\n ),\n updateProfile: (profile, o) =>\n send<void>(\n 'PUT',\n '/v1/account/profile',\n {\n name: profile.name,\n surname: profile.surname,\n phone: profile.phone,\n },\n o,\n {},\n true,\n ),\n saveAddresses: async (addresses, o) =>\n (\n await send<{ addresses: SavedAddress[] }>(\n 'PUT',\n '/v1/account/addresses',\n { addresses },\n o,\n )\n ).addresses,\n },\n media: {\n url: (key) =>\n `${baseUrl}/v1/media/${key.split('/').map(seg).join('/')}?pk=${encodeURIComponent(publishableKey)}`,\n },\n };\n}\n\n/** The caller aborted the request (`options.signal`). */\nfunction abortError(signal: AbortSignal): StorefrontError {\n return new StorefrontError(\n 'aborted',\n 0,\n 'Storefront API request was aborted',\n undefined,\n { cause: signal.reason },\n );\n}\n\n/** A fetch / body-read failure as `timeout` or `network_error`. */\nfunction transportError(\n e: unknown,\n timedOut: boolean,\n timeoutMs: number,\n): StorefrontError {\n if (timedOut) {\n return new StorefrontError(\n 'timeout',\n 0,\n `Storefront API did not answer within ${timeoutMs} ms`,\n { timeoutMs },\n { cause: e },\n );\n }\n return new StorefrontError(\n 'network_error',\n 0,\n 'Storefront API could not be reached',\n undefined,\n {\n cause: e,\n },\n );\n}\n","/**\n * Store theme, `schemaVersion: 1` (the commerce module's \"Store settings\n * JSON\"). The Storefront API passes the theme through **as stored**: it is\n * not validated, so every field is optional and a renderer must tolerate\n * missing values, wrong types and keys it does not know. Image fields are\n * tenant storage keys — turn them into URLs with `client.media.url(key)`.\n */\nexport interface ThemeV1 {\n /** `1` for this shape. Anything else: render defaults. */\n schemaVersion?: number;\n /** Storage key of the logo (the same key as the store's `logo`). */\n logo?: string | null;\n /** Storage key of the favicon. */\n favicon?: string | null;\n /** Theme colors, CSS color strings (normally `#rrggbb`). */\n colors?: ThemeColors;\n /** One of {@link THEME_FONTS}; an unknown value means \"use the default font\". */\n font?: ThemeFont | (string & {});\n /** The homepage, as ordered sections. */\n homepage?: ThemeHomepage;\n /** Footer links and social profiles. */\n footer?: ThemeFooter;\n /** Keys this SDK version does not know are kept as stored. */\n [key: string]: unknown;\n}\n\n/** Theme colors. Each is a CSS color string; any may be missing. */\nexport interface ThemeColors {\n /** Primary brand color. */\n primary?: string;\n /** Accent (links, highlights). */\n accent?: string;\n /** Page background. */\n background?: string;\n /** Body text. */\n text?: string;\n /** Unknown color keys are kept as stored. */\n [key: string]: unknown;\n}\n\n/** The fonts a v1 theme may name. */\nexport const THEME_FONTS = [\n 'inter',\n 'roboto',\n 'open-sans',\n 'lato',\n 'poppins',\n] as const;\n\n/** A font a v1 theme may name. */\nexport type ThemeFont = (typeof THEME_FONTS)[number];\n\n/** The homepage: sections in display order. */\nexport interface ThemeHomepage {\n /**\n * Sections in display order. May contain section types this SDK does not\n * know (skip them) — narrow with {@link isKnownThemeSection}.\n */\n sections?: ThemeSection[];\n /** Unknown homepage keys are kept as stored. */\n [key: string]: unknown;\n}\n\n/** A call-to-action link. */\nexport interface ThemeLink {\n /** Visible text. */\n label?: string;\n /** Target URL or path. */\n href?: string;\n}\n\n/** `hero`: a large banner with an optional image and call to action. */\nexport interface HeroSection {\n /** Discriminator. */\n type: 'hero';\n /** Storage key of the banner image. */\n image?: string | null;\n /** Headline. */\n title?: string;\n /** Sub-headline. */\n subtitle?: string;\n /** Optional call-to-action button. */\n cta?: ThemeLink;\n}\n\n/** `featuredProducts`: a hand-picked list of products. */\nexport interface FeaturedProductsSection {\n /** Discriminator. */\n type: 'featuredProducts';\n /** Section heading. */\n title?: string;\n /** Product slugs, in display order. Slugs no longer sold are skipped. */\n productSlugs?: string[];\n}\n\n/** `categoryGrid`: a grid of category tiles. */\nexport interface CategoryGridSection {\n /** Discriminator. */\n type: 'categoryGrid';\n /** Category slugs, in display order. Unknown slugs are skipped. */\n categorySlugs?: string[];\n}\n\n/**\n * `richText`: seller-written text. Render it as text or sanitized\n * markdown — never as raw HTML.\n */\nexport interface RichTextSection {\n /** Discriminator. */\n type: 'richText';\n /** The text. */\n content?: string;\n}\n\n/** A section type this SDK knows how to describe. */\nexport type KnownThemeSection =\n HeroSection | FeaturedProductsSection | CategoryGridSection | RichTextSection;\n\n/** A section of a type this SDK version does not know; renderers skip it. */\nexport interface UnknownThemeSection {\n /** The stored type. */\n type: string;\n /** Other stored keys. */\n [key: string]: unknown;\n}\n\n/** A homepage section as stored: a known section or an unknown one. */\nexport type ThemeSection = KnownThemeSection | UnknownThemeSection;\n\nconst KNOWN_SECTION_TYPES: ReadonlySet<string> = new Set([\n 'hero',\n 'featuredProducts',\n 'categoryGrid',\n 'richText',\n]);\n\n/**\n * Whether a stored section is one of the known types. After this guard a\n * `switch (section.type)` narrows to the exact section shape.\n */\nexport function isKnownThemeSection(\n section: unknown,\n): section is KnownThemeSection {\n return (\n typeof section === 'object' &&\n section !== null &&\n typeof (section as { type?: unknown }).type === 'string' &&\n KNOWN_SECTION_TYPES.has((section as { type: string }).type)\n );\n}\n\n/** Social profile URLs; only filled ones are stored. */\nexport interface ThemeSocial {\n /** Instagram profile URL. */\n instagram?: string;\n /** Facebook page URL. */\n facebook?: string;\n /** X profile URL. */\n x?: string;\n /** TikTok profile URL. */\n tiktok?: string;\n /** YouTube channel URL. */\n youtube?: string;\n /** Unknown networks are kept as stored. */\n [key: string]: unknown;\n}\n\n/** Footer configuration. */\nexport interface ThemeFooter {\n /** Footer links, in display order. */\n links?: ThemeLink[];\n /** Social profiles. */\n social?: ThemeSocial;\n /** Unknown footer keys are kept as stored. */\n [key: string]: unknown;\n}\n","import type {\n CheckoutEmbed,\n CheckoutResult,\n ClosedCheckoutPage,\n EmbeddedCheckoutResult,\n RedirectCheckoutResult,\n ClosedCheckoutResult,\n} from './models';\n\n/**\n * What {@link mountPayment} renders: a checkout result, or just its\n * presentation part.\n */\nexport type PaymentPresentation =\n | Pick<EmbeddedCheckoutResult, 'presentation' | 'embed'>\n | Pick<RedirectCheckoutResult, 'presentation' | 'url'>\n | Pick<ClosedCheckoutResult, 'presentation' | 'page'>;\n\n/** Options of {@link mountPayment}. */\nexport interface MountPaymentOptions {\n /**\n * Called for `presentation: \"closed\"` with the page to show (`paid`,\n * `cancelled`, `processing`, …). Typically: go to the order status page.\n */\n onClosed?: (page: ClosedCheckoutPage) => void;\n}\n\n/** The provider form is in the element. */\nexport interface EmbeddedPaymentMount {\n /** Discriminator. */\n kind: 'embedded';\n /** Removes the form from the element. */\n unmount(): void;\n}\n\n/** The browser is navigating to the provider's payment page. */\nexport interface RedirectPaymentMount {\n /** Discriminator. */\n kind: 'redirect';\n /** Where the browser was sent. */\n url: string;\n}\n\n/** Payment cannot be opened; `onClosed` was called. */\nexport interface ClosedPaymentMount {\n /** Discriminator. */\n kind: 'closed';\n /** The page to show. */\n page: ClosedCheckoutPage;\n}\n\n/**\n * The embed has a `kind` this SDK version cannot render. Nothing was put\n * in the element; show a fallback (e.g. \"payment unavailable\").\n */\nexport interface UnsupportedPaymentMount {\n /** Discriminator. */\n kind: 'unsupported';\n /** The embed kind that was not understood. */\n embedKind: string;\n}\n\n/** The result of {@link mountPayment}, discriminated by `kind`. */\nexport type PaymentMount =\n | EmbeddedPaymentMount\n | RedirectPaymentMount\n | ClosedPaymentMount\n | UnsupportedPaymentMount;\n\ninterface MountedForm {\n content: string;\n nodes: Node[];\n unmount: () => void;\n}\n\n/** What each element currently holds, so a repeat mount is a no-op. */\nconst mounted = new WeakMap<Element, MountedForm>();\n\n/**\n * Presents payment from a checkout result. Card data never touches your\n * page's code: the form is the provider's own, or a redirect.\n *\n * - `embedded` (`iyzico-checkout-form`): puts the provider's HTML into\n * `element` and re-creates every `<script>` in it so it executes\n * (`innerHTML` alone never runs scripts). Idempotent per element:\n * mounting the same content again does nothing, other content replaces\n * the previous form — scripts are never injected twice.\n * - `redirect`: top-level navigation to the provider page\n * (`location.assign`). Only `http:` / `https:` URLs are followed.\n * - `closed`: calls `onClosed(page)`.\n *\n * Browser only (needs a DOM).\n *\n * @throws TypeError for a redirect URL that is not `http(s)`.\n */\nexport function mountPayment(\n element: HTMLElement,\n presentation: PaymentPresentation | CheckoutResult,\n options: MountPaymentOptions = {},\n): PaymentMount {\n switch (presentation.presentation) {\n case 'embedded':\n return mountEmbedded(element, presentation.embed);\n case 'redirect': {\n const url = presentation.url;\n let protocol: string;\n try {\n protocol = new URL(url).protocol;\n } catch {\n protocol = '';\n }\n if (protocol !== 'https:' && protocol !== 'http:') {\n throw new TypeError('mountPayment: redirect URL must be http(s)');\n }\n const view = element.ownerDocument.defaultView;\n if (!view) throw new TypeError('mountPayment: element has no window');\n view.location.assign(url);\n return { kind: 'redirect', url };\n }\n case 'closed':\n options.onClosed?.(presentation.page);\n return { kind: 'closed', page: presentation.page };\n }\n}\n\nfunction mountEmbedded(\n element: HTMLElement,\n embed: CheckoutEmbed,\n): EmbeddedPaymentMount | UnsupportedPaymentMount {\n if (\n embed.kind !== 'iyzico-checkout-form' ||\n typeof embed.content !== 'string'\n ) {\n return { kind: 'unsupported', embedKind: String(embed.kind) };\n }\n const content = embed.content;\n const current = mounted.get(element);\n if (\n current &&\n current.content === content &&\n current.nodes.every((n) => n.parentNode === element)\n ) {\n return { kind: 'embedded', unmount: current.unmount };\n }\n\n element.replaceChildren();\n // The provider's own checkout form (from the payments service). It must\n // run its scripts, so it cannot be sanitised; it is the only HTML this\n // SDK ever injects.\n element.innerHTML = content;\n const doc = element.ownerDocument;\n for (const inert of Array.from(element.querySelectorAll('script'))) {\n const live = doc.createElement('script');\n for (const attr of Array.from(inert.attributes)) {\n live.setAttribute(attr.name, attr.value);\n }\n // Dynamically inserted external scripts are async by default; keep\n // document order like the provider's markup expects.\n if (live.hasAttribute('src')) live.async = false;\n live.text = inert.text;\n inert.replaceWith(live);\n }\n const entry: MountedForm = {\n content,\n nodes: Array.from(element.childNodes),\n unmount: () => {\n // A stale handle never removes a newer form.\n if (mounted.get(element) !== entry) return;\n for (const node of entry.nodes) node.parentNode?.removeChild(node);\n mounted.delete(element);\n },\n };\n mounted.set(element, entry);\n return { kind: 'embedded', unmount: entry.unmount };\n}\n","/**\n * Formats an integer amount of minor units (kuruş, cents, …) as a\n * localised currency string with `Intl.NumberFormat`, using the currency's\n * own number of minor digits (2 for `TRY`, 0 for `JPY`).\n *\n * @example formatMoney(14990, 'TRY', 'tr-TR') // \"₺149,90\"\n * @throws TypeError when `minor` is not a finite number; RangeError for an\n * unknown currency code (from `Intl`).\n */\nexport function formatMoney(\n minor: number,\n currency: string,\n locale?: string | string[],\n): string {\n if (typeof minor !== 'number' || !Number.isFinite(minor)) {\n throw new TypeError('formatMoney: minor must be a finite number');\n }\n const format = new Intl.NumberFormat(locale, { style: 'currency', currency });\n const digits = format.resolvedOptions().maximumFractionDigits ?? 2;\n return format.format(minor / 10 ** digits);\n}\n","import type { AdPixels, CookieInfo } from './models';\n\n// Pure helpers for choosing what a store host may load and list. They touch\n// no browser API, so they run in server code (for example a Next.js server\n// component) as well as in the browser.\n\n/** Whether `host` is a default store domain (`suffix` or below it). */\nexport function onDefaultDomain(\n host: string,\n suffix: string | undefined,\n): boolean {\n if (!suffix) return false;\n const h = host.toLowerCase();\n const s = suffix.toLowerCase();\n return h === s || h.endsWith(`.${s}`);\n}\n\n/**\n * The pixels a host may load: Meta and TikTok write their cookies to the\n * registrable domain, which every default store domain shares, so they run\n * only on custom domains.\n */\nexport function pixelsForHost(\n p: AdPixels | undefined,\n defaultDomain: boolean,\n): AdPixels | undefined {\n if (!p || !defaultDomain) return p;\n return p.google ? { google: p.google } : {};\n}\n\n/**\n * The cookies a host lists: on a default domain without the\n * `customDomainOnly` ones, and none at all when no optional cookie is left.\n */\nexport function cookiesForHost(\n cookies: CookieInfo[],\n defaultDomain: boolean,\n): CookieInfo[] {\n if (!defaultDomain) return cookies;\n const kept = cookies.filter((c) => !c.customDomainOnly);\n return kept.some((c) => c.category !== 'necessary') ? kept : [];\n}\n","/**\n * The part of the Web Storage API the cart-id helpers use; `localStorage`,\n * `sessionStorage` or any object with these methods (a cookie adapter, a\n * test double).\n */\nexport interface CartIdStorage {\n /** Reads a value, or null. */\n getItem(key: string): string | null;\n /** Writes a value. */\n setItem(key: string, value: string): void;\n /** Deletes a value. */\n removeItem(key: string): void;\n}\n\n/** The storage key of a store's cart id. Namespaced per store. */\nexport function cartIdKey(storeId: string): string {\n return `storefront:cart:${storeId}`;\n}\n\n/**\n * The saved cart id of a store, or null. Never throws: a missing storage\n * (SSR), a storage that throws (Safari private mode, blocked cookies) or\n * an empty value all read as null.\n */\nexport function loadCartId(\n storage: CartIdStorage | null | undefined,\n storeId: string,\n): string | null {\n try {\n const v = storage?.getItem(cartIdKey(storeId));\n return typeof v === 'string' && v.trim() !== '' ? v.trim() : null;\n } catch {\n return null;\n }\n}\n\n/** Saves a store's cart id. Returns false when the storage refused. Never throws. */\nexport function saveCartId(\n storage: CartIdStorage | null | undefined,\n storeId: string,\n cartId: string,\n): boolean {\n if (!storage) return false;\n try {\n storage.setItem(cartIdKey(storeId), cartId);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Forgets a store's cart id (after `cart_not_found`, or `cart_read_only`\n * with `status: \"expired\"`). Returns false when the storage refused. Never throws.\n */\nexport function clearCartId(\n storage: CartIdStorage | null | undefined,\n storeId: string,\n): boolean {\n if (!storage) return false;\n try {\n storage.removeItem(cartIdKey(storeId));\n return true;\n } catch {\n return false;\n }\n}\n\n/** The part of `document` the cookie storage uses. */\nexport interface CookieJar {\n cookie: string;\n}\n\n/** The cookie carrying the cart ids. */\nconst CART_COOKIE = '__Host-konfiqo_cart';\n/** Largest encoded cookie value written (browsers drop a cookie over ~4 KB). */\nconst MAX_COOKIE_VALUE = 3500;\n/** One year, seconds. */\nconst COOKIE_MAX_AGE = 31_536_000;\n\nfunction readMap(doc: CookieJar): Record<string, string> {\n try {\n for (const part of doc.cookie.split(';')) {\n const p = part.trim();\n if (!p.startsWith(`${CART_COOKIE}=`)) continue;\n const parsed: unknown = JSON.parse(\n decodeURIComponent(p.slice(CART_COOKIE.length + 1)),\n );\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n return {};\n }\n const out: Record<string, string> = {};\n for (const [k, v] of Object.entries(parsed)) {\n if (typeof v === 'string') out[k] = v;\n }\n return out;\n }\n } catch {\n // Malformed cookie: ignored (and replaced by the next write).\n }\n return {};\n}\n\nfunction writeMap(doc: CookieJar, map: Record<string, string>): boolean {\n const attrs = '; Path=/; SameSite=Lax; Secure';\n const keys = Object.keys(map);\n if (keys.length === 0) {\n doc.cookie = `${CART_COOKIE}=; Max-Age=0${attrs}`;\n return true;\n }\n const value = encodeURIComponent(JSON.stringify(map));\n if (value.length > MAX_COOKIE_VALUE) return false;\n doc.cookie = `${CART_COOKIE}=${value}; Max-Age=${COOKIE_MAX_AGE}${attrs}`;\n return true;\n}\n\n/**\n * Cart ids in the first-party `__Host-konfiqo_cart` cookie (path\n * `/`, no `Domain`, `SameSite=Lax`, `Secure`). The `__Host-` prefix makes\n * browsers refuse a cookie of this name scoped to a parent domain, so a\n * sibling store subdomain cannot plant a cart; the old unprefixed\n * `konfiqo_cart` is never read. The value is a JSON map keyed by\n * {@link cartIdKey}, so a store's own frontend and the hosted checkout on the same domain share\n * the cart. `Secure` cookies are dropped by browsers on plain `http`\n * (other than `localhost`), so over http nothing is stored here; pair it\n * with a `localStorage` fallback. Without a document (SSR) it reads nothing and writes fail.\n * Never throws; a malformed or oversized cookie is ignored.\n *\n * @param doc Defaults to the global `document`; `null` disables it.\n */\nexport function cookieCartStorage(doc?: CookieJar | null): CartIdStorage {\n const jar = (): CookieJar | null =>\n doc === undefined\n ? ((globalThis as { document?: CookieJar }).document ?? null)\n : doc;\n return {\n getItem(key) {\n const d = jar();\n if (!d) return null;\n return readMap(d)[key] ?? null;\n },\n setItem(key, value) {\n const d = jar();\n if (!d) throw new Error('no document');\n const map = readMap(d);\n map[key] = value;\n if (!writeMap(d, map)) throw new Error('cart cookie too large');\n },\n removeItem(key) {\n const d = jar();\n if (!d) return;\n const map = readMap(d);\n if (!(key in map)) return;\n delete map[key];\n writeMap(d, map);\n },\n };\n}\n","/**\n * Cloudflare's official Turnstile script, explicit-render mode. The only\n * URL {@link loadTurnstile} ever injects.\n */\nexport const TURNSTILE_SCRIPT_URL =\n 'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit';\n\n/** The subset of Cloudflare's `window.turnstile` API the SDK uses. */\nexport interface TurnstileApi {\n /** Renders a widget into `container`; returns its widget id. */\n render(\n container: HTMLElement | string,\n params: {\n sitekey: string;\n callback?: (token: string) => void;\n 'expired-callback'?: () => void;\n 'error-callback'?: (code?: string) => void;\n [key: string]: unknown;\n },\n ): string | null | undefined;\n /** Resets a widget so it produces a new token. */\n reset(widgetId?: string): void;\n /** Removes a widget. */\n remove(widgetId?: string): void;\n}\n\ntype TurnstileWindow = Window & { turnstile?: TurnstileApi };\n\nconst loading = new WeakMap<Document, Promise<TurnstileApi>>();\n\n/**\n * Loads Cloudflare Turnstile into `document` (once: the script is injected\n * at most once per document, concurrent calls share one load) and resolves\n * with `window.turnstile`. Rejects when the script fails to load; the\n * failed `<script>` is removed, so calling again injects a fresh one.\n */\nexport function loadTurnstile(document: Document): Promise<TurnstileApi> {\n const view = document.defaultView as TurnstileWindow | null;\n if (!view)\n return Promise.reject(\n new TypeError('loadTurnstile: document has no window'),\n );\n if (view.turnstile) return Promise.resolve(view.turnstile);\n const pending = loading.get(document);\n if (pending) return pending;\n\n const promise = new Promise<TurnstileApi>((resolve, reject) => {\n let script = Array.from(document.scripts).find(\n (s) => s.src === TURNSTILE_SCRIPT_URL,\n );\n if (!script) {\n script = document.createElement('script');\n script.src = TURNSTILE_SCRIPT_URL;\n script.async = true;\n (document.head ?? document.documentElement).appendChild(script);\n }\n script.addEventListener('load', () => {\n if (view.turnstile) resolve(view.turnstile);\n else\n reject(\n new Error('loadTurnstile: script loaded without window.turnstile'),\n );\n });\n const tag = script;\n tag.addEventListener('error', () => {\n // A failed tag never loads again: remove it so a retry injects a\n // fresh one instead of waiting on the dead tag forever.\n tag.remove();\n reject(new Error('loadTurnstile: script failed to load'));\n });\n });\n loading.set(document, promise);\n // A failed load can be retried by calling again.\n promise.catch(() => {\n if (loading.get(document) === promise) loading.delete(document);\n });\n return promise;\n}\n\n/** Callbacks of {@link renderTurnstile}. */\nexport interface RenderTurnstileOptions {\n /** A token is ready: keep it for the next `carts.checkout` call. */\n onToken: (token: string) => void;\n /** The token expired unused (about 5 minutes): drop it; the widget refreshes. */\n onExpired?: () => void;\n /** The widget failed (network, unsupported browser, …). */\n onError?: (code?: string) => void;\n}\n\n/** A rendered Turnstile widget. */\nexport interface TurnstileWidget {\n /** The widget id. */\n readonly widgetId: string;\n /**\n * Gets a new token. Call it after every `carts.checkout` that used the\n * current token: tokens are **single-use**.\n */\n reset(): void;\n /** Removes the widget. */\n remove(): void;\n}\n\n/**\n * Renders a Turnstile widget with the store's `siteKey`\n * (`store.checkoutChallenge.siteKey`) into `element`, loading the script\n * first if needed. Pass each token from `onToken` to\n * `carts.checkout(id, { turnstileToken })`, then `reset()`.\n */\nexport async function renderTurnstile(\n element: HTMLElement,\n siteKey: string,\n options: RenderTurnstileOptions,\n): Promise<TurnstileWidget> {\n if (!siteKey) throw new TypeError('renderTurnstile: siteKey is required');\n const turnstile = await loadTurnstile(element.ownerDocument);\n const params: Parameters<TurnstileApi['render']>[1] = {\n sitekey: siteKey,\n callback: (token: string) => options.onToken(token),\n 'expired-callback': () => options.onExpired?.(),\n 'error-callback': (code?: string) => options.onError?.(code),\n };\n const widgetId = turnstile.render(element, params);\n if (!widgetId) throw new Error('renderTurnstile: the widget did not render');\n return {\n widgetId,\n reset: () => turnstile.reset(widgetId),\n remove: () => turnstile.remove(widgetId),\n };\n}\n","/** Version of the Storefront SDK package. */\nexport const SDK_VERSION = '0.6.1';\n\nexport {\n createStorefrontClient,\n DEFAULT_TIMEOUT_MS,\n PUBLISHABLE_KEY_HEADER,\n STOREFRONT_KEY_HEADER,\n BUYER_IP_HEADER,\n TURNSTILE_TOKEN_HEADER,\n} from './client';\nexport type {\n CheckoutOptions,\n RequestCodeOptions,\n RequestOptions,\n StorefrontClient,\n StorefrontClientOptions,\n} from './client';\nexport { StorefrontError, isStorefrontError } from './errors';\nexport type {\n AnyStorefrontError,\n BuyerDetailField,\n CheckoutMissing,\n StorefrontApiErrorCode,\n StorefrontClientErrorCode,\n StorefrontErrorCode,\n StorefrontErrorDetails,\n StorefrontErrorDetailsMap,\n ValidationIssue,\n} from './errors';\nexport type * from './models';\nexport { THEME_FONTS, isKnownThemeSection } from './theme';\nexport type {\n CategoryGridSection,\n FeaturedProductsSection,\n HeroSection,\n KnownThemeSection,\n RichTextSection,\n ThemeColors,\n ThemeFont,\n ThemeFooter,\n ThemeHomepage,\n ThemeLink,\n ThemeSection,\n ThemeSocial,\n ThemeV1,\n UnknownThemeSection,\n} from './theme';\nexport { mountPayment } from './payment';\nexport type {\n ClosedPaymentMount,\n EmbeddedPaymentMount,\n MountPaymentOptions,\n PaymentMount,\n PaymentPresentation,\n RedirectPaymentMount,\n UnsupportedPaymentMount,\n} from './payment';\nexport { formatMoney } from './money';\nexport { cookiesForHost, onDefaultDomain, pixelsForHost } from './host-pixels';\nexport {\n cartIdKey,\n clearCartId,\n cookieCartStorage,\n loadCartId,\n saveCartId,\n} from './cart-storage';\nexport type { CartIdStorage, CookieJar } from './cart-storage';\nexport {\n TURNSTILE_SCRIPT_URL,\n loadTurnstile,\n renderTurnstile,\n} from './turnstile';\nexport type {\n RenderTurnstileOptions,\n TurnstileApi,\n TurnstileWidget,\n} from './turnstile';\n"],"mappings":";AAkJA,IAAM,YAAiC,oBAAI,IAA4B;AAAA,EACrE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