@konfiqo/storefront-react 0.5.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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/provider.tsx","../src/cart-store.ts","../src/use-resource.ts","../src/catalog.ts","../src/use-cart.ts","../src/use-account.ts","../src/use-checkout.ts","../src/use-order.ts","../src/payment-form.tsx","../src/checkout-challenge.tsx","../src/content.tsx"],"sourcesContent":["'use client';\n\n// Every export is a hook or a client component (React Server Components /\n// Next.js App Router). esbuild keeps this entry directive in the build.\nexport { StorefrontProvider, useStorefrontClient } from './provider';\nexport type { ClientConfig, StorefrontProviderProps } from './provider';\nexport { useStore, useCategories, useProducts, useProduct } from './catalog';\nexport type { ResourceResult } from './use-resource';\nexport { useCart, useCartStorage } from './use-cart';\nexport type { UseCartResult } from './use-cart';\nexport { isDeadCartError, defaultCartStorage } from './cart-store';\nexport type {\n CartSnapshot,\n CheckoutSnapshot,\n StorefrontHookError,\n} from './cart-store';\nexport { useAccount } from './use-account';\nexport type { UseAccountResult } from './use-account';\nexport { useCheckout } from './use-checkout';\nexport type { CheckoutCallOptions, UseCheckoutResult } from './use-checkout';\nexport {\n useOrder,\n isOrderSettled,\n orderPollDelay,\n ORDER_POLL_MIN_MS,\n ORDER_POLL_MAX_MS,\n} from './use-order';\nexport type { UseOrderOptions, UseOrderResult } from './use-order';\nexport { PaymentForm } from './payment-form';\nexport type { PaymentFormProps } from './payment-form';\nexport { CheckoutChallenge } from './checkout-challenge';\nexport type {\n CheckoutChallengeHandle,\n CheckoutChallengeProps,\n} from './checkout-challenge';\nexport { Content, renderContent } from './content';\nexport type { ContentComponents, ContentProps } from './content';\n","import {\n createContext,\n useContext,\n useEffect,\n useMemo,\n useRef,\n type ReactNode,\n} from 'react';\nimport {\n createStorefrontClient,\n type CartIdStorage,\n type StorefrontClient,\n type StorefrontClientOptions,\n} from '@konfiqo/storefront-sdk';\nimport { CartStore, defaultCartStorage } from './cart-store';\n\n/** Client options the provider accepts: no secret keys, no buyer IP. */\nexport type ClientConfig = Omit<\n StorefrontClientOptions,\n 'serverKey' | 'trustedStorefrontKey' | 'buyerIp'\n>;\n\n/** Props of {@link StorefrontProvider}. */\nexport interface StorefrontProviderProps {\n /**\n * The store's id: namespaces the persisted cart id, so one origin can\n * serve several stores.\n */\n storeId: string;\n /** A client to use. Give either `client` or `config`. */\n client?: StorefrontClient;\n /**\n * Options to create the client with (when `client` is not given). The\n * secret keys `serverKey` and `trustedStorefrontKey`, and `buyerIp`, are\n * refused: props of a client component are serialized into the page HTML.\n */\n config?: ClientConfig;\n /**\n * Where the cart id is persisted. Default: the first-party `__Host-konfiqo_cart`\n * cookie (shared with a store's own frontend on the same domain) with\n * `window.localStorage` as a fallback, read lazily (never during render, so server rendering is safe). `null`\n * keeps the cart id in memory only (lost on reload).\n */\n cartStorage?: CartIdStorage | null;\n /** The storefront. */\n children?: ReactNode;\n}\n\ninterface StorefrontContextValue {\n client: StorefrontClient;\n storeId: string;\n cart: CartStore;\n}\n\nconst StorefrontContext = createContext<StorefrontContextValue | null>(null);\n\n/**\n * Makes a Storefront client and the buyer's cart available to the hooks\n * below it. Holds the cart state, so every `useCart()` under one provider\n * sees the same cart.\n *\n * @throws Error when neither `client` nor `config` is given, or when\n * `config` holds `serverKey`, `trustedStorefrontKey` or `buyerIp`.\n */\nexport function StorefrontProvider({\n storeId,\n client,\n config,\n cartStorage,\n children,\n}: StorefrontProviderProps) {\n const forbidden = ['serverKey', 'trustedStorefrontKey', 'buyerIp'].filter(\n (k) => config !== undefined && k in config,\n );\n if (forbidden.length > 0) {\n throw new Error(\n `StorefrontProvider: config.${forbidden.join(', config.')} must not be passed to a client component (it would reach the browser). Create a server-side client instead.`,\n );\n }\n const baseUrl = config?.baseUrl;\n const publishableKey = config?.publishableKey;\n const timeoutMs = config?.timeoutMs;\n const customFetch = config?.fetch;\n const resolved = useMemo(() => {\n if (client) return client;\n if (baseUrl === undefined || publishableKey === undefined) {\n throw new Error('StorefrontProvider: pass `client` or `config`');\n }\n return createStorefrontClient({\n baseUrl,\n publishableKey,\n timeoutMs,\n fetch: customFetch,\n });\n }, [client, baseUrl, publishableKey, timeoutMs, customFetch]);\n\n // Read by the cart store per call. Assigned during render (an\n // idempotent write of the latest props) so the store — keyed by\n // `storeId` only — always uses the current client and storage, and the\n // cart state survives a new client (e.g. a new `fetch` identity).\n const clientRef = useRef(resolved);\n clientRef.current = resolved;\n const storageRef = useRef(cartStorage);\n storageRef.current = cartStorage;\n\n const cart = useMemo(\n () =>\n new CartStore(\n () => clientRef.current,\n storeId,\n () =>\n storageRef.current === undefined\n ? defaultCartStorage()\n : storageRef.current,\n ),\n [storeId],\n );\n // Cancels the cart read when the provider goes away. Writes (and\n // checkout) are never aborted: the server may apply them anyway.\n useEffect(() => () => cart.abortReads(), [cart]);\n // Another tab changed this store's cart id: follow it.\n useEffect(() => {\n if (typeof window === 'undefined') return;\n const onStorage = (e: StorageEvent) => {\n const storage = cart.currentStorage();\n if (!storage) return;\n // The default storage names the `localStorage` it writes through.\n const area = (storage as { storageArea?: unknown }).storageArea;\n if (e.storageArea !== (area ?? storage)) return;\n if (e.key !== null && e.key !== cart.storageKey) return;\n cart.syncFromStorage();\n };\n window.addEventListener('storage', onStorage);\n return () => window.removeEventListener('storage', onStorage);\n }, [cart]);\n\n const value = useMemo(\n () => ({ client: resolved, storeId, cart }),\n [resolved, storeId, cart],\n );\n return (\n <StorefrontContext.Provider value={value}>\n {children}\n </StorefrontContext.Provider>\n );\n}\n\n/** The provider's context. Internal. */\nexport function useStorefrontContext(): StorefrontContextValue {\n const ctx = useContext(StorefrontContext);\n if (!ctx) {\n throw new Error(\n 'Storefront hooks must be used inside <StorefrontProvider>',\n );\n }\n return ctx;\n}\n\n/** The provider's context, or null outside a provider. Internal. */\nexport function useOptionalStorefrontContext(): StorefrontContextValue | null {\n return useContext(StorefrontContext);\n}\n\n/**\n * The provider's {@link StorefrontClient}, for calls the hooks do not\n * cover.\n */\nexport function useStorefrontClient(): StorefrontClient {\n return useStorefrontContext().client;\n}\n","import {\n StorefrontError,\n cartIdKey,\n clearCartId,\n cookieCartStorage,\n isStorefrontError,\n loadCartId,\n saveCartId,\n type AddLineInput,\n type AnyStorefrontError,\n type Cart,\n type CartIdStorage,\n type CheckoutResult,\n type RequestOptions,\n type ShippingOptionList,\n type StorefrontClient,\n} from '@konfiqo/storefront-sdk';\n\n/**\n * An error a hook reports: a {@link StorefrontError} (narrow with\n * `isStorefrontError` and switch on `code`), or a plain `Error` for\n * programming mistakes (e.g. an invalid slug).\n */\nexport type StorefrontHookError = AnyStorefrontError | Error;\n\n/** The cart part of the shared state. */\nexport interface CartSnapshot {\n /** The cart, or null when the buyer has none yet (created on the first write). */\n cart: Cart | null;\n /**\n * `idle` before the first read (and during server rendering), `loading`\n * while the saved cart is read, `ready` afterwards.\n */\n status: 'idle' | 'loading' | 'ready';\n /** A write is in progress. */\n isUpdating: boolean;\n /** The last read or write error, cleared by the next success. */\n error: StorefrontHookError | null;\n /**\n * The id of a cart this provider left because it was already `ordered`\n * when the buyer changed it (a write moved to a fresh cart). Lets the\n * app offer \"continue your payment\" for that order. Cleared by `reset()`.\n */\n previousCartId: string | null;\n}\n\n/** The checkout part of the shared state. */\nexport interface CheckoutSnapshot {\n /** A checkout call is in flight. */\n isPending: boolean;\n /** The last checkout's result. Holds the once-only order `token`. */\n result: CheckoutResult | null;\n /** The last checkout's error. */\n error: StorefrontHookError | null;\n /** Settled checkout calls so far (a challenge widget resets on each). */\n attempts: number;\n}\n\n/** Whether a write error means \"this cart is already ordered\". */\nfunction isOrderedCartError(e: unknown): boolean {\n return (\n isStorefrontError(e) &&\n e.code === 'cart_read_only' &&\n e.details.status === 'ordered'\n );\n}\n\n/** Whether a cart error means \"this cart is gone: start a new one\". */\nexport function isDeadCartError(e: unknown): boolean {\n if (!isStorefrontError(e)) return false;\n if (e.code === 'cart_not_found') return true;\n return e.code === 'cart_read_only' && e.details.status === 'expired';\n}\n\nconst toError = (e: unknown): StorefrontHookError =>\n e instanceof Error ? (e as StorefrontHookError) : new Error(String(e));\n\n/**\n * The buyer's cart and checkout state, shared by every hook under one\n * provider. Writes and checkout run one at a time, in call order, and\n * every write replaces the state with the server's cart view. Internal.\n */\nexport class CartStore {\n private cartState: CartSnapshot = {\n cart: null,\n status: 'idle',\n isUpdating: false,\n error: null,\n previousCartId: null,\n };\n private checkoutState: CheckoutSnapshot = {\n isPending: false,\n result: null,\n error: null,\n attempts: 0,\n };\n private readonly listeners = new Set<() => void>();\n private queue: Promise<void> = Promise.resolve();\n private cartId: string | null = null;\n private loadPromise: Promise<void> | null = null;\n private reads = new AbortController();\n private pendingCheckout: Promise<CheckoutResult> | null = null;\n private pendingWrites = 0;\n /**\n * Bumped by `reset()` (and a cart id changed in another tab): a queued\n * operation that started under an older epoch drops its outcome instead\n * of resurrecting (or persisting) the cart it was working on.\n */\n private epoch = 0;\n /**\n * Bumped by `reset()` only. A checkout in flight keeps its outcome (the\n * once-only order token) when another tab merely changes the cart id.\n */\n private resetEpoch = 0;\n /** Whether a checkout was started under this provider. */\n checkoutStarted = false;\n\n /**\n * @param getClient - the provider's current client (read per call, so\n * a new client — e.g. another `fetch` — keeps this cart state)\n */\n constructor(\n private readonly getClient: () => StorefrontClient,\n private readonly storeId: string,\n private readonly storage: () => CartIdStorage | null,\n ) {}\n\n private get client(): StorefrontClient {\n return this.getClient();\n }\n\n // ------------------------------------------------------ subscription\n\n subscribe = (listener: () => void): (() => void) => {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n };\n getCart = (): CartSnapshot => this.cartState;\n getCheckout = (): CheckoutSnapshot => this.checkoutState;\n\n private setCart(patch: Partial<CartSnapshot>): void {\n this.cartState = { ...this.cartState, ...patch };\n this.emit();\n }\n private setCheckout(patch: Partial<CheckoutSnapshot>): void {\n this.checkoutState = { ...this.checkoutState, ...patch };\n this.emit();\n }\n private emit(): void {\n for (const l of this.listeners) l();\n }\n\n /** Runs `fn` after everything queued before it. */\n private enqueue<T>(fn: () => Promise<T>): Promise<T> {\n const run = this.queue.then(fn);\n this.queue = run.then(\n () => undefined,\n () => undefined,\n );\n return run;\n }\n\n private currentId(): string | null {\n return this.cartId ?? loadCartId(this.storage(), this.storeId);\n }\n\n /** Forgets the cart: the next write creates a new one. */\n private forget(): void {\n this.cartId = null;\n clearCartId(this.storage(), this.storeId);\n }\n\n /** Puts a server cart view into the state (an expired cart is forgotten). */\n private apply(cart: Cart): void {\n if (cart.status === 'expired') {\n this.forget();\n this.setCart({ cart: null, status: 'ready', error: null });\n return;\n }\n if (this.cartId !== cart.id) {\n this.cartId = cart.id;\n saveCartId(this.storage(), this.storeId, cart.id);\n }\n this.setCart({ cart, status: 'ready', error: null });\n }\n\n // ------------------------------------------------------ reads\n\n /** Reads the saved cart once (later calls share the first read). */\n load = (): Promise<void> => {\n this.loadPromise ??= this.read();\n return this.loadPromise;\n };\n\n /**\n * Reads the cart again. Also how a cart whose payment failed shows up\n * as `open` again: the read reopens it on the server.\n */\n refresh = (): Promise<void> => this.read();\n\n /** Cancels pending cart reads (the provider unmounted). */\n abortReads(): void {\n this.reads.abort();\n this.reads = new AbortController();\n this.loadPromise = null;\n }\n\n private read(): Promise<void> {\n const signal = this.reads.signal;\n return this.enqueue(async () => {\n if (signal.aborted) {\n if (this.cartState.status === 'loading')\n this.setCart({ status: 'idle' });\n return;\n }\n const epoch = this.epoch;\n const id = this.currentId();\n if (!id) {\n this.setCart({ cart: null, status: 'ready' });\n return;\n }\n this.cartId = id;\n if (this.cartState.cart === null) this.setCart({ status: 'loading' });\n try {\n const cart = await this.client.carts.get(id, { signal });\n if (epoch !== this.epoch) return;\n this.apply(cart);\n } catch (e) {\n if (epoch !== this.epoch) return;\n if (signal.aborted) {\n if (this.cartState.status === 'loading')\n this.setCart({ status: 'idle' });\n return;\n }\n if (isDeadCartError(e)) {\n this.forget();\n this.setCart({ cart: null, status: 'ready', error: null });\n return;\n }\n this.setCart({ status: 'ready', error: toError(e) });\n }\n });\n }\n\n // ------------------------------------------------------ writes\n\n private write(op: (cartId: string) => Promise<Cart>): Promise<Cart> {\n this.pendingWrites++;\n this.setCart({ isUpdating: true });\n return this.enqueue(async () => {\n const epoch = this.epoch;\n const current = () => epoch === this.epoch;\n /** Runs `op` on the current cart, creating one if needed. */\n const attempt = async (): Promise<Cart> => {\n let id = this.currentId();\n if (!id) {\n // Created lazily: a buyer who only browses never gets a cart.\n const created = await this.client.carts.create();\n if (!current()) {\n // Reset (or another tab) while the cart was being created: do\n // not write into a cart nobody holds.\n throw new StorefrontError(\n 'aborted',\n 0,\n 'The cart was reset while the write was pending',\n undefined,\n );\n }\n this.apply(created);\n id = created.id;\n }\n return op(id);\n };\n try {\n let cart: Cart;\n try {\n cart = await attempt();\n } catch (e) {\n if (!current() || !isOrderedCartError(e)) throw e;\n // The cart was already checked out (its payment may still be\n // open): keep its id for the app, and replay the write once on\n // a fresh cart.\n const previousCartId = this.currentId();\n this.forget();\n this.setCart({ cart: null, previousCartId });\n cart = await attempt();\n }\n if (current()) this.apply(cart);\n return cart;\n } catch (e) {\n if (current()) {\n if (isDeadCartError(e)) {\n // Gone (expired / unknown): the next write starts a new cart.\n this.forget();\n this.setCart({ cart: null, status: 'ready' });\n }\n this.setCart({ error: toError(e) });\n }\n throw e;\n } finally {\n this.pendingWrites--;\n if (this.pendingWrites === 0) this.setCart({ isUpdating: false });\n }\n });\n }\n\n addLine = (input: AddLineInput) =>\n this.write((id) => this.client.carts.addLine(id, input));\n updateLine = (lineId: string, input: { quantity: number }) =>\n this.write((id) => this.client.carts.updateLine(id, lineId, input));\n removeLine = (lineId: string) =>\n this.write((id) => this.client.carts.removeLine(id, lineId));\n setCustomer = (\n input: Parameters<StorefrontClient['carts']['setCustomer']>[1],\n ) => this.write((id) => this.client.carts.setCustomer(id, input));\n setAddress = (\n input: Parameters<StorefrontClient['carts']['setAddress']>[1],\n ) => this.write((id) => this.client.carts.setAddress(id, input));\n setShippingOption = (optionId: string) =>\n this.write((id) => this.client.carts.setShippingOption(id, optionId));\n\n /** The shipping options of the cart (empty when there is no cart yet). */\n shippingOptions = async (\n options?: RequestOptions,\n ): Promise<ShippingOptionList> => {\n const id = this.currentId();\n if (!id) return { items: [] };\n return this.client.carts.shippingOptions(id, options);\n };\n\n /**\n * Forgets the cart (e.g. once its order is paid): the next write\n * creates a new one. The old cart is not deleted on the server.\n */\n reset = (): void => {\n this.epoch++;\n this.resetEpoch++;\n this.forget();\n this.loadPromise = null;\n this.setCart({\n cart: null,\n status: 'ready',\n error: null,\n previousCartId: null,\n });\n this.setCheckout({ result: null, error: null });\n };\n\n /**\n * The saved cart id changed in another tab (a `storage` event for this\n * store's key): follow it. Operations in flight on the old cart drop\n * their outcome.\n */\n syncFromStorage = (): void => {\n const id = loadCartId(this.storage(), this.storeId);\n if (id === this.cartId) return;\n this.epoch++;\n this.cartId = id;\n this.loadPromise = null;\n if (id === null) {\n this.setCart({ cart: null, status: 'ready', error: null });\n return;\n }\n void this.refresh();\n };\n\n /** The storage key this store persists its cart id under. */\n get storageKey(): string {\n return cartIdKey(this.storeId);\n }\n\n /** The storage the cart id is kept in (null: memory only). */\n currentStorage(): CartIdStorage | null {\n return this.storage();\n }\n\n // ------------------------------------------------------ checkout\n\n /**\n * Checks the cart out. Never aborted (the server may place the order\n * anyway); a second call while one is in flight returns the same\n * promise. The cart is read again afterwards.\n */\n checkout = (\n options: { turnstileToken?: string } = {},\n ): Promise<CheckoutResult> => {\n if (this.pendingCheckout) return this.pendingCheckout;\n this.checkoutStarted = true;\n this.setCheckout({ isPending: true, error: null });\n let epoch = this.resetEpoch;\n const run = this.enqueue(async () => {\n epoch = this.resetEpoch;\n const id = this.currentId();\n if (!id) {\n throw new StorefrontError(\n 'checkout_incomplete',\n 0,\n 'There is no cart to check out',\n { missing: ['lines'] },\n );\n }\n return this.client.carts.checkout(id, {\n turnstileToken: options.turnstileToken || undefined,\n });\n });\n this.pendingCheckout = run;\n run.then(\n (result) => this.settleCheckout(epoch, { result, error: null }),\n (e: unknown) =>\n this.settleCheckout(epoch, { result: null, error: toError(e) }),\n );\n return run;\n };\n\n private settleCheckout(\n epoch: number,\n patch: Partial<CheckoutSnapshot>,\n ): void {\n this.pendingCheckout = null;\n this.setCheckout({\n // After `reset()` the outcome belongs to a cart the buyer left.\n ...(epoch === this.resetEpoch ? patch : {}),\n isPending: false,\n attempts: this.checkoutState.attempts + 1,\n });\n // Shows what the server now has: `ordered`, or the new prices after\n // `cart_changed`.\n void this.refresh();\n }\n\n /** Clears the last checkout result and error. */\n clearCheckout = (): void => {\n this.setCheckout({ result: null, error: null });\n };\n}\n\n/**\n * The default cart-id storage in a browser: the first-party `__Host-konfiqo_cart`\n * cookie (shared with a store's own frontend on the same domain) backed by\n * `localStorage`. Reads prefer the cookie, and each read that finds it\n * rewrites it, renewing its expiry. Safari caps a script-written cookie to\n * 7 days, so a cookie may expire while `localStorage` still holds the id:\n * then the id is read from `localStorage` and written back into the cookie.\n * Writes go to both, so the cart still persists when cookies are blocked.\n *\n * `removeItem` (the cart deliberately cleared on this origin) leaves a\n * tombstone in `localStorage`, which every frontend on the store origin\n * shares: while it is there an id left in `localStorage` is not brought\n * back. `setItem` clears it. Null on a server.\n */\nexport function defaultCartStorage(): CartIdStorage | null {\n if (typeof window === 'undefined') return null;\n let local: Storage | null = null;\n try {\n local = window.localStorage;\n } catch {\n local = null;\n }\n const cookie = cookieCartStorage();\n const attempt = (f: () => void): boolean => {\n try {\n f();\n return true;\n } catch {\n return false;\n }\n };\n const tombstoneKey = (key: string) => `${key}:cleared`;\n /** The marker an earlier version set; removed wherever it is seen. */\n const legacyMarkerKey = (key: string) => `${key}:in-cookie`;\n const cleared = (key: string): boolean => {\n try {\n return local?.getItem(tombstoneKey(key)) === '1';\n } catch {\n return false;\n }\n };\n const storage: CartIdStorage & { storageArea: Storage | null } = {\n // The area a `storage` event of another tab names.\n storageArea: local,\n getItem(key) {\n let fromCookie: string | null = null;\n try {\n fromCookie = cookie.getItem(key);\n } catch {\n fromCookie = null;\n }\n if (fromCookie) {\n // Renews the expiry (Safari: 7 days from the last write).\n attempt(() => cookie.setItem(key, fromCookie));\n return fromCookie;\n }\n let fromLocal: string | null = null;\n try {\n fromLocal = local?.getItem(key) ?? null;\n } catch {\n fromLocal = null;\n }\n if (!fromLocal) return null;\n // Cleared on purpose on this origin: do not bring the old id back.\n if (cleared(key)) return null;\n // The cookie expired, or never existed: put the id back into it.\n attempt(() => cookie.setItem(key, fromLocal));\n return fromLocal;\n },\n setItem(key, value) {\n const a = attempt(() => cookie.setItem(key, value));\n const b = local ? attempt(() => local.setItem(key, value)) : false;\n if (local) {\n attempt(() => local.removeItem(tombstoneKey(key)));\n attempt(() => local.removeItem(legacyMarkerKey(key)));\n }\n if (!a && !b) throw new Error('no cart storage available');\n },\n removeItem(key) {\n attempt(() => cookie.removeItem(key));\n if (local) {\n attempt(() => local.removeItem(key));\n attempt(() => local.setItem(tombstoneKey(key), '1'));\n attempt(() => local.removeItem(legacyMarkerKey(key)));\n }\n },\n };\n return storage;\n}\n","import { useCallback, useEffect, useRef, useState } from 'react';\nimport type { StorefrontHookError } from './cart-store';\n\n/** What a read hook returns. */\nexport interface ResourceResult<T> {\n /** The data, or null before it arrives (and after an error). */\n data: T | null;\n /** The error of the last read, or null. */\n error: StorefrontHookError | null;\n /** A read is in progress. */\n isLoading: boolean;\n /** Reads again. */\n refetch: () => void;\n}\n\ninterface State<T> {\n key: string | null;\n data: T | null;\n error: StorefrontHookError | null;\n isLoading: boolean;\n}\n\nconst toError = (e: unknown): StorefrontHookError =>\n e instanceof Error ? (e as StorefrontHookError) : new Error(String(e));\n\n/**\n * Reads `fetcher` whenever `key` changes (null = nothing to read). Each\n * read has its own AbortSignal, aborted when the key changes or the\n * component unmounts, so a stale answer never replaces a newer one.\n * Internal.\n */\nexport function useResource<T>(\n key: string | null,\n deps: unknown,\n fetcher: (signal: AbortSignal) => Promise<T>,\n): ResourceResult<T> {\n const [state, setState] = useState<State<T>>({\n key: null,\n data: null,\n error: null,\n isLoading: key !== null,\n });\n const [nonce, setNonce] = useState(0);\n const fetcherRef = useRef(fetcher);\n useEffect(() => {\n fetcherRef.current = fetcher;\n });\n\n useEffect(() => {\n if (key === null) {\n setState({ key, data: null, error: null, isLoading: false });\n return;\n }\n const controller = new AbortController();\n setState((s) =>\n s.key === key\n ? { ...s, isLoading: true }\n : { key, data: null, error: null, isLoading: true },\n );\n fetcherRef.current(controller.signal).then(\n (data) => {\n if (!controller.signal.aborted)\n setState({ key, data, error: null, isLoading: false });\n },\n (e: unknown) => {\n if (!controller.signal.aborted)\n setState({ key, data: null, error: toError(e), isLoading: false });\n },\n );\n return () => controller.abort();\n }, [key, deps, nonce]);\n\n const refetch = useCallback(() => setNonce((n) => n + 1), []);\n // Until the effect runs for a new key, do not show the old key's data.\n if (state.key !== key) {\n return { data: null, error: null, isLoading: key !== null, refetch };\n }\n return {\n data: state.data,\n error: state.error,\n isLoading: state.isLoading,\n refetch,\n };\n}\n","import type {\n CategoryList,\n Product,\n ProductListQuery,\n ProductPage,\n Store,\n} from '@konfiqo/storefront-sdk';\nimport { useStorefrontContext } from './provider';\nimport { useResource, type ResourceResult } from './use-resource';\n\n/** The store (`store.get()`): name, currency, theme, legal texts, checkout challenge. */\nexport function useStore(): ResourceResult<Store> {\n const { client } = useStorefrontContext();\n return useResource('store', client, (signal) => client.store.get({ signal }));\n}\n\n/** The active category tree (`categories.list()`). */\nexport function useCategories(): ResourceResult<CategoryList> {\n const { client } = useStorefrontContext();\n return useResource('categories', client, (signal) =>\n client.categories.list({ signal }),\n );\n}\n\n/**\n * A page of products (`products.list(params)`). Reads again when a\n * parameter changes, cancelling the previous read.\n */\nexport function useProducts(\n params: ProductListQuery = {},\n): ResourceResult<ProductPage> {\n const { client } = useStorefrontContext();\n const query: ProductListQuery = {\n category: params.category,\n q: params.q,\n page: params.page,\n pageSize: params.pageSize,\n };\n return useResource(JSON.stringify(query), client, (signal) =>\n client.products.list(query, { signal }),\n );\n}\n\n/**\n * One product by slug (`products.get(slug)`); an unknown slug is the\n * error `product_not_found`. A null / empty slug reads nothing.\n */\nexport function useProduct(\n slug: string | null | undefined,\n): ResourceResult<Product> {\n const { client } = useStorefrontContext();\n return useResource(slug ? `product:${slug}` : null, client, (signal) =>\n client.products.get(slug!, { signal }),\n );\n}\n","import { useEffect, useMemo, useSyncExternalStore } from 'react';\nimport type {\n AddLineInput,\n AddressInput,\n Cart,\n CartIdStorage,\n CustomerInput,\n RequestOptions,\n ShippingOptionList,\n UpdateLineInput,\n} from '@konfiqo/storefront-sdk';\nimport type { CartSnapshot } from './cart-store';\nimport { useStorefrontContext } from './provider';\n\n/** What {@link useCart} returns. */\nexport interface UseCartResult extends CartSnapshot {\n /** Total units in the cart (for a badge). */\n itemCount: number;\n /** Adds units of a variant. Creates the cart on the first write. */\n addLine(input: AddLineInput): Promise<Cart>;\n /** Sets a line's quantity (`lineId` is `CartLine.id`). */\n updateLine(lineId: string, input: UpdateLineInput): Promise<Cart>;\n /** Removes a line. */\n removeLine(lineId: string): Promise<Cart>;\n /** Sets the buyer. */\n setCustomer(input: CustomerInput): Promise<Cart>;\n /** Sets the shipping (and billing) address. */\n setAddress(input: AddressInput): Promise<Cart>;\n /** Selects a shipping option. */\n setShippingOption(optionId: string): Promise<Cart>;\n /** The shipping options of the cart (`{ items: [] }` without a cart). */\n shippingOptions(options?: RequestOptions): Promise<ShippingOptionList>;\n /** Reads the cart again (a cart whose payment failed comes back `open`). */\n refresh(): Promise<void>;\n /** Forgets the cart (e.g. after its order is paid); the next write starts a new one. */\n reset(): void;\n}\n\nconst SERVER_CART: CartSnapshot = {\n cart: null,\n status: 'idle',\n isUpdating: false,\n error: null,\n previousCartId: null,\n};\n\n/**\n * The buyer's cart, shared by every component under the provider.\n *\n * The saved cart id is read on mount (after hydration: nothing is read\n * during render). No cart is created until the first write. Every write\n * replaces the state with the server's cart view — prices are never\n * computed locally. Writes reject with a {@link StorefrontHookError} (and\n * also set `error`); a cart that expired or is unknown is forgotten, and\n * the next write starts a new one.\n */\nexport function useCart(): UseCartResult {\n const { cart: store } = useStorefrontContext();\n const snapshot = useSyncExternalStore(\n store.subscribe,\n store.getCart,\n () => SERVER_CART,\n );\n useEffect(() => {\n void store.load();\n }, [store]);\n const itemCount =\n snapshot.cart?.lines.reduce((n, line) => n + line.quantity, 0) ?? 0;\n return {\n ...snapshot,\n itemCount,\n addLine: store.addLine,\n updateLine: store.updateLine,\n removeLine: store.removeLine,\n setCustomer: store.setCustomer,\n setAddress: store.setAddress,\n setShippingOption: store.setShippingOption,\n shippingOptions: store.shippingOptions,\n refresh: store.refresh,\n reset: store.reset,\n };\n}\n\n/**\n * Where this provider keeps the cart id, as a getter (read it inside an\n * effect or handler, never during render: it is null on a server). Lets a\n * page that learns a cart id out of band (e.g. cart recovery) save it\n * where the cart reads it, with `saveCartId(getStorage(), storeId, id)`.\n */\nexport function useCartStorage(): () => CartIdStorage | null {\n const { cart } = useStorefrontContext();\n return useMemo(() => () => cart.currentStorage(), [cart]);\n}\n","import { useCallback, useEffect, useRef, useState } from 'react';\nimport { isStorefrontError, type Account } from '@konfiqo/storefront-sdk';\nimport type { StorefrontHookError } from './cart-store';\nimport { useStorefrontContext } from './provider';\n\n/** What {@link useAccount} returns. */\nexport interface UseAccountResult {\n /** The signed-in buyer's account, or null. */\n account: Account | null;\n /** `loading` until the first read answers; `signedOut` on a 401. */\n status: 'loading' | 'signedOut' | 'signedIn';\n /**\n * The last read's error when it was not a 401 (e.g. network, timeout),\n * else null. The status is `signedOut` then, unless an earlier read\n * succeeded (the account is kept).\n */\n error: StorefrontHookError | null;\n /** Reads the account again (call after sign-in, sign-out or a save). */\n refresh(): Promise<void>;\n}\n\ninterface State {\n account: Account | null;\n status: UseAccountResult['status'];\n error: StorefrontHookError | null;\n}\n\n/**\n * The buyer's account (`client.account.get()`), read after mount. A 401\n * (no or an ended session) means `signedOut`. Sign in / out and saves go\n * through `useStorefrontClient().account`; call `refresh()` afterwards.\n */\nexport function useAccount(): UseAccountResult {\n const { client } = useStorefrontContext();\n const [state, setState] = useState<State>({\n account: null,\n status: 'loading',\n error: null,\n });\n const seq = useRef(0);\n const alive = useRef(true);\n\n const refresh = useCallback(async () => {\n const mine = ++seq.current;\n try {\n const account = await client.account.get();\n if (!alive.current || mine !== seq.current) return;\n setState({ account, status: 'signedIn', error: null });\n } catch (e) {\n if (!alive.current || mine !== seq.current) return;\n if (isStorefrontError(e) && e.status === 401) {\n setState({ account: null, status: 'signedOut', error: null });\n return;\n }\n const error =\n e instanceof Error ? (e as StorefrontHookError) : new Error(String(e));\n setState((s) => ({\n account: s.account,\n status: s.account ? 'signedIn' : 'signedOut',\n error,\n }));\n }\n }, [client]);\n\n useEffect(() => {\n alive.current = true;\n void refresh();\n return () => {\n alive.current = false;\n };\n }, [refresh]);\n\n return { ...state, refresh };\n}\n","import { useCallback, useEffect, useSyncExternalStore } from 'react';\nimport type { CheckoutResult } from '@konfiqo/storefront-sdk';\nimport type { CheckoutSnapshot } from './cart-store';\nimport { useOptionalStorefrontContext, useStorefrontContext } from './provider';\n\n/** Options of `checkout()`. */\nexport interface CheckoutCallOptions {\n /**\n * The checkout challenge token (from `<CheckoutChallenge>`), required\n * when `store.checkoutChallenge` is set. Single-use.\n */\n turnstileToken?: string | null;\n}\n\n/** What {@link useCheckout} returns. */\nexport interface UseCheckoutResult extends CheckoutSnapshot {\n /**\n * Checks the cart out: `carts.checkout(cartId, { turnstileToken })`.\n * Resolves with the result (present it with `<PaymentForm>`; keep its\n * `token`, returned only once) or rejects with the error (also in\n * `error`). A call while one is in flight returns the same promise.\n */\n checkout(options?: CheckoutCallOptions): Promise<CheckoutResult>;\n /** Clears `result` and `error`. */\n reset(): void;\n}\n\nconst SERVER_CHECKOUT: CheckoutSnapshot = {\n isPending: false,\n result: null,\n error: null,\n attempts: 0,\n};\n\n/**\n * Checkout for the provider's cart. The state is shared under the\n * provider, and a checkout is **never aborted** — not even when the\n * component unmounts — because the server may place the order anyway.\n * When a component using this hook mounts after a checkout was started,\n * the cart is read again so it shows what the server has.\n *\n * Errors are {@link StorefrontError}s: switch on `error.code`. For\n * `cart_changed`, `error.details` has the new `lines`, totals and\n * `shippingOptions` (the cart is also read again): show them and let the\n * buyer confirm before calling `checkout()` again — never retry silently.\n */\nexport function useCheckout(): UseCheckoutResult {\n const { cart: store } = useStorefrontContext();\n const snapshot = useSyncExternalStore(\n store.subscribe,\n store.getCheckout,\n () => SERVER_CHECKOUT,\n );\n useEffect(() => {\n if (store.checkoutStarted) void store.refresh();\n }, [store]);\n const checkout = useCallback(\n (options: CheckoutCallOptions = {}) =>\n store.checkout({ turnstileToken: options.turnstileToken ?? undefined }),\n [store],\n );\n return { ...snapshot, checkout, reset: store.clearCheckout };\n}\n\n/** Settled checkout attempts under the provider (0 outside one). Internal. */\nexport function useCheckoutAttempts(): number {\n const ctx = useOptionalStorefrontContext();\n const store = ctx?.cart;\n return useSyncExternalStore(\n store?.subscribe ?? noopSubscribe,\n () => store?.getCheckout().attempts ?? 0,\n () => 0,\n );\n}\n\nconst noopSubscribe = () => () => {};\n","import { useCallback, useEffect, useState } from 'react';\nimport { isStorefrontError, type Order } from '@konfiqo/storefront-sdk';\nimport type { StorefrontHookError } from './cart-store';\nimport { useStorefrontContext } from './provider';\n\n/** First poll delay, milliseconds. */\nexport const ORDER_POLL_MIN_MS = 2_000;\n/** Longest poll delay, milliseconds. */\nexport const ORDER_POLL_MAX_MS = 15_000;\n\n/** The delay before poll number `attempt` (0-based): 2 s, 4 s, 8 s, then 15 s. */\nexport function orderPollDelay(attempt: number): number {\n return Math.min(ORDER_POLL_MIN_MS * 2 ** attempt, ORDER_POLL_MAX_MS);\n}\n\n/**\n * Whether an order no longer changes on its own soon: anything past\n * `pendingPayment` (`paid`, `fulfilling`, `shipped`, `delivered`,\n * `cancelled`, `refunded`, …), or a pending order whose payment `failed`\n * / `expired` (the buyer has to check out again).\n */\nexport function isOrderSettled(order: Order): boolean {\n if (order.status !== 'pendingPayment') return true;\n return order.paymentStatus === 'failed' || order.paymentStatus === 'expired';\n}\n\n/** Errors worth polling through (the service may answer next time). */\nfunction isTransient(e: unknown): boolean {\n if (!isStorefrontError(e)) return false;\n switch (e.code) {\n case 'network_error':\n case 'timeout':\n case 'rate_limited':\n case 'order_unavailable':\n case 'http_error':\n return true;\n default:\n return false;\n }\n}\n\n/** Options of {@link useOrder}. */\nexport interface UseOrderOptions {\n /**\n * Keep reading until the order is settled ({@link isOrderSettled}),\n * backing off 2 s → 4 s → 8 s → 15 s (then every 15 s). Transient\n * errors (network, timeout, throttling, `order_unavailable`) keep\n * polling; others stop it.\n */\n pollUntilFinal?: boolean;\n}\n\n/** What {@link useOrder} returns. */\nexport interface UseOrderResult {\n /** The order, or null before it arrives. Kept through a failed poll. */\n order: Order | null;\n /** The last read's error, or null. */\n error: StorefrontHookError | null;\n /** The first read is in progress. */\n isLoading: boolean;\n /** Another read is scheduled. */\n isPolling: boolean;\n /** Reads again now (and restarts polling). */\n refetch: () => void;\n}\n\ninterface State {\n key: string | null;\n order: Order | null;\n error: StorefrontHookError | null;\n isPolling: boolean;\n}\n\n/**\n * The buyer's order (`orders.get(orderId, token)`), e.g. on the page the\n * payment provider returns to (`/orders/{orderId}?token=`). The token is\n * the buyer's only key to the order: this hook never logs it or puts it\n * anywhere but the request; do not send it to analytics either.\n */\nexport function useOrder(\n orderId: string | null | undefined,\n token: string | null | undefined,\n options: UseOrderOptions = {},\n): UseOrderResult {\n const { client } = useStorefrontContext();\n const poll = options.pollUntilFinal ?? false;\n const key = orderId && token ? `${orderId} ${token}` : null;\n const [state, setState] = useState<State>({\n key: null,\n order: null,\n error: null,\n isPolling: false,\n });\n const [nonce, setNonce] = useState(0);\n\n useEffect(() => {\n if (!orderId || !token) {\n setState({ key: null, order: null, error: null, isPolling: false });\n return;\n }\n const k = `${orderId} ${token}`;\n const controller = new AbortController();\n let timer: ReturnType<typeof setTimeout> | undefined;\n let attempt = 0;\n const schedule = (atLeastMs: number) => {\n const delay = Math.max(orderPollDelay(attempt++), atLeastMs);\n setState((s) => ({ ...s, isPolling: true }));\n timer = setTimeout(tick, delay);\n };\n const tick = async () => {\n try {\n const order = await client.orders.get(orderId, token, {\n signal: controller.signal,\n });\n if (controller.signal.aborted) return;\n setState({ key: k, order, error: null, isPolling: false });\n if (poll && !isOrderSettled(order)) schedule(0);\n } catch (e) {\n if (controller.signal.aborted) return;\n const error =\n e instanceof Error\n ? (e as StorefrontHookError)\n : new Error(String(e));\n setState((s) => ({\n key: k,\n order: s.key === k ? s.order : null,\n error,\n isPolling: false,\n }));\n if (poll && isTransient(e)) {\n const retryAfter =\n isStorefrontError(e) && e.code === 'rate_limited'\n ? (e.details.retryAfter ?? 0) * 1000\n : 0;\n schedule(retryAfter);\n }\n }\n };\n void tick();\n return () => {\n controller.abort();\n clearTimeout(timer);\n };\n }, [client, orderId, token, poll, nonce]);\n\n const refetch = useCallback(() => setNonce((n) => n + 1), []);\n if (state.key !== key) {\n return {\n order: null,\n error: null,\n isLoading: key !== null,\n isPolling: false,\n refetch,\n };\n }\n return {\n order: state.order,\n error: state.error,\n isLoading: false,\n isPolling: state.isPolling,\n refetch,\n };\n}\n","import { useEffect, useRef, type HTMLAttributes } from 'react';\nimport {\n mountPayment,\n type CheckoutResult,\n type ClosedCheckoutPage,\n type PaymentPresentation,\n} from '@konfiqo/storefront-sdk';\n\n/** Props of {@link PaymentForm}. */\nexport interface PaymentFormProps extends Omit<\n HTMLAttributes<HTMLDivElement>,\n 'children' | 'onError'\n> {\n /**\n * The **unmodified** result of `checkout()` (or its presentation part).\n * Never build it from user input, URL parameters or storage: embedded\n * content runs as script.\n */\n presentation: PaymentPresentation | CheckoutResult;\n /**\n * Payment cannot be (re)opened (`presentation: \"closed\"`): show the\n * order status page for `page` (`paid`, `cancelled`, `processing`, …).\n */\n onClosed?: (page: ClosedCheckoutPage) => void;\n /** The embed is of a kind this SDK cannot render: show a fallback. */\n onUnsupported?: (embedKind: string) => void;\n /** Presenting failed (e.g. a redirect URL that is not http(s)). */\n onError?: (error: Error) => void;\n}\n\ninterface Pending {\n timer: ReturnType<typeof setTimeout>;\n content: string | null;\n unmount: () => void;\n}\n\nconst embeddedContent = (p: PaymentPresentation | CheckoutResult) =>\n p.presentation === 'embedded' && typeof p.embed.content === 'string'\n ? p.embed.content\n : null;\n\n/**\n * Presents payment with the SDK's `mountPayment`: renders the provider's\n * embedded form inside a `<div>` (its scripts run once), sends the browser\n * to a `redirect` URL, or calls `onClosed`. The form is removed on\n * unmount. Card data never passes through your code. Unstyled: pass\n * `className` / `style` for the wrapper.\n */\nexport function PaymentForm({\n presentation,\n onClosed,\n onUnsupported,\n onError,\n ...divProps\n}: PaymentFormProps) {\n const ref = useRef<HTMLDivElement>(null);\n const callbacks = useRef({ onClosed, onUnsupported, onError });\n useEffect(() => {\n callbacks.current = { onClosed, onUnsupported, onError };\n });\n const pending = useRef<Pending | null>(null);\n const navigated = useRef<unknown>(null);\n\n useEffect(() => {\n const element = ref.current;\n if (!element) return;\n // A removal deferred by the previous cleanup: skip it when the same\n // form is mounted again (React Strict Mode re-runs effects), so the\n // provider's scripts are not injected twice.\n const prev = pending.current;\n pending.current = null;\n if (prev) {\n clearTimeout(prev.timer);\n if (\n prev.content === null ||\n prev.content !== embeddedContent(presentation)\n )\n prev.unmount();\n }\n // A redirect / closed result is acted on once, even if the effect\n // re-runs (Strict Mode): one navigation, one `onClosed`.\n if (presentation.presentation !== 'embedded') {\n if (navigated.current === presentation) return;\n navigated.current = presentation;\n }\n\n let unmount: (() => void) | null = null;\n try {\n const mount = mountPayment(element, presentation, {\n onClosed: (page) => callbacks.current.onClosed?.(page),\n });\n if (mount.kind === 'embedded') unmount = mount.unmount;\n else if (mount.kind === 'unsupported')\n callbacks.current.onUnsupported?.(mount.embedKind);\n } catch (e) {\n callbacks.current.onError?.(\n e instanceof Error ? e : new Error(String(e)),\n );\n }\n if (!unmount) return;\n const remove = unmount;\n return () => {\n const entry: Pending = {\n content: embeddedContent(presentation),\n unmount: remove,\n timer: setTimeout(() => {\n if (pending.current === entry) pending.current = null;\n remove();\n }, 0),\n };\n pending.current = entry;\n };\n }, [presentation]);\n\n return <div {...divProps} ref={ref} />;\n}\n","import {\n forwardRef,\n useEffect,\n useImperativeHandle,\n useRef,\n type HTMLAttributes,\n} from 'react';\nimport { renderTurnstile, type TurnstileWidget } from '@konfiqo/storefront-sdk';\nimport { useCheckoutAttempts } from './use-checkout';\n\n/** Props of {@link CheckoutChallenge}. */\nexport interface CheckoutChallengeProps extends Omit<\n HTMLAttributes<HTMLDivElement>,\n 'children' | 'onError'\n> {\n /**\n * The store's Turnstile site key (`store.checkoutChallenge?.siteKey`).\n * Null / empty renders an empty `<div>` (the store has no challenge).\n */\n siteKey: string | null | undefined;\n /** A token is ready: pass it to `checkout({ turnstileToken })`. */\n onToken: (token: string) => void;\n /**\n * The current token can no longer be used — it expired, or a checkout\n * consumed it and the widget was reset. Drop it; a new one follows.\n */\n onExpired?: () => void;\n /** The widget failed to load or render. */\n onError?: (error: Error | string | undefined) => void;\n}\n\n/** Imperative handle of {@link CheckoutChallenge} (via `ref`). */\nexport interface CheckoutChallengeHandle {\n /** Gets a new token (the current one is dropped: `onExpired` is called). */\n reset(): void;\n}\n\n/**\n * Renders the store's checkout challenge (Cloudflare Turnstile) with the\n * SDK's `renderTurnstile`. Tokens are single-use: under a\n * `StorefrontProvider` the widget resets itself after every checkout\n * attempt of `useCheckout()`; call `ref.current.reset()` to reset it\n * yourself. The widget is removed on unmount.\n */\nexport const CheckoutChallenge = forwardRef<\n CheckoutChallengeHandle,\n CheckoutChallengeProps\n>(function CheckoutChallenge(\n { siteKey, onToken, onExpired, onError, ...divProps },\n handle,\n) {\n const ref = useRef<HTMLDivElement>(null);\n const widget = useRef<TurnstileWidget | null>(null);\n const callbacks = useRef({ onToken, onExpired, onError });\n useEffect(() => {\n callbacks.current = { onToken, onExpired, onError };\n });\n\n useEffect(() => {\n const element = ref.current;\n if (!element || !siteKey) return;\n let active = true;\n let rendered: TurnstileWidget | null = null;\n renderTurnstile(element, siteKey, {\n onToken: (t) => callbacks.current.onToken(t),\n onExpired: () => callbacks.current.onExpired?.(),\n onError: (code) => callbacks.current.onError?.(code),\n }).then(\n (w) => {\n if (!active) {\n w.remove();\n return;\n }\n rendered = w;\n widget.current = w;\n },\n (e: unknown) => {\n if (active)\n callbacks.current.onError?.(\n e instanceof Error ? e : new Error(String(e)),\n );\n },\n );\n return () => {\n active = false;\n if (rendered) {\n rendered.remove();\n if (widget.current === rendered) widget.current = null;\n }\n };\n }, [siteKey]);\n\n const reset = () => {\n if (!widget.current) return;\n callbacks.current.onExpired?.();\n widget.current.reset();\n };\n useImperativeHandle(handle, () => ({ reset }), []);\n\n // Tokens are single-use: every settled checkout consumed (or rejected)\n // the current one.\n const attempts = useCheckoutAttempts();\n const seen = useRef(attempts);\n useEffect(() => {\n if (attempts === seen.current) return;\n seen.current = attempts;\n reset();\n });\n\n return <div {...divProps} ref={ref} />;\n});\n","import Markdoc from '@markdoc/markdoc';\nimport * as React from 'react';\nimport { useEffect } from 'react';\nimport type { ComponentType, ReactNode } from 'react';\nimport { formatMoney, type ContentNode } from '@konfiqo/storefront-sdk';\nimport { useProduct, useProducts } from './catalog';\nimport { useStorefrontContext } from './provider';\nimport { useResource } from './use-resource';\n\n/** Components by tag name (`ProductGrid`, `Button`, …), e.g. to replace a default. */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type ContentComponents = Record<string, ComponentType<any>>;\n\n// ---------------------------------------------------------------- safety\n\n/** Plain tags content may use. Everything else is dropped with its children. */\nconst HTML_TAGS = new Set(\n (\n 'article section div span p h1 h2 h3 h4 h5 h6 ul ol li strong em s del ' +\n 'code pre blockquote hr br a table thead tbody tr th td figure figcaption ' +\n 'small sub sup mark'\n ).split(' '),\n);\n/** The attributes a plain tag keeps (`href` only on `a`, and only if safe). */\nconst HTML_ATTRS = new Set([\n 'class',\n 'title',\n 'align',\n 'colspan',\n 'rowspan',\n 'start',\n]);\nconst MAX_DEPTH = 40;\nconst MAX_NODES = 5000;\n\nconst hasControl = (s: string): boolean =>\n Array.from(s).some((c) => {\n const n = c.charCodeAt(0);\n return n < 0x20 || n === 0x7f;\n });\n\n/** A link target a page may follow: relative, http(s), mailto or tel. */\nfunction safeHref(v: unknown): string | null {\n if (typeof v !== 'string') return null;\n const href = v.trim();\n // No whitespace or control characters inside (`java\\nscript:` tricks).\n if (href === '' || /\\s/.test(href) || hasControl(href)) return null;\n // Browsers read `\\` like `/`: `/\\host` is protocol-relative. Refuse any\n // backslash, also percent-encoded.\n if (href.includes('\\\\') || /%5c/i.test(href)) return null;\n if (href.startsWith('#')) return href;\n if (href.startsWith('/')) return href[1] === '/' ? null : href;\n return /^(https?:|mailto:|tel:)/i.test(href) ? href : null;\n}\n\ntype Prop = string | number | boolean;\nconst isProp = (v: unknown): v is Prop =>\n typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean';\n\ninterface Walk {\n nodes: number;\n components: ContentComponents;\n}\n\nfunction clean(node: unknown, w: Walk, depth: number): ContentNode | null {\n if (typeof node === 'string') return node;\n if (node === null || typeof node !== 'object') return null;\n const n = node as Partial<Exclude<ContentNode, string>>;\n if (\n n.$$mdtype !== 'Tag' ||\n typeof n.name !== 'string' ||\n depth > MAX_DEPTH ||\n ++w.nodes > MAX_NODES\n ) {\n return null;\n }\n const name = n.name;\n const raw =\n n.attributes && typeof n.attributes === 'object' ? n.attributes : {};\n const attributes: Record<string, Prop> = {};\n if (name === '') return null;\n const isHtml = name[0] === name[0]!.toLowerCase();\n if (isHtml) {\n if (!HTML_TAGS.has(name)) return null;\n for (const [k, v] of Object.entries(raw)) {\n if (name === 'a' && k === 'href') {\n const href = safeHref(v);\n if (href !== null) attributes.href = href;\n } else if (HTML_ATTRS.has(k) && isProp(v)) {\n attributes[k] = v;\n }\n }\n } else {\n if (!Object.hasOwn(w.components, name)) return null;\n for (const [k, v] of Object.entries(raw)) {\n if (!isProp(v)) continue;\n if (k === 'ref' || k === 'children' || /^on/i.test(k)) continue;\n if (k === 'dangerouslySetInnerHTML') continue;\n // `key` would be swallowed by React as the element key.\n if (k === 'key') attributes.contentKey = v;\n else attributes[k] = v;\n }\n }\n const children: ContentNode[] = [];\n for (const c of Array.isArray(n.children) ? n.children : []) {\n const cleaned = clean(c, w, depth + 1);\n if (cleaned !== null) children.push(cleaned);\n }\n return { $$mdtype: 'Tag', name, attributes, children };\n}\n\n// ------------------------------------------------------ default components\n\nconst text = (v: unknown): string | undefined =>\n typeof v === 'string' && v !== '' ? v : undefined;\nconst slugOf = (v: unknown): string | null => {\n const s = text(v);\n return s && !/[/\\\\?#]/.test(s) && s !== '.' && s !== '..' ? s : null;\n};\n\nfunction ProductCard({\n product,\n}: {\n product: import('@konfiqo/storefront-sdk').Product;\n}) {\n const { client } = useStorefrontContext();\n const variant = product.variants[0];\n let price: string | null = null;\n try {\n price = variant ? formatMoney(variant.priceMinor, variant.currency) : null;\n } catch {\n price = null;\n }\n let image: string | null = null;\n try {\n image = product.image ? client.media.url(product.image) : null;\n } catch {\n image = null;\n }\n return (\n <a href={`/p/${encodeURIComponent(product.slug)}`}>\n {image ? <img src={image} alt=\"\" /> : null}\n <span>{product.name}</span>\n {price ? <span> {price}</span> : null}\n </a>\n );\n}\n\nfunction ProductGrid(props: { category?: unknown; limit?: unknown }) {\n const category = text(props.category);\n const limit = Number(props.limit);\n const cap = Number.isInteger(limit) && limit > 0 ? Math.min(limit, 48) : 12;\n const { data } = useProducts({ category, pageSize: cap });\n if (!data) return null;\n return (\n <ul className=\"content-product-grid\">\n {data.items.slice(0, cap).map((p) => (\n <li key={p.id}>\n <ProductCard product={p} />\n </li>\n ))}\n </ul>\n );\n}\n\nfunction ProductTag(props: { slug?: unknown }) {\n const { data } = useProduct(slugOf(props.slug));\n return data ? <ProductCard product={data} /> : null;\n}\n\nfunction CategoryLink(props: { slug?: unknown; children?: ReactNode }) {\n const slug = slugOf(props.slug);\n if (!slug) return null;\n return (\n <a href={`/c/${encodeURIComponent(slug)}`}>{props.children ?? slug}</a>\n );\n}\n\nfunction ImageTag(props: { contentKey?: unknown; alt?: unknown }) {\n const { client } = useStorefrontContext();\n const key = text(props.contentKey);\n if (!key) return null;\n let src: string;\n try {\n // Always through the media path, never a URL taken from the content.\n src = client.media.url(key);\n } catch {\n return null;\n }\n return <img src={src} alt={text(props.alt) ?? ''} />;\n}\n\nfunction ButtonTag(props: { href?: unknown; label?: unknown }) {\n const href = safeHref(props.href);\n const label = text(props.label);\n if (!href || !label) return null;\n return (\n <a className=\"button\" href={href}>\n {label}\n </a>\n );\n}\n\nconst DEFAULT_COMPONENTS: ContentComponents = {\n ProductGrid,\n Product: ProductTag,\n CategoryLink,\n Image: ImageTag,\n Button: ButtonTag,\n};\n\n// ------------------------------------------------------------------ render\n\n/**\n * Renders a store-content tree (`StoreContent.tree`) with React. Only\n * plain text tags and the known components are rendered (raw images,\n * unknown tags, ids, styles and event handlers are dropped); output goes\n * through `Markdoc.renderers.react`, never as HTML. The default components\n * (`ProductGrid`, `Product`, `CategoryLink`, `Image`, `Button`) need a\n * `<StorefrontProvider>`; `components` replaces or adds components. A\n * component gets an `Image` / custom tag's `key` attribute as `contentKey`.\n */\nexport function renderContent(\n tree: ContentNode,\n components: ContentComponents = {},\n): ReactNode {\n try {\n const merged = { ...DEFAULT_COMPONENTS, ...components };\n const cleaned = clean(tree, { nodes: 0, components: merged }, 0);\n if (cleaned === null) return null;\n return Markdoc.renderers.react(\n cleaned as unknown as Parameters<typeof Markdoc.renderers.react>[0],\n React,\n { components: merged },\n );\n } catch {\n return null;\n }\n}\n\n/** Props of {@link Content}. */\nexport interface ContentProps {\n /** The content key (`home.hero`, `about-us`, …). */\n contentKey: string;\n /** Components by tag name, replacing or adding to the defaults. */\n components?: ContentComponents;\n}\n\n/**\n * A piece of store content (Markdoc written in the console), read by key\n * from the store. Renders nothing while loading, or when the key does not\n * exist or cannot be read (a warning in development only).\n */\nexport function Content({ contentKey, components }: ContentProps): ReactNode {\n const { client } = useStorefrontContext();\n const { data, error } = useResource(\n `content:${contentKey}`,\n client,\n (signal) => client.getContent(contentKey, { signal }),\n );\n useEffect(() => {\n if (\n error &&\n typeof process !== 'undefined' &&\n process.env?.NODE_ENV !== 'production'\n ) {\n console.warn(\n `<Content contentKey=\"${contentKey}\">: ${error.message || 'could not be read'}`,\n );\n }\n }, [error, contentKey]);\n if (!data) return null;\n return <>{renderContent(data.tree, components)}</>;\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;;;ACAA,mBAOO;AACP,IAAAA,yBAKO;;;ACbP,4BAgBO;AA2CP,SAAS,mBAAmB,GAAqB;AAC/C,aACE,yCAAkB,CAAC,KACnB,EAAE,SAAS,oBACX,EAAE,QAAQ,WAAW;AAEzB;AAGO,SAAS,gBAAgB,GAAqB;AACnD,MAAI,KAAC,yCAAkB,CAAC,EAAG,QAAO;AAClC,MAAI,EAAE,SAAS,iBAAkB,QAAO;AACxC,SAAO,EAAE,SAAS,oBAAoB,EAAE,QAAQ,WAAW;AAC7D;AAEA,IAAM,UAAU,CAAC,MACf,aAAa,QAAS,IAA4B,IAAI,MAAM,OAAO,CAAC,CAAC;AAOhE,IAAM,YAAN,MAAgB;AAAA;AAAA;AAAA;AAAA;AAAA,EAuCrB,YACmB,WACA,SACA,SACjB;AAHiB;AACA;AACA;AAAA,EAChB;AAAA,EAHgB;AAAA,EACA;AAAA,EACA;AAAA,EAzCX,YAA0B;AAAA,IAChC,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,YAAY;AAAA,IACZ,OAAO;AAAA,IACP,gBAAgB;AAAA,EAClB;AAAA,EACQ,gBAAkC;AAAA,IACxC,WAAW;AAAA,IACX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,GAAG,YAAY,OAAO,GAAG,CAAC;AAC/D,QAAI,YAAY,KAAM,QAAO;AAC7B,WAAO,eAAAC,QAAQ,UAAU;AAAA,MACvB;AAAA,MACA;AAAA,MACA,EAAE,YAAY,OAAO;AAAA,IACvB;AAAA,EACF,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAeO,SAAS,QAAQ,EAAE,YAAY,WAAW,GAA4B;AAC3E,QAAM,EAAE,OAAO,IAAI,qBAAqB;AACxC,QAAM,EAAE,MAAM,MAAM,IAAI;AAAA,IACtB,WAAW,UAAU;AAAA,IACrB;AAAA,IACA,CAAC,WAAW,OAAO,WAAW,YAAY,EAAE,OAAO,CAAC;AAAA,EACtD;AACA,+BAAU,MAAM;AACd,QACE,SACA,OAAO,YAAY,eACnB,QAAQ,KAAK,aAAa,cAC1B;AACA,cAAQ;AAAA,QACN,wBAAwB,UAAU,OAAO,MAAM,WAAW,mBAAmB;AAAA,MAC/E;AAAA,IACF;AAAA,EACF,GAAG,CAAC,OAAO,UAAU,CAAC;AACtB,MAAI,CAAC,KAAM,QAAO;AAClB,SAAO,6EAAG,wBAAc,KAAK,MAAM,UAAU,GAAE;AACjD;","names":["import_storefront_sdk","import_react","toError","import_react","import_react","import_storefront_sdk","import_react","import_react","import_storefront_sdk","import_react","import_storefront_sdk","import_jsx_runtime","import_react","import_storefront_sdk","import_jsx_runtime","CheckoutChallenge","import_react","import_storefront_sdk","import_jsx_runtime","Markdoc"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/provider.tsx","../src/cart-store.ts","../src/use-resource.ts","../src/catalog.ts","../src/use-cart.ts","../src/use-account.ts","../src/use-checkout.ts","../src/use-order.ts","../src/payment-form.tsx","../src/checkout-challenge.tsx","../src/content.tsx","../src/consent-provider.tsx","../src/consent.ts","../src/analytics.ts","../src/analytics-tracker.tsx","../src/ad-pixels.ts","../src/ad-pixels-loader.tsx"],"sourcesContent":["'use client';\n\n// Every export is a hook or a client component (React Server Components /\n// Next.js App Router). esbuild keeps this entry directive in the build.\nexport { StorefrontProvider, useStorefrontClient } from './provider';\nexport type { ClientConfig, StorefrontProviderProps } from './provider';\nexport { useStore, useCategories, useProducts, useProduct } from './catalog';\nexport type { ResourceResult } from './use-resource';\nexport { useCart, useCartStorage } from './use-cart';\nexport type { UseCartResult } from './use-cart';\nexport { isDeadCartError, defaultCartStorage } from './cart-store';\nexport type {\n CartSnapshot,\n CheckoutSnapshot,\n StorefrontHookError,\n} from './cart-store';\nexport { useAccount } from './use-account';\nexport type { UseAccountResult } from './use-account';\nexport { useCheckout } from './use-checkout';\nexport type { CheckoutCallOptions, UseCheckoutResult } from './use-checkout';\nexport {\n useOrder,\n isOrderSettled,\n orderPollDelay,\n ORDER_POLL_MIN_MS,\n ORDER_POLL_MAX_MS,\n} from './use-order';\nexport type { UseOrderOptions, UseOrderResult } from './use-order';\nexport { PaymentForm } from './payment-form';\nexport type { PaymentFormProps } from './payment-form';\nexport { CheckoutChallenge } from './checkout-challenge';\nexport type {\n CheckoutChallengeHandle,\n CheckoutChallengeProps,\n} from './checkout-challenge';\nexport { Content, renderContent } from './content';\nexport type { ContentComponents, ContentProps } from './content';\nexport { ConsentProvider, useConsent } from './consent-provider';\nexport type { ConsentProviderProps, ConsentState } from './consent-provider';\nexport { OPTIONAL_CATEGORIES } from './consent';\nexport type {\n ConsentRecord,\n OptionalCookieCategory,\n StoredConsent,\n} from './consent';\nexport {\n configureAnalytics,\n track,\n recordConsent,\n resetAnalytics,\n} from './analytics';\nexport type { AnalyticsEventType, AnalyticsExtra } from './analytics';\nexport { AnalyticsTracker } from './analytics-tracker';\nexport type { AnalyticsTrackerProps } from './analytics-tracker';\nexport {\n configurePixels,\n firePixel,\n onSecretPage,\n resetPixels,\n} from './ad-pixels';\nexport type { PixelEvent } from './ad-pixels';\nexport { AdPixelsLoader } from './ad-pixels-loader';\nexport type { AdPixelsLoaderProps } from './ad-pixels-loader';\n","import {\n createContext,\n useContext,\n useEffect,\n useMemo,\n useRef,\n type ReactNode,\n} from 'react';\nimport {\n createStorefrontClient,\n type CartIdStorage,\n type StorefrontClient,\n type StorefrontClientOptions,\n} from '@konfiqo/storefront-sdk';\nimport { CartStore, defaultCartStorage } from './cart-store';\n\n/** Client options the provider accepts: no secret keys, no buyer IP. */\nexport type ClientConfig = Omit<\n StorefrontClientOptions,\n 'serverKey' | 'trustedStorefrontKey' | 'buyerIp'\n>;\n\n/** Props of {@link StorefrontProvider}. */\nexport interface StorefrontProviderProps {\n /**\n * The store's id: namespaces the persisted cart id, so one origin can\n * serve several stores.\n */\n storeId: string;\n /** A client to use. Give either `client` or `config`. */\n client?: StorefrontClient;\n /**\n * Options to create the client with (when `client` is not given). The\n * secret keys `serverKey` and `trustedStorefrontKey`, and `buyerIp`, are\n * refused: props of a client component are serialized into the page HTML.\n */\n config?: ClientConfig;\n /**\n * Where the cart id is persisted. Default: the first-party `__Host-konfiqo_cart`\n * cookie (shared with a store's own frontend on the same domain) with\n * `window.localStorage` as a fallback, read lazily (never during render, so server rendering is safe). `null`\n * keeps the cart id in memory only (lost on reload).\n */\n cartStorage?: CartIdStorage | null;\n /** The storefront. */\n children?: ReactNode;\n}\n\ninterface StorefrontContextValue {\n client: StorefrontClient;\n storeId: string;\n cart: CartStore;\n}\n\nconst StorefrontContext = createContext<StorefrontContextValue | null>(null);\n\n/**\n * Makes a Storefront client and the buyer's cart available to the hooks\n * below it. Holds the cart state, so every `useCart()` under one provider\n * sees the same cart.\n *\n * @throws Error when neither `client` nor `config` is given, or when\n * `config` holds `serverKey`, `trustedStorefrontKey` or `buyerIp`.\n */\nexport function StorefrontProvider({\n storeId,\n client,\n config,\n cartStorage,\n children,\n}: StorefrontProviderProps) {\n const forbidden = ['serverKey', 'trustedStorefrontKey', 'buyerIp'].filter(\n (k) => config !== undefined && k in config,\n );\n if (forbidden.length > 0) {\n throw new Error(\n `StorefrontProvider: config.${forbidden.join(', config.')} must not be passed to a client component (it would reach the browser). Create a server-side client instead.`,\n );\n }\n const baseUrl = config?.baseUrl;\n const publishableKey = config?.publishableKey;\n const timeoutMs = config?.timeoutMs;\n const customFetch = config?.fetch;\n const resolved = useMemo(() => {\n if (client) return client;\n if (baseUrl === undefined || publishableKey === undefined) {\n throw new Error('StorefrontProvider: pass `client` or `config`');\n }\n return createStorefrontClient({\n baseUrl,\n publishableKey,\n timeoutMs,\n fetch: customFetch,\n });\n }, [client, baseUrl, publishableKey, timeoutMs, customFetch]);\n\n // Read by the cart store per call. Assigned during render (an\n // idempotent write of the latest props) so the store — keyed by\n // `storeId` only — always uses the current client and storage, and the\n // cart state survives a new client (e.g. a new `fetch` identity).\n const clientRef = useRef(resolved);\n clientRef.current = resolved;\n const storageRef = useRef(cartStorage);\n storageRef.current = cartStorage;\n\n const cart = useMemo(\n () =>\n new CartStore(\n () => clientRef.current,\n storeId,\n () =>\n storageRef.current === undefined\n ? defaultCartStorage()\n : storageRef.current,\n ),\n [storeId],\n );\n // Cancels the cart read when the provider goes away. Writes (and\n // checkout) are never aborted: the server may apply them anyway.\n useEffect(() => () => cart.abortReads(), [cart]);\n // Another tab changed this store's cart id: follow it.\n useEffect(() => {\n if (typeof window === 'undefined') return;\n const onStorage = (e: StorageEvent) => {\n const storage = cart.currentStorage();\n if (!storage) return;\n // The default storage names the `localStorage` it writes through.\n const area = (storage as { storageArea?: unknown }).storageArea;\n if (e.storageArea !== (area ?? storage)) return;\n if (e.key !== null && e.key !== cart.storageKey) return;\n cart.syncFromStorage();\n };\n window.addEventListener('storage', onStorage);\n return () => window.removeEventListener('storage', onStorage);\n }, [cart]);\n\n const value = useMemo(\n () => ({ client: resolved, storeId, cart }),\n [resolved, storeId, cart],\n );\n return (\n <StorefrontContext.Provider value={value}>\n {children}\n </StorefrontContext.Provider>\n );\n}\n\n/** The provider's context. Internal. */\nexport function useStorefrontContext(): StorefrontContextValue {\n const ctx = useContext(StorefrontContext);\n if (!ctx) {\n throw new Error(\n 'Storefront hooks must be used inside <StorefrontProvider>',\n );\n }\n return ctx;\n}\n\n/** The provider's context, or null outside a provider. Internal. */\nexport function useOptionalStorefrontContext(): StorefrontContextValue | null {\n return useContext(StorefrontContext);\n}\n\n/**\n * The provider's {@link StorefrontClient}, for calls the hooks do not\n * cover.\n */\nexport function useStorefrontClient(): StorefrontClient {\n return useStorefrontContext().client;\n}\n","import {\n StorefrontError,\n cartIdKey,\n clearCartId,\n cookieCartStorage,\n isStorefrontError,\n loadCartId,\n saveCartId,\n type AddLineInput,\n type AnyStorefrontError,\n type Cart,\n type CartIdStorage,\n type CheckoutResult,\n type RequestOptions,\n type ShippingOptionList,\n type StorefrontClient,\n} from '@konfiqo/storefront-sdk';\n\n/**\n * An error a hook reports: a {@link StorefrontError} (narrow with\n * `isStorefrontError` and switch on `code`), or a plain `Error` for\n * programming mistakes (e.g. an invalid slug).\n */\nexport type StorefrontHookError = AnyStorefrontError | Error;\n\n/** The cart part of the shared state. */\nexport interface CartSnapshot {\n /** The cart, or null when the buyer has none yet (created on the first write). */\n cart: Cart | null;\n /**\n * `idle` before the first read (and during server rendering), `loading`\n * while the saved cart is read, `ready` afterwards.\n */\n status: 'idle' | 'loading' | 'ready';\n /** A write is in progress. */\n isUpdating: boolean;\n /** The last read or write error, cleared by the next success. */\n error: StorefrontHookError | null;\n /**\n * The id of a cart this provider left because it was already `ordered`\n * when the buyer changed it (a write moved to a fresh cart). Lets the\n * app offer \"continue your payment\" for that order. Cleared by `reset()`.\n */\n previousCartId: string | null;\n}\n\n/** The checkout part of the shared state. */\nexport interface CheckoutSnapshot {\n /** A checkout call is in flight. */\n isPending: boolean;\n /** The last checkout's result. Holds the once-only order `token`. */\n result: CheckoutResult | null;\n /** The last checkout's error. */\n error: StorefrontHookError | null;\n /** Settled checkout calls so far (a challenge widget resets on each). */\n attempts: number;\n}\n\n/** Whether a write error means \"this cart is already ordered\". */\nfunction isOrderedCartError(e: unknown): boolean {\n return (\n isStorefrontError(e) &&\n e.code === 'cart_read_only' &&\n e.details.status === 'ordered'\n );\n}\n\n/** Whether a cart error means \"this cart is gone: start a new one\". */\nexport function isDeadCartError(e: unknown): boolean {\n if (!isStorefrontError(e)) return false;\n if (e.code === 'cart_not_found') return true;\n return e.code === 'cart_read_only' && e.details.status === 'expired';\n}\n\nconst toError = (e: unknown): StorefrontHookError =>\n e instanceof Error ? (e as StorefrontHookError) : new Error(String(e));\n\n/**\n * The buyer's cart and checkout state, shared by every hook under one\n * provider. Writes and checkout run one at a time, in call order, and\n * every write replaces the state with the server's cart view. Internal.\n */\nexport class CartStore {\n private cartState: CartSnapshot = {\n cart: null,\n status: 'idle',\n isUpdating: false,\n error: null,\n previousCartId: null,\n };\n private checkoutState: CheckoutSnapshot = {\n isPending: false,\n result: null,\n error: null,\n attempts: 0,\n };\n private readonly listeners = new Set<() => void>();\n private queue: Promise<void> = Promise.resolve();\n private cartId: string | null = null;\n private loadPromise: Promise<void> | null = null;\n private reads = new AbortController();\n private pendingCheckout: Promise<CheckoutResult> | null = null;\n private pendingWrites = 0;\n /**\n * Bumped by `reset()` (and a cart id changed in another tab): a queued\n * operation that started under an older epoch drops its outcome instead\n * of resurrecting (or persisting) the cart it was working on.\n */\n private epoch = 0;\n /**\n * Bumped by `reset()` only. A checkout in flight keeps its outcome (the\n * once-only order token) when another tab merely changes the cart id.\n */\n private resetEpoch = 0;\n /** Whether a checkout was started under this provider. */\n checkoutStarted = false;\n\n /**\n * @param getClient - the provider's current client (read per call, so\n * a new client — e.g. another `fetch` — keeps this cart state)\n */\n constructor(\n private readonly getClient: () => StorefrontClient,\n private readonly storeId: string,\n private readonly storage: () => CartIdStorage | null,\n ) {}\n\n private get client(): StorefrontClient {\n return this.getClient();\n }\n\n // ------------------------------------------------------ subscription\n\n subscribe = (listener: () => void): (() => void) => {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n };\n getCart = (): CartSnapshot => this.cartState;\n getCheckout = (): CheckoutSnapshot => this.checkoutState;\n\n private setCart(patch: Partial<CartSnapshot>): void {\n this.cartState = { ...this.cartState, ...patch };\n this.emit();\n }\n private setCheckout(patch: Partial<CheckoutSnapshot>): void {\n this.checkoutState = { ...this.checkoutState, ...patch };\n this.emit();\n }\n private emit(): void {\n for (const l of this.listeners) l();\n }\n\n /** Runs `fn` after everything queued before it. */\n private enqueue<T>(fn: () => Promise<T>): Promise<T> {\n const run = this.queue.then(fn);\n this.queue = run.then(\n () => undefined,\n () => undefined,\n );\n return run;\n }\n\n private currentId(): string | null {\n return this.cartId ?? loadCartId(this.storage(), this.storeId);\n }\n\n /** Forgets the cart: the next write creates a new one. */\n private forget(): void {\n this.cartId = null;\n clearCartId(this.storage(), this.storeId);\n }\n\n /** Puts a server cart view into the state (an expired cart is forgotten). */\n private apply(cart: Cart): void {\n if (cart.status === 'expired') {\n this.forget();\n this.setCart({ cart: null, status: 'ready', error: null });\n return;\n }\n if (this.cartId !== cart.id) {\n this.cartId = cart.id;\n saveCartId(this.storage(), this.storeId, cart.id);\n }\n this.setCart({ cart, status: 'ready', error: null });\n }\n\n // ------------------------------------------------------ reads\n\n /** Reads the saved cart once (later calls share the first read). */\n load = (): Promise<void> => {\n this.loadPromise ??= this.read();\n return this.loadPromise;\n };\n\n /**\n * Reads the cart again. Also how a cart whose payment failed shows up\n * as `open` again: the read reopens it on the server.\n */\n refresh = (): Promise<void> => this.read();\n\n /** Cancels pending cart reads (the provider unmounted). */\n abortReads(): void {\n this.reads.abort();\n this.reads = new AbortController();\n this.loadPromise = null;\n }\n\n private read(): Promise<void> {\n const signal = this.reads.signal;\n return this.enqueue(async () => {\n if (signal.aborted) {\n if (this.cartState.status === 'loading')\n this.setCart({ status: 'idle' });\n return;\n }\n const epoch = this.epoch;\n const id = this.currentId();\n if (!id) {\n this.setCart({ cart: null, status: 'ready' });\n return;\n }\n this.cartId = id;\n if (this.cartState.cart === null) this.setCart({ status: 'loading' });\n try {\n const cart = await this.client.carts.get(id, { signal });\n if (epoch !== this.epoch) return;\n this.apply(cart);\n } catch (e) {\n if (epoch !== this.epoch) return;\n if (signal.aborted) {\n if (this.cartState.status === 'loading')\n this.setCart({ status: 'idle' });\n return;\n }\n if (isDeadCartError(e)) {\n this.forget();\n this.setCart({ cart: null, status: 'ready', error: null });\n return;\n }\n this.setCart({ status: 'ready', error: toError(e) });\n }\n });\n }\n\n // ------------------------------------------------------ writes\n\n private write(op: (cartId: string) => Promise<Cart>): Promise<Cart> {\n this.pendingWrites++;\n this.setCart({ isUpdating: true });\n return this.enqueue(async () => {\n const epoch = this.epoch;\n const current = () => epoch === this.epoch;\n /** Runs `op` on the current cart, creating one if needed. */\n const attempt = async (): Promise<Cart> => {\n let id = this.currentId();\n if (!id) {\n // Created lazily: a buyer who only browses never gets a cart.\n const created = await this.client.carts.create();\n if (!current()) {\n // Reset (or another tab) while the cart was being created: do\n // not write into a cart nobody holds.\n throw new StorefrontError(\n 'aborted',\n 0,\n 'The cart was reset while the write was pending',\n undefined,\n );\n }\n this.apply(created);\n id = created.id;\n }\n return op(id);\n };\n try {\n let cart: Cart;\n try {\n cart = await attempt();\n } catch (e) {\n if (!current() || !isOrderedCartError(e)) throw e;\n // The cart was already checked out (its payment may still be\n // open): keep its id for the app, and replay the write once on\n // a fresh cart.\n const previousCartId = this.currentId();\n this.forget();\n this.setCart({ cart: null, previousCartId });\n cart = await attempt();\n }\n if (current()) this.apply(cart);\n return cart;\n } catch (e) {\n if (current()) {\n if (isDeadCartError(e)) {\n // Gone (expired / unknown): the next write starts a new cart.\n this.forget();\n this.setCart({ cart: null, status: 'ready' });\n }\n this.setCart({ error: toError(e) });\n }\n throw e;\n } finally {\n this.pendingWrites--;\n if (this.pendingWrites === 0) this.setCart({ isUpdating: false });\n }\n });\n }\n\n addLine = (input: AddLineInput) =>\n this.write((id) => this.client.carts.addLine(id, input));\n updateLine = (lineId: string, input: { quantity: number }) =>\n this.write((id) => this.client.carts.updateLine(id, lineId, input));\n removeLine = (lineId: string) =>\n this.write((id) => this.client.carts.removeLine(id, lineId));\n setCustomer = (\n input: Parameters<StorefrontClient['carts']['setCustomer']>[1],\n ) => this.write((id) => this.client.carts.setCustomer(id, input));\n setAddress = (\n input: Parameters<StorefrontClient['carts']['setAddress']>[1],\n ) => this.write((id) => this.client.carts.setAddress(id, input));\n setShippingOption = (optionId: string) =>\n this.write((id) => this.client.carts.setShippingOption(id, optionId));\n\n /** The shipping options of the cart (empty when there is no cart yet). */\n shippingOptions = async (\n options?: RequestOptions,\n ): Promise<ShippingOptionList> => {\n const id = this.currentId();\n if (!id) return { items: [] };\n return this.client.carts.shippingOptions(id, options);\n };\n\n /**\n * Forgets the cart (e.g. once its order is paid): the next write\n * creates a new one. The old cart is not deleted on the server.\n */\n reset = (): void => {\n this.epoch++;\n this.resetEpoch++;\n this.forget();\n this.loadPromise = null;\n this.setCart({\n cart: null,\n status: 'ready',\n error: null,\n previousCartId: null,\n });\n this.setCheckout({ result: null, error: null });\n };\n\n /**\n * The saved cart id changed in another tab (a `storage` event for this\n * store's key): follow it. Operations in flight on the old cart drop\n * their outcome.\n */\n syncFromStorage = (): void => {\n const id = loadCartId(this.storage(), this.storeId);\n if (id === this.cartId) return;\n this.epoch++;\n this.cartId = id;\n this.loadPromise = null;\n if (id === null) {\n this.setCart({ cart: null, status: 'ready', error: null });\n return;\n }\n void this.refresh();\n };\n\n /** The storage key this store persists its cart id under. */\n get storageKey(): string {\n return cartIdKey(this.storeId);\n }\n\n /** The storage the cart id is kept in (null: memory only). */\n currentStorage(): CartIdStorage | null {\n return this.storage();\n }\n\n // ------------------------------------------------------ checkout\n\n /**\n * Checks the cart out. Never aborted (the server may place the order\n * anyway); a second call while one is in flight returns the same\n * promise. The cart is read again afterwards.\n */\n checkout = (\n options: { turnstileToken?: string } = {},\n ): Promise<CheckoutResult> => {\n if (this.pendingCheckout) return this.pendingCheckout;\n this.checkoutStarted = true;\n this.setCheckout({ isPending: true, error: null });\n let epoch = this.resetEpoch;\n const run = this.enqueue(async () => {\n epoch = this.resetEpoch;\n const id = this.currentId();\n if (!id) {\n throw new StorefrontError(\n 'checkout_incomplete',\n 0,\n 'There is no cart to check out',\n { missing: ['lines'] },\n );\n }\n return this.client.carts.checkout(id, {\n turnstileToken: options.turnstileToken || undefined,\n });\n });\n this.pendingCheckout = run;\n run.then(\n (result) => this.settleCheckout(epoch, { result, error: null }),\n (e: unknown) =>\n this.settleCheckout(epoch, { result: null, error: toError(e) }),\n );\n return run;\n };\n\n private settleCheckout(\n epoch: number,\n patch: Partial<CheckoutSnapshot>,\n ): void {\n this.pendingCheckout = null;\n this.setCheckout({\n // After `reset()` the outcome belongs to a cart the buyer left.\n ...(epoch === this.resetEpoch ? patch : {}),\n isPending: false,\n attempts: this.checkoutState.attempts + 1,\n });\n // Shows what the server now has: `ordered`, or the new prices after\n // `cart_changed`.\n void this.refresh();\n }\n\n /** Clears the last checkout result and error. */\n clearCheckout = (): void => {\n this.setCheckout({ result: null, error: null });\n };\n}\n\n/**\n * The default cart-id storage in a browser: the first-party `__Host-konfiqo_cart`\n * cookie (shared with a store's own frontend on the same domain) backed by\n * `localStorage`. Reads prefer the cookie, and each read that finds it\n * rewrites it, renewing its expiry. Safari caps a script-written cookie to\n * 7 days, so a cookie may expire while `localStorage` still holds the id:\n * then the id is read from `localStorage` and written back into the cookie.\n * Writes go to both, so the cart still persists when cookies are blocked.\n *\n * `removeItem` (the cart deliberately cleared on this origin) leaves a\n * tombstone in `localStorage`, which every frontend on the store origin\n * shares: while it is there an id left in `localStorage` is not brought\n * back. `setItem` clears it. Null on a server.\n */\nexport function defaultCartStorage(): CartIdStorage | null {\n if (typeof window === 'undefined') return null;\n let local: Storage | null = null;\n try {\n local = window.localStorage;\n } catch {\n local = null;\n }\n const cookie = cookieCartStorage();\n const attempt = (f: () => void): boolean => {\n try {\n f();\n return true;\n } catch {\n return false;\n }\n };\n const tombstoneKey = (key: string) => `${key}:cleared`;\n /** The marker an earlier version set; removed wherever it is seen. */\n const legacyMarkerKey = (key: string) => `${key}:in-cookie`;\n const cleared = (key: string): boolean => {\n try {\n return local?.getItem(tombstoneKey(key)) === '1';\n } catch {\n return false;\n }\n };\n const storage: CartIdStorage & { storageArea: Storage | null } = {\n // The area a `storage` event of another tab names.\n storageArea: local,\n getItem(key) {\n let fromCookie: string | null = null;\n try {\n fromCookie = cookie.getItem(key);\n } catch {\n fromCookie = null;\n }\n if (fromCookie) {\n // Renews the expiry (Safari: 7 days from the last write).\n attempt(() => cookie.setItem(key, fromCookie));\n return fromCookie;\n }\n let fromLocal: string | null = null;\n try {\n fromLocal = local?.getItem(key) ?? null;\n } catch {\n fromLocal = null;\n }\n if (!fromLocal) return null;\n // Cleared on purpose on this origin: do not bring the old id back.\n if (cleared(key)) return null;\n // The cookie expired, or never existed: put the id back into it.\n attempt(() => cookie.setItem(key, fromLocal));\n return fromLocal;\n },\n setItem(key, value) {\n const a = attempt(() => cookie.setItem(key, value));\n const b = local ? attempt(() => local.setItem(key, value)) : false;\n if (local) {\n attempt(() => local.removeItem(tombstoneKey(key)));\n attempt(() => local.removeItem(legacyMarkerKey(key)));\n }\n if (!a && !b) throw new Error('no cart storage available');\n },\n removeItem(key) {\n attempt(() => cookie.removeItem(key));\n if (local) {\n attempt(() => local.removeItem(key));\n attempt(() => local.setItem(tombstoneKey(key), '1'));\n attempt(() => local.removeItem(legacyMarkerKey(key)));\n }\n },\n };\n return storage;\n}\n","import { useCallback, useEffect, useRef, useState } from 'react';\nimport type { StorefrontHookError } from './cart-store';\n\n/** What a read hook returns. */\nexport interface ResourceResult<T> {\n /** The data, or null before it arrives (and after an error). */\n data: T | null;\n /** The error of the last read, or null. */\n error: StorefrontHookError | null;\n /** A read is in progress. */\n isLoading: boolean;\n /** Reads again. */\n refetch: () => void;\n}\n\ninterface State<T> {\n key: string | null;\n data: T | null;\n error: StorefrontHookError | null;\n isLoading: boolean;\n}\n\nconst toError = (e: unknown): StorefrontHookError =>\n e instanceof Error ? (e as StorefrontHookError) : new Error(String(e));\n\n/**\n * Reads `fetcher` whenever `key` changes (null = nothing to read). Each\n * read has its own AbortSignal, aborted when the key changes or the\n * component unmounts, so a stale answer never replaces a newer one.\n * Internal.\n */\nexport function useResource<T>(\n key: string | null,\n deps: unknown,\n fetcher: (signal: AbortSignal) => Promise<T>,\n): ResourceResult<T> {\n const [state, setState] = useState<State<T>>({\n key: null,\n data: null,\n error: null,\n isLoading: key !== null,\n });\n const [nonce, setNonce] = useState(0);\n const fetcherRef = useRef(fetcher);\n useEffect(() => {\n fetcherRef.current = fetcher;\n });\n\n useEffect(() => {\n if (key === null) {\n setState({ key, data: null, error: null, isLoading: false });\n return;\n }\n const controller = new AbortController();\n setState((s) =>\n s.key === key\n ? { ...s, isLoading: true }\n : { key, data: null, error: null, isLoading: true },\n );\n fetcherRef.current(controller.signal).then(\n (data) => {\n if (!controller.signal.aborted)\n setState({ key, data, error: null, isLoading: false });\n },\n (e: unknown) => {\n if (!controller.signal.aborted)\n setState({ key, data: null, error: toError(e), isLoading: false });\n },\n );\n return () => controller.abort();\n }, [key, deps, nonce]);\n\n const refetch = useCallback(() => setNonce((n) => n + 1), []);\n // Until the effect runs for a new key, do not show the old key's data.\n if (state.key !== key) {\n return { data: null, error: null, isLoading: key !== null, refetch };\n }\n return {\n data: state.data,\n error: state.error,\n isLoading: state.isLoading,\n refetch,\n };\n}\n","import type {\n CategoryList,\n Product,\n ProductListQuery,\n ProductPage,\n Store,\n} from '@konfiqo/storefront-sdk';\nimport { useStorefrontContext } from './provider';\nimport { useResource, type ResourceResult } from './use-resource';\n\n/** The store (`store.get()`): name, currency, theme, legal texts, checkout challenge. */\nexport function useStore(): ResourceResult<Store> {\n const { client } = useStorefrontContext();\n return useResource('store', client, (signal) => client.store.get({ signal }));\n}\n\n/** The active category tree (`categories.list()`). */\nexport function useCategories(): ResourceResult<CategoryList> {\n const { client } = useStorefrontContext();\n return useResource('categories', client, (signal) =>\n client.categories.list({ signal }),\n );\n}\n\n/**\n * A page of products (`products.list(params)`). Reads again when a\n * parameter changes, cancelling the previous read.\n */\nexport function useProducts(\n params: ProductListQuery = {},\n): ResourceResult<ProductPage> {\n const { client } = useStorefrontContext();\n const query: ProductListQuery = {\n category: params.category,\n q: params.q,\n page: params.page,\n pageSize: params.pageSize,\n };\n return useResource(JSON.stringify(query), client, (signal) =>\n client.products.list(query, { signal }),\n );\n}\n\n/**\n * One product by slug (`products.get(slug)`); an unknown slug is the\n * error `product_not_found`. A null / empty slug reads nothing.\n */\nexport function useProduct(\n slug: string | null | undefined,\n): ResourceResult<Product> {\n const { client } = useStorefrontContext();\n return useResource(slug ? `product:${slug}` : null, client, (signal) =>\n client.products.get(slug!, { signal }),\n );\n}\n","import { useEffect, useMemo, useSyncExternalStore } from 'react';\nimport type {\n AddLineInput,\n AddressInput,\n Cart,\n CartIdStorage,\n CustomerInput,\n RequestOptions,\n ShippingOptionList,\n UpdateLineInput,\n} from '@konfiqo/storefront-sdk';\nimport type { CartSnapshot } from './cart-store';\nimport { useStorefrontContext } from './provider';\n\n/** What {@link useCart} returns. */\nexport interface UseCartResult extends CartSnapshot {\n /** Total units in the cart (for a badge). */\n itemCount: number;\n /** Adds units of a variant. Creates the cart on the first write. */\n addLine(input: AddLineInput): Promise<Cart>;\n /** Sets a line's quantity (`lineId` is `CartLine.id`). */\n updateLine(lineId: string, input: UpdateLineInput): Promise<Cart>;\n /** Removes a line. */\n removeLine(lineId: string): Promise<Cart>;\n /** Sets the buyer. */\n setCustomer(input: CustomerInput): Promise<Cart>;\n /** Sets the shipping (and billing) address. */\n setAddress(input: AddressInput): Promise<Cart>;\n /** Selects a shipping option. */\n setShippingOption(optionId: string): Promise<Cart>;\n /** The shipping options of the cart (`{ items: [] }` without a cart). */\n shippingOptions(options?: RequestOptions): Promise<ShippingOptionList>;\n /** Reads the cart again (a cart whose payment failed comes back `open`). */\n refresh(): Promise<void>;\n /** Forgets the cart (e.g. after its order is paid); the next write starts a new one. */\n reset(): void;\n}\n\nconst SERVER_CART: CartSnapshot = {\n cart: null,\n status: 'idle',\n isUpdating: false,\n error: null,\n previousCartId: null,\n};\n\n/**\n * The buyer's cart, shared by every component under the provider.\n *\n * The saved cart id is read on mount (after hydration: nothing is read\n * during render). No cart is created until the first write. Every write\n * replaces the state with the server's cart view — prices are never\n * computed locally. Writes reject with a {@link StorefrontHookError} (and\n * also set `error`); a cart that expired or is unknown is forgotten, and\n * the next write starts a new one.\n */\nexport function useCart(): UseCartResult {\n const { cart: store } = useStorefrontContext();\n const snapshot = useSyncExternalStore(\n store.subscribe,\n store.getCart,\n () => SERVER_CART,\n );\n useEffect(() => {\n void store.load();\n }, [store]);\n const itemCount =\n snapshot.cart?.lines.reduce((n, line) => n + line.quantity, 0) ?? 0;\n return {\n ...snapshot,\n itemCount,\n addLine: store.addLine,\n updateLine: store.updateLine,\n removeLine: store.removeLine,\n setCustomer: store.setCustomer,\n setAddress: store.setAddress,\n setShippingOption: store.setShippingOption,\n shippingOptions: store.shippingOptions,\n refresh: store.refresh,\n reset: store.reset,\n };\n}\n\n/**\n * Where this provider keeps the cart id, as a getter (read it inside an\n * effect or handler, never during render: it is null on a server). Lets a\n * page that learns a cart id out of band (e.g. cart recovery) save it\n * where the cart reads it, with `saveCartId(getStorage(), storeId, id)`.\n */\nexport function useCartStorage(): () => CartIdStorage | null {\n const { cart } = useStorefrontContext();\n return useMemo(() => () => cart.currentStorage(), [cart]);\n}\n","import { useCallback, useEffect, useRef, useState } from 'react';\nimport { isStorefrontError, type Account } from '@konfiqo/storefront-sdk';\nimport type { StorefrontHookError } from './cart-store';\nimport { useStorefrontContext } from './provider';\n\n/** What {@link useAccount} returns. */\nexport interface UseAccountResult {\n /** The signed-in buyer's account, or null. */\n account: Account | null;\n /** `loading` until the first read answers; `signedOut` on a 401. */\n status: 'loading' | 'signedOut' | 'signedIn';\n /**\n * The last read's error when it was not a 401 (e.g. network, timeout),\n * else null. The status is `signedOut` then, unless an earlier read\n * succeeded (the account is kept).\n */\n error: StorefrontHookError | null;\n /** Reads the account again (call after sign-in, sign-out or a save). */\n refresh(): Promise<void>;\n}\n\ninterface State {\n account: Account | null;\n status: UseAccountResult['status'];\n error: StorefrontHookError | null;\n}\n\n/**\n * The buyer's account (`client.account.get()`), read after mount. A 401\n * (no or an ended session) means `signedOut`. Sign in / out and saves go\n * through `useStorefrontClient().account`; call `refresh()` afterwards.\n */\nexport function useAccount(): UseAccountResult {\n const { client } = useStorefrontContext();\n const [state, setState] = useState<State>({\n account: null,\n status: 'loading',\n error: null,\n });\n const seq = useRef(0);\n const alive = useRef(true);\n\n const refresh = useCallback(async () => {\n const mine = ++seq.current;\n try {\n const account = await client.account.get();\n if (!alive.current || mine !== seq.current) return;\n setState({ account, status: 'signedIn', error: null });\n } catch (e) {\n if (!alive.current || mine !== seq.current) return;\n if (isStorefrontError(e) && e.status === 401) {\n setState({ account: null, status: 'signedOut', error: null });\n return;\n }\n const error =\n e instanceof Error ? (e as StorefrontHookError) : new Error(String(e));\n setState((s) => ({\n account: s.account,\n status: s.account ? 'signedIn' : 'signedOut',\n error,\n }));\n }\n }, [client]);\n\n useEffect(() => {\n alive.current = true;\n void refresh();\n return () => {\n alive.current = false;\n };\n }, [refresh]);\n\n return { ...state, refresh };\n}\n","import { useCallback, useEffect, useSyncExternalStore } from 'react';\nimport type { CheckoutResult } from '@konfiqo/storefront-sdk';\nimport type { CheckoutSnapshot } from './cart-store';\nimport { useOptionalStorefrontContext, useStorefrontContext } from './provider';\n\n/** Options of `checkout()`. */\nexport interface CheckoutCallOptions {\n /**\n * The checkout challenge token (from `<CheckoutChallenge>`), required\n * when `store.checkoutChallenge` is set. Single-use.\n */\n turnstileToken?: string | null;\n}\n\n/** What {@link useCheckout} returns. */\nexport interface UseCheckoutResult extends CheckoutSnapshot {\n /**\n * Checks the cart out: `carts.checkout(cartId, { turnstileToken })`.\n * Resolves with the result (present it with `<PaymentForm>`; keep its\n * `token`, returned only once) or rejects with the error (also in\n * `error`). A call while one is in flight returns the same promise.\n */\n checkout(options?: CheckoutCallOptions): Promise<CheckoutResult>;\n /** Clears `result` and `error`. */\n reset(): void;\n}\n\nconst SERVER_CHECKOUT: CheckoutSnapshot = {\n isPending: false,\n result: null,\n error: null,\n attempts: 0,\n};\n\n/**\n * Checkout for the provider's cart. The state is shared under the\n * provider, and a checkout is **never aborted** — not even when the\n * component unmounts — because the server may place the order anyway.\n * When a component using this hook mounts after a checkout was started,\n * the cart is read again so it shows what the server has.\n *\n * Errors are {@link StorefrontError}s: switch on `error.code`. For\n * `cart_changed`, `error.details` has the new `lines`, totals and\n * `shippingOptions` (the cart is also read again): show them and let the\n * buyer confirm before calling `checkout()` again — never retry silently.\n */\nexport function useCheckout(): UseCheckoutResult {\n const { cart: store } = useStorefrontContext();\n const snapshot = useSyncExternalStore(\n store.subscribe,\n store.getCheckout,\n () => SERVER_CHECKOUT,\n );\n useEffect(() => {\n if (store.checkoutStarted) void store.refresh();\n }, [store]);\n const checkout = useCallback(\n (options: CheckoutCallOptions = {}) =>\n store.checkout({ turnstileToken: options.turnstileToken ?? undefined }),\n [store],\n );\n return { ...snapshot, checkout, reset: store.clearCheckout };\n}\n\n/** Settled checkout attempts under the provider (0 outside one). Internal. */\nexport function useCheckoutAttempts(): number {\n const ctx = useOptionalStorefrontContext();\n const store = ctx?.cart;\n return useSyncExternalStore(\n store?.subscribe ?? noopSubscribe,\n () => store?.getCheckout().attempts ?? 0,\n () => 0,\n );\n}\n\nconst noopSubscribe = () => () => {};\n","import { useCallback, useEffect, useState } from 'react';\nimport { isStorefrontError, type Order } from '@konfiqo/storefront-sdk';\nimport type { StorefrontHookError } from './cart-store';\nimport { useStorefrontContext } from './provider';\n\n/** First poll delay, milliseconds. */\nexport const ORDER_POLL_MIN_MS = 2_000;\n/** Longest poll delay, milliseconds. */\nexport const ORDER_POLL_MAX_MS = 15_000;\n\n/** The delay before poll number `attempt` (0-based): 2 s, 4 s, 8 s, then 15 s. */\nexport function orderPollDelay(attempt: number): number {\n return Math.min(ORDER_POLL_MIN_MS * 2 ** attempt, ORDER_POLL_MAX_MS);\n}\n\n/**\n * Whether an order no longer changes on its own soon: anything past\n * `pendingPayment` (`paid`, `fulfilling`, `shipped`, `delivered`,\n * `cancelled`, `refunded`, …), or a pending order whose payment `failed`\n * / `expired` (the buyer has to check out again).\n */\nexport function isOrderSettled(order: Order): boolean {\n if (order.status !== 'pendingPayment') return true;\n return order.paymentStatus === 'failed' || order.paymentStatus === 'expired';\n}\n\n/** Errors worth polling through (the service may answer next time). */\nfunction isTransient(e: unknown): boolean {\n if (!isStorefrontError(e)) return false;\n switch (e.code) {\n case 'network_error':\n case 'timeout':\n case 'rate_limited':\n case 'order_unavailable':\n case 'http_error':\n return true;\n default:\n return false;\n }\n}\n\n/** Options of {@link useOrder}. */\nexport interface UseOrderOptions {\n /**\n * Keep reading until the order is settled ({@link isOrderSettled}),\n * backing off 2 s → 4 s → 8 s → 15 s (then every 15 s). Transient\n * errors (network, timeout, throttling, `order_unavailable`) keep\n * polling; others stop it.\n */\n pollUntilFinal?: boolean;\n}\n\n/** What {@link useOrder} returns. */\nexport interface UseOrderResult {\n /** The order, or null before it arrives. Kept through a failed poll. */\n order: Order | null;\n /** The last read's error, or null. */\n error: StorefrontHookError | null;\n /** The first read is in progress. */\n isLoading: boolean;\n /** Another read is scheduled. */\n isPolling: boolean;\n /** Reads again now (and restarts polling). */\n refetch: () => void;\n}\n\ninterface State {\n key: string | null;\n order: Order | null;\n error: StorefrontHookError | null;\n isPolling: boolean;\n}\n\n/**\n * The buyer's order (`orders.get(orderId, token)`), e.g. on the page the\n * payment provider returns to (`/orders/{orderId}?token=`). The token is\n * the buyer's only key to the order: this hook never logs it or puts it\n * anywhere but the request; do not send it to analytics either.\n */\nexport function useOrder(\n orderId: string | null | undefined,\n token: string | null | undefined,\n options: UseOrderOptions = {},\n): UseOrderResult {\n const { client } = useStorefrontContext();\n const poll = options.pollUntilFinal ?? false;\n const key = orderId && token ? `${orderId} ${token}` : null;\n const [state, setState] = useState<State>({\n key: null,\n order: null,\n error: null,\n isPolling: false,\n });\n const [nonce, setNonce] = useState(0);\n\n useEffect(() => {\n if (!orderId || !token) {\n setState({ key: null, order: null, error: null, isPolling: false });\n return;\n }\n const k = `${orderId} ${token}`;\n const controller = new AbortController();\n let timer: ReturnType<typeof setTimeout> | undefined;\n let attempt = 0;\n const schedule = (atLeastMs: number) => {\n const delay = Math.max(orderPollDelay(attempt++), atLeastMs);\n setState((s) => ({ ...s, isPolling: true }));\n timer = setTimeout(tick, delay);\n };\n const tick = async () => {\n try {\n const order = await client.orders.get(orderId, token, {\n signal: controller.signal,\n });\n if (controller.signal.aborted) return;\n setState({ key: k, order, error: null, isPolling: false });\n if (poll && !isOrderSettled(order)) schedule(0);\n } catch (e) {\n if (controller.signal.aborted) return;\n const error =\n e instanceof Error\n ? (e as StorefrontHookError)\n : new Error(String(e));\n setState((s) => ({\n key: k,\n order: s.key === k ? s.order : null,\n error,\n isPolling: false,\n }));\n if (poll && isTransient(e)) {\n const retryAfter =\n isStorefrontError(e) && e.code === 'rate_limited'\n ? (e.details.retryAfter ?? 0) * 1000\n : 0;\n schedule(retryAfter);\n }\n }\n };\n void tick();\n return () => {\n controller.abort();\n clearTimeout(timer);\n };\n }, [client, orderId, token, poll, nonce]);\n\n const refetch = useCallback(() => setNonce((n) => n + 1), []);\n if (state.key !== key) {\n return {\n order: null,\n error: null,\n isLoading: key !== null,\n isPolling: false,\n refetch,\n };\n }\n return {\n order: state.order,\n error: state.error,\n isLoading: false,\n isPolling: state.isPolling,\n refetch,\n };\n}\n","import { useEffect, useRef, type HTMLAttributes } from 'react';\nimport {\n mountPayment,\n type CheckoutResult,\n type ClosedCheckoutPage,\n type PaymentPresentation,\n} from '@konfiqo/storefront-sdk';\n\n/** Props of {@link PaymentForm}. */\nexport interface PaymentFormProps extends Omit<\n HTMLAttributes<HTMLDivElement>,\n 'children' | 'onError'\n> {\n /**\n * The **unmodified** result of `checkout()` (or its presentation part).\n * Never build it from user input, URL parameters or storage: embedded\n * content runs as script.\n */\n presentation: PaymentPresentation | CheckoutResult;\n /**\n * Payment cannot be (re)opened (`presentation: \"closed\"`): show the\n * order status page for `page` (`paid`, `cancelled`, `processing`, …).\n */\n onClosed?: (page: ClosedCheckoutPage) => void;\n /** The embed is of a kind this SDK cannot render: show a fallback. */\n onUnsupported?: (embedKind: string) => void;\n /** Presenting failed (e.g. a redirect URL that is not http(s)). */\n onError?: (error: Error) => void;\n}\n\ninterface Pending {\n timer: ReturnType<typeof setTimeout>;\n content: string | null;\n unmount: () => void;\n}\n\nconst embeddedContent = (p: PaymentPresentation | CheckoutResult) =>\n p.presentation === 'embedded' && typeof p.embed.content === 'string'\n ? p.embed.content\n : null;\n\n/**\n * Presents payment with the SDK's `mountPayment`: renders the provider's\n * embedded form inside a `<div>` (its scripts run once), sends the browser\n * to a `redirect` URL, or calls `onClosed`. The form is removed on\n * unmount. Card data never passes through your code. Unstyled: pass\n * `className` / `style` for the wrapper.\n */\nexport function PaymentForm({\n presentation,\n onClosed,\n onUnsupported,\n onError,\n ...divProps\n}: PaymentFormProps) {\n const ref = useRef<HTMLDivElement>(null);\n const callbacks = useRef({ onClosed, onUnsupported, onError });\n useEffect(() => {\n callbacks.current = { onClosed, onUnsupported, onError };\n });\n const pending = useRef<Pending | null>(null);\n const navigated = useRef<unknown>(null);\n\n useEffect(() => {\n const element = ref.current;\n if (!element) return;\n // A removal deferred by the previous cleanup: skip it when the same\n // form is mounted again (React Strict Mode re-runs effects), so the\n // provider's scripts are not injected twice.\n const prev = pending.current;\n pending.current = null;\n if (prev) {\n clearTimeout(prev.timer);\n if (\n prev.content === null ||\n prev.content !== embeddedContent(presentation)\n )\n prev.unmount();\n }\n // A redirect / closed result is acted on once, even if the effect\n // re-runs (Strict Mode): one navigation, one `onClosed`.\n if (presentation.presentation !== 'embedded') {\n if (navigated.current === presentation) return;\n navigated.current = presentation;\n }\n\n let unmount: (() => void) | null = null;\n try {\n const mount = mountPayment(element, presentation, {\n onClosed: (page) => callbacks.current.onClosed?.(page),\n });\n if (mount.kind === 'embedded') unmount = mount.unmount;\n else if (mount.kind === 'unsupported')\n callbacks.current.onUnsupported?.(mount.embedKind);\n } catch (e) {\n callbacks.current.onError?.(\n e instanceof Error ? e : new Error(String(e)),\n );\n }\n if (!unmount) return;\n const remove = unmount;\n return () => {\n const entry: Pending = {\n content: embeddedContent(presentation),\n unmount: remove,\n timer: setTimeout(() => {\n if (pending.current === entry) pending.current = null;\n remove();\n }, 0),\n };\n pending.current = entry;\n };\n }, [presentation]);\n\n return <div {...divProps} ref={ref} />;\n}\n","import {\n forwardRef,\n useEffect,\n useImperativeHandle,\n useRef,\n type HTMLAttributes,\n} from 'react';\nimport { renderTurnstile, type TurnstileWidget } from '@konfiqo/storefront-sdk';\nimport { useCheckoutAttempts } from './use-checkout';\n\n/** Props of {@link CheckoutChallenge}. */\nexport interface CheckoutChallengeProps extends Omit<\n HTMLAttributes<HTMLDivElement>,\n 'children' | 'onError'\n> {\n /**\n * The store's Turnstile site key (`store.checkoutChallenge?.siteKey`).\n * Null / empty renders an empty `<div>` (the store has no challenge).\n */\n siteKey: string | null | undefined;\n /** A token is ready: pass it to `checkout({ turnstileToken })`. */\n onToken: (token: string) => void;\n /**\n * The current token can no longer be used — it expired, or a checkout\n * consumed it and the widget was reset. Drop it; a new one follows.\n */\n onExpired?: () => void;\n /** The widget failed to load or render. */\n onError?: (error: Error | string | undefined) => void;\n}\n\n/** Imperative handle of {@link CheckoutChallenge} (via `ref`). */\nexport interface CheckoutChallengeHandle {\n /** Gets a new token (the current one is dropped: `onExpired` is called). */\n reset(): void;\n}\n\n/**\n * Renders the store's checkout challenge (Cloudflare Turnstile) with the\n * SDK's `renderTurnstile`. Tokens are single-use: under a\n * `StorefrontProvider` the widget resets itself after every checkout\n * attempt of `useCheckout()`; call `ref.current.reset()` to reset it\n * yourself. The widget is removed on unmount.\n */\nexport const CheckoutChallenge = forwardRef<\n CheckoutChallengeHandle,\n CheckoutChallengeProps\n>(function CheckoutChallenge(\n { siteKey, onToken, onExpired, onError, ...divProps },\n handle,\n) {\n const ref = useRef<HTMLDivElement>(null);\n const widget = useRef<TurnstileWidget | null>(null);\n const callbacks = useRef({ onToken, onExpired, onError });\n useEffect(() => {\n callbacks.current = { onToken, onExpired, onError };\n });\n\n useEffect(() => {\n const element = ref.current;\n if (!element || !siteKey) return;\n let active = true;\n let rendered: TurnstileWidget | null = null;\n renderTurnstile(element, siteKey, {\n onToken: (t) => callbacks.current.onToken(t),\n onExpired: () => callbacks.current.onExpired?.(),\n onError: (code) => callbacks.current.onError?.(code),\n }).then(\n (w) => {\n if (!active) {\n w.remove();\n return;\n }\n rendered = w;\n widget.current = w;\n },\n (e: unknown) => {\n if (active)\n callbacks.current.onError?.(\n e instanceof Error ? e : new Error(String(e)),\n );\n },\n );\n return () => {\n active = false;\n if (rendered) {\n rendered.remove();\n if (widget.current === rendered) widget.current = null;\n }\n };\n }, [siteKey]);\n\n const reset = () => {\n if (!widget.current) return;\n callbacks.current.onExpired?.();\n widget.current.reset();\n };\n useImperativeHandle(handle, () => ({ reset }), []);\n\n // Tokens are single-use: every settled checkout consumed (or rejected)\n // the current one.\n const attempts = useCheckoutAttempts();\n const seen = useRef(attempts);\n useEffect(() => {\n if (attempts === seen.current) return;\n seen.current = attempts;\n reset();\n });\n\n return <div {...divProps} ref={ref} />;\n});\n","import Markdoc from '@markdoc/markdoc';\nimport * as React from 'react';\nimport { useEffect } from 'react';\nimport type { ComponentType, ReactNode } from 'react';\nimport { formatMoney, type ContentNode } from '@konfiqo/storefront-sdk';\nimport { useProduct, useProducts } from './catalog';\nimport { useStorefrontContext } from './provider';\nimport { useResource } from './use-resource';\n\n/** Components by tag name (`ProductGrid`, `Button`, …), e.g. to replace a default. */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type ContentComponents = Record<string, ComponentType<any>>;\n\n// ---------------------------------------------------------------- safety\n\n/** Plain tags content may use. Everything else is dropped with its children. */\nconst HTML_TAGS = new Set(\n (\n 'article section div span p h1 h2 h3 h4 h5 h6 ul ol li strong em s del ' +\n 'code pre blockquote hr br a table thead tbody tr th td figure figcaption ' +\n 'small sub sup mark'\n ).split(' '),\n);\n/** The attributes a plain tag keeps (`href` only on `a`, and only if safe). */\nconst HTML_ATTRS = new Set([\n 'class',\n 'title',\n 'align',\n 'colspan',\n 'rowspan',\n 'start',\n]);\nconst MAX_DEPTH = 40;\nconst MAX_NODES = 5000;\n\nconst hasControl = (s: string): boolean =>\n Array.from(s).some((c) => {\n const n = c.charCodeAt(0);\n return n < 0x20 || n === 0x7f;\n });\n\n/** A link target a page may follow: relative, http(s), mailto or tel. */\nfunction safeHref(v: unknown): string | null {\n if (typeof v !== 'string') return null;\n const href = v.trim();\n // No whitespace or control characters inside (`java\\nscript:` tricks).\n if (href === '' || /\\s/.test(href) || hasControl(href)) return null;\n // Browsers read `\\` like `/`: `/\\host` is protocol-relative. Refuse any\n // backslash, also percent-encoded.\n if (href.includes('\\\\') || /%5c/i.test(href)) return null;\n if (href.startsWith('#')) return href;\n if (href.startsWith('/')) return href[1] === '/' ? null : href;\n return /^(https?:|mailto:|tel:)/i.test(href) ? href : null;\n}\n\ntype Prop = string | number | boolean;\nconst isProp = (v: unknown): v is Prop =>\n typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean';\n\ninterface Walk {\n nodes: number;\n components: ContentComponents;\n}\n\nfunction clean(node: unknown, w: Walk, depth: number): ContentNode | null {\n if (typeof node === 'string') return node;\n if (node === null || typeof node !== 'object') return null;\n const n = node as Partial<Exclude<ContentNode, string>>;\n if (\n n.$$mdtype !== 'Tag' ||\n typeof n.name !== 'string' ||\n depth > MAX_DEPTH ||\n ++w.nodes > MAX_NODES\n ) {\n return null;\n }\n const name = n.name;\n const raw =\n n.attributes && typeof n.attributes === 'object' ? n.attributes : {};\n const attributes: Record<string, Prop> = {};\n if (name === '') return null;\n const isHtml = name[0] === name[0]!.toLowerCase();\n if (isHtml) {\n if (!HTML_TAGS.has(name)) return null;\n for (const [k, v] of Object.entries(raw)) {\n if (name === 'a' && k === 'href') {\n const href = safeHref(v);\n if (href !== null) attributes.href = href;\n } else if (HTML_ATTRS.has(k) && isProp(v)) {\n attributes[k] = v;\n }\n }\n } else {\n if (!Object.hasOwn(w.components, name)) return null;\n for (const [k, v] of Object.entries(raw)) {\n if (!isProp(v)) continue;\n if (k === 'ref' || k === 'children' || /^on/i.test(k)) continue;\n if (k === 'dangerouslySetInnerHTML') continue;\n // `key` would be swallowed by React as the element key.\n if (k === 'key') attributes.contentKey = v;\n else attributes[k] = v;\n }\n }\n const children: ContentNode[] = [];\n for (const c of Array.isArray(n.children) ? n.children : []) {\n const cleaned = clean(c, w, depth + 1);\n if (cleaned !== null) children.push(cleaned);\n }\n return { $$mdtype: 'Tag', name, attributes, children };\n}\n\n// ------------------------------------------------------ default components\n\nconst text = (v: unknown): string | undefined =>\n typeof v === 'string' && v !== '' ? v : undefined;\nconst slugOf = (v: unknown): string | null => {\n const s = text(v);\n return s && !/[/\\\\?#]/.test(s) && s !== '.' && s !== '..' ? s : null;\n};\n\nfunction ProductCard({\n product,\n}: {\n product: import('@konfiqo/storefront-sdk').Product;\n}) {\n const { client } = useStorefrontContext();\n const variant = product.variants[0];\n let price: string | null = null;\n try {\n price = variant ? formatMoney(variant.priceMinor, variant.currency) : null;\n } catch {\n price = null;\n }\n let image: string | null = null;\n try {\n image = product.image ? client.media.url(product.image) : null;\n } catch {\n image = null;\n }\n return (\n <a href={`/p/${encodeURIComponent(product.slug)}`}>\n {image ? <img src={image} alt=\"\" /> : null}\n <span>{product.name}</span>\n {price ? <span> {price}</span> : null}\n </a>\n );\n}\n\nfunction ProductGrid(props: { category?: unknown; limit?: unknown }) {\n const category = text(props.category);\n const limit = Number(props.limit);\n const cap = Number.isInteger(limit) && limit > 0 ? Math.min(limit, 48) : 12;\n const { data } = useProducts({ category, pageSize: cap });\n if (!data) return null;\n return (\n <ul className=\"content-product-grid\">\n {data.items.slice(0, cap).map((p) => (\n <li key={p.id}>\n <ProductCard product={p} />\n </li>\n ))}\n </ul>\n );\n}\n\nfunction ProductTag(props: { slug?: unknown }) {\n const { data } = useProduct(slugOf(props.slug));\n return data ? <ProductCard product={data} /> : null;\n}\n\nfunction CategoryLink(props: { slug?: unknown; children?: ReactNode }) {\n const slug = slugOf(props.slug);\n if (!slug) return null;\n return (\n <a href={`/c/${encodeURIComponent(slug)}`}>{props.children ?? slug}</a>\n );\n}\n\nfunction ImageTag(props: { contentKey?: unknown; alt?: unknown }) {\n const { client } = useStorefrontContext();\n const key = text(props.contentKey);\n if (!key) return null;\n let src: string;\n try {\n // Always through the media path, never a URL taken from the content.\n src = client.media.url(key);\n } catch {\n return null;\n }\n return <img src={src} alt={text(props.alt) ?? ''} />;\n}\n\nfunction ButtonTag(props: { href?: unknown; label?: unknown }) {\n const href = safeHref(props.href);\n const label = text(props.label);\n if (!href || !label) return null;\n return (\n <a className=\"button\" href={href}>\n {label}\n </a>\n );\n}\n\nconst DEFAULT_COMPONENTS: ContentComponents = {\n ProductGrid,\n Product: ProductTag,\n CategoryLink,\n Image: ImageTag,\n Button: ButtonTag,\n};\n\n// ------------------------------------------------------------------ render\n\n/**\n * Renders a store-content tree (`StoreContent.tree`) with React. Only\n * plain text tags and the known components are rendered (raw images,\n * unknown tags, ids, styles and event handlers are dropped); output goes\n * through `Markdoc.renderers.react`, never as HTML. The default components\n * (`ProductGrid`, `Product`, `CategoryLink`, `Image`, `Button`) need a\n * `<StorefrontProvider>`; `components` replaces or adds components. A\n * component gets an `Image` / custom tag's `key` attribute as `contentKey`.\n */\nexport function renderContent(\n tree: ContentNode,\n components: ContentComponents = {},\n): ReactNode {\n try {\n const merged = { ...DEFAULT_COMPONENTS, ...components };\n const cleaned = clean(tree, { nodes: 0, components: merged }, 0);\n if (cleaned === null) return null;\n return Markdoc.renderers.react(\n cleaned as unknown as Parameters<typeof Markdoc.renderers.react>[0],\n React,\n { components: merged },\n );\n } catch {\n return null;\n }\n}\n\n/** Props of {@link Content}. */\nexport interface ContentProps {\n /** The content key (`home.hero`, `about-us`, …). */\n contentKey: string;\n /** Components by tag name, replacing or adding to the defaults. */\n components?: ContentComponents;\n}\n\n/**\n * A piece of store content (Markdoc written in the console), read by key\n * from the store. Renders nothing while loading, or when the key does not\n * exist or cannot be read (a warning in development only).\n */\nexport function Content({ contentKey, components }: ContentProps): ReactNode {\n const { client } = useStorefrontContext();\n const { data, error } = useResource(\n `content:${contentKey}`,\n client,\n (signal) => client.getContent(contentKey, { signal }),\n );\n useEffect(() => {\n if (\n error &&\n typeof process !== 'undefined' &&\n process.env?.NODE_ENV !== 'production'\n ) {\n console.warn(\n `<Content contentKey=\"${contentKey}\">: ${error.message || 'could not be read'}`,\n );\n }\n }, [error, contentKey]);\n if (!data) return null;\n return <>{renderContent(data.tree, components)}</>;\n}\n","import {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n type ReactNode,\n} from 'react';\nimport type { CookieInfo } from '@konfiqo/storefront-sdk';\nimport {\n configureConsent,\n consentFor,\n OPTIONAL_CATEGORIES,\n rawConsent,\n subscribeConsent,\n writeConsent,\n type ConsentRecord,\n type OptionalCookieCategory,\n type StoredConsent,\n} from './consent';\n\n/** The consent state the banner, the panel and the footer button share. */\nexport interface ConsentState {\n /** Whether the store uses an optional cookie (so consent applies). */\n needed: boolean;\n /**\n * Opens the preferences panel; focus returns to `opener` (default: the\n * focused element) on close. When the opener is gone, focus moves to the\n * element with id `main`.\n */\n open: (opener?: HTMLElement | null) => void;\n /** The store's cookies (necessary and optional). */\n cookies: CookieInfo[];\n /** The optional categories the store uses, in display order. */\n categories: OptionalCookieCategory[];\n /** The stored choice for the current version; null when none. */\n stored: StoredConsent | null;\n /**\n * Whether the browser's choice has been read (false on the server and\n * during hydration, when `stored` is null without meaning \"no choice\").\n */\n known: boolean;\n /** Whether to show the bar: needed and no choice yet (never on the server). */\n showBar: boolean;\n /** Whether the preferences panel is open. */\n panelOpen: boolean;\n /** Closes the panel without a decision. */\n close: () => void;\n /** Stores a decision, passes it to `onDecision`, then closes the panel. */\n decide: (granted: OptionalCookieCategory[]) => void;\n}\n\nconst noop = () => undefined;\n\nconst ConsentContext = createContext<ConsentState>({\n needed: false,\n open: noop,\n cookies: [],\n categories: [],\n known: false,\n stored: null,\n showBar: false,\n panelOpen: false,\n close: noop,\n decide: noop,\n});\n\n/** Props of {@link ConsentProvider}: the store's public cookie list. */\nexport interface ConsentProviderProps {\n cookies: CookieInfo[];\n /** The store's category version ('' when no optional cookie). */\n version: string;\n /**\n * Called after every stored decision, for example to record it with\n * commerce (`recordConsent`). An error it throws is ignored.\n */\n onDecision?: (record: ConsentRecord) => void;\n children?: ReactNode;\n}\n\n/** `undefined` on the server and during hydration: the choice is unknown. */\nconst serverSnapshot = () => undefined;\n\n/**\n * Holds the shopper's cookie choice for the banner and the footer button.\n *\n * When the panel closes, focus returns to the element that opened it. When\n * there is none (it was removed, or the decision was made in the bar),\n * focus moves to the element with id `main`: give your main content\n * `id=\"main\"` and `tabIndex={-1}`.\n */\nexport function ConsentProvider({\n cookies,\n version,\n onDecision,\n children,\n}: ConsentProviderProps) {\n // Done during render so that analytics in effects below already sees it.\n configureConsent(version);\n const raw = useSyncExternalStore(\n subscribeConsent,\n rawConsent,\n serverSnapshot,\n );\n const [panelOpen, setPanelOpen] = useState(false);\n // A choice made on this page, for when cookies are blocked.\n const [decidedVersion, setDecidedVersion] = useState<string | null>(null);\n const opener = useRef<HTMLElement | null>(null);\n // Read at decision time, so a new callback each render changes nothing.\n const onDecisionRef = useRef(onDecision);\n onDecisionRef.current = onDecision;\n\n const categories = useMemo(\n () =>\n OPTIONAL_CATEGORIES.filter((c) => cookies.some((k) => k.category === c)),\n [cookies],\n );\n const needed = categories.length > 0;\n const stored = useMemo(\n () => (raw === undefined ? null : consentFor(raw, version)),\n [raw, version],\n );\n const known = raw !== undefined;\n const showBar = needed && known && !stored && decidedVersion !== version;\n\n // Focus goes back to the opener once the panel has closed; to the main\n // content when the opener has gone or the decision was made in the bar\n // (which then closes).\n const restorePending = useRef(false);\n useEffect(() => {\n if (panelOpen || !restorePending.current) return;\n restorePending.current = false;\n const target = opener.current;\n opener.current = null;\n if (target?.isConnected) target.focus();\n else document.getElementById('main')?.focus({ preventScroll: true });\n }, [panelOpen, showBar]);\n\n const open = useCallback((from?: HTMLElement | null) => {\n // Some browsers do not focus a clicked button: prefer the one passed.\n const active = from ?? document.activeElement;\n opener.current =\n active instanceof HTMLElement && active !== document.body ? active : null;\n setPanelOpen(true);\n }, []);\n\n const close = useCallback(() => {\n if (panelOpen) restorePending.current = true;\n setPanelOpen(false);\n }, [panelOpen]);\n\n const decide = useCallback(\n (granted: OptionalCookieCategory[]) => {\n const allowed = categories.filter((c) => granted.includes(c));\n const consentId = writeConsent(version, allowed);\n try {\n onDecisionRef.current?.({ consentId, granted: allowed, version });\n } catch {\n // A failing callback must not keep the panel open or lose focus.\n }\n setDecidedVersion(version);\n if (!panelOpen) opener.current = null;\n restorePending.current = true;\n setPanelOpen(false);\n },\n [categories, version, panelOpen],\n );\n\n const value = useMemo<ConsentState>(\n () => ({\n needed,\n open,\n cookies,\n categories,\n stored,\n known,\n showBar,\n panelOpen,\n close,\n decide,\n }),\n [\n needed,\n open,\n cookies,\n categories,\n stored,\n known,\n showBar,\n panelOpen,\n close,\n decide,\n ],\n );\n return (\n <ConsentContext.Provider value={value}>{children}</ConsentContext.Provider>\n );\n}\n\n/** The shared consent state (inert outside a {@link ConsentProvider}). */\nexport function useConsent(): ConsentState {\n return useContext(ConsentContext);\n}\n","import type { CookieCategory } from '@konfiqo/storefront-sdk';\n\n/** A category the shopper can grant: every one but `necessary`. */\nexport type OptionalCookieCategory = Exclude<CookieCategory, 'necessary'>;\n\n/**\n * A consent decision, as commerce records it (`POST /v1/consents`). The\n * provider hands one to `onDecision` for every decision.\n */\nexport interface ConsentRecord {\n consentId: string;\n granted: OptionalCookieCategory[];\n version: string;\n}\n\n/** A stored consent for the current category version. */\nexport interface StoredConsent {\n /** Consent id: 32 lowercase hex, kept across later choices. */\n id: string;\n granted: OptionalCookieCategory[];\n}\n\n/**\n * The strictly necessary cookie holding the shopper's choice. Its name,\n * value format (`id.version.granted`) and attributes are shared with every\n * storefront on the same host: keep them unchanged.\n */\nconst COOKIE = '_consent';\nconst MAX_AGE = 31536000;\nconst ID = /^[0-9a-f]{32}$/;\n/** Every optional category, in display order. */\nexport const OPTIONAL_CATEGORIES: readonly OptionalCookieCategory[] = [\n 'analytics',\n 'marketing',\n];\n\n/** The store's current category version ('' when it uses no optional cookie). */\nlet currentVersion = '';\nconst listeners = new Set<() => void>();\n\n/**\n * Sets the store's category version `analyticsConsent` checks against.\n * Browser-only: a no-op on the server, where this module state would be\n * shared by every request of every store.\n */\nexport function configureConsent(version: string): void {\n if (typeof window === 'undefined') return;\n currentVersion = version;\n}\n\n/** Calls `listener` after every `writeConsent`; returns the unsubscribe. */\nexport function subscribeConsent(listener: () => void): () => void {\n listeners.add(listener);\n return () => listeners.delete(listener);\n}\n\n/** The raw `_consent` value; '' when absent or unreadable. */\nexport function rawConsent(): string {\n try {\n for (const part of document.cookie.split(';')) {\n const eq = part.indexOf('=');\n if (eq < 0 || part.slice(0, eq).trim() !== COOKIE) continue;\n return part.slice(eq + 1).trim();\n }\n } catch {\n // Cookies may be blocked: no consent.\n }\n return '';\n}\n\n/** `id.version.granted` parsed; null when malformed. */\nfunction parse(\n raw: string,\n): { id: string; version: string; granted: OptionalCookieCategory[] } | null {\n const parts = raw.split('.');\n if (parts.length !== 3) return null;\n const [id, version, list] = parts as [string, string, string];\n if (!ID.test(id)) return null;\n const items = list === '' ? [] : list.split(',');\n if (\n !items.every((c) => (OPTIONAL_CATEGORIES as readonly string[]).includes(c))\n )\n return null;\n return { id, version, granted: items as OptionalCookieCategory[] };\n}\n\n/**\n * The stored consent for `version`; null when absent, malformed or given\n * for another category version (the store's cookie set has changed).\n */\nexport function readConsent(version: string): StoredConsent | null {\n return consentFor(rawConsent(), version);\n}\n\n/** {@link readConsent} on a raw `_consent` value. */\nexport function consentFor(raw: string, version: string): StoredConsent | null {\n const parsed = parse(raw);\n if (!parsed || parsed.version !== version) return null;\n return { id: parsed.id, granted: parsed.granted };\n}\n\n/** A new consent id: 32 lowercase hex from the browser's CSPRNG. */\nfunction newConsentId(): string {\n const bytes = crypto.getRandomValues(new Uint8Array(16));\n return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');\n}\n\n/**\n * Stores the shopper's choice for `version` in `_consent` (12 months) and\n * returns the consent id: a new one on the first choice, the stored one on\n * later choices.\n */\nexport function writeConsent(\n version: string,\n granted: OptionalCookieCategory[],\n): string {\n const id = parse(rawConsent())?.id ?? newConsentId();\n const list = OPTIONAL_CATEGORIES.filter((c) => granted.includes(c)).join(',');\n try {\n document.cookie = `${COOKIE}=${id}.${version}.${list}; Max-Age=${MAX_AGE}; Path=/; SameSite=Lax; Secure`;\n } catch {\n // Cookies may be blocked: the choice lasts for this page only.\n }\n for (const listener of listeners) listener();\n return id;\n}\n\n/**\n * Whether the shopper granted analytics for the store's current category\n * version. False when the store uses no optional cookie.\n */\nexport function analyticsConsent(): boolean {\n if (!currentVersion) return false;\n return readConsent(currentVersion)?.granted.includes('analytics') ?? false;\n}\n","import { analyticsConsent, type ConsentRecord } from './consent';\n\n/** The events the store reports to commerce. */\nexport type AnalyticsEventType =\n 'page_view' | 'product_view' | 'add_to_cart' | 'checkout_start';\n\n/** Optional ids that go with an event. */\nexport interface AnalyticsExtra {\n productId?: string;\n}\n\n/** Query parameters that may leave the browser: campaign tags and click ids. */\nconst QUERY_ALLOWLIST = [\n 'utm_source',\n 'utm_medium',\n 'utm_campaign',\n 'utm_content',\n 'utm_term',\n 'fbclid',\n 'ttclid',\n 'gclid',\n 'gbraid',\n 'wbraid',\n];\nconst MAX_URL = 2000;\n/** Events per request at most (the commerce limit). */\nconst MAX_BATCH = 20;\n\n/** The path with ids of token-bearing pages (order status) redacted. */\nfunction safePath(): string {\n const path = location.pathname;\n return path.startsWith('/orders/') ? '/orders/:id' : path;\n}\n\n/** The allowlisted query of the landing URL; none on token-bearing pages. */\nfunction safeQuery(): string {\n const path = location.pathname;\n if (path.startsWith('/orders/') || path.startsWith('/cart/recover'))\n return '';\n const source = new URLSearchParams(location.search);\n const kept = new URLSearchParams();\n for (const [key, value] of source) {\n if (QUERY_ALLOWLIST.includes(key)) kept.append(key, value);\n }\n const query = kept.toString();\n return query ? `?${query}` : '';\n}\n\n/** The referrer reduced to its origin; null when absent or unparsable. */\nfunction referrerOrigin(): string | null {\n try {\n return document.referrer ? new URL(document.referrer).origin : null;\n } catch {\n return null;\n }\n}\n\ninterface AnalyticsConfig {\n baseUrl: string;\n publishableKey: string;\n}\n\nconst PREVIEW_KEY = '_preview';\n\ninterface QueuedEvent {\n type: AnalyticsEventType;\n url: string;\n referrer: string | null;\n productId?: string;\n}\n\nlet config: AnalyticsConfig | null = null;\nlet first = true;\n/** Whether the landing URL has been checked for `_preview=1`. */\nlet landingChecked = false;\n/** Events tracked this tick, sent together by `flush`. */\nlet queue: QueuedEvent[] = [];\n/** Paths of the `page_view`s in `queue`, to drop same-tick duplicates. */\nlet queuedViews: string[] = [];\n\n/**\n * Sets where events go: the commerce API origin and the store's publishable\n * key. Idempotent; `AnalyticsTracker` calls it on every render.\n */\nexport function configureAnalytics(next: AnalyticsConfig): void {\n config = next;\n}\n\n/**\n * For tests only, not for production code: forgets the configuration, the\n * first-event state, the landing check and the queue, so each test starts\n * as a fresh page load. Call it in `beforeEach`.\n */\nexport function resetAnalytics(): void {\n config = null;\n first = true;\n landingChecked = false;\n queue = [];\n queuedViews = [];\n}\n\n/** Whether a URL query carries the store editor's preview flag. */\nfunction previewQuery(): boolean {\n return new URLSearchParams(location.search).get(PREVIEW_KEY) === '1';\n}\n\n/**\n * Reads the landing URL once: a tab opened from the store editor's preview\n * (`_preview=1` on the landing URL, only there) is remembered in\n * sessionStorage so the flag survives navigation inside the tab. Only\n * `track` reads the landing (its first event is the landing view).\n */\nfunction readLanding(): void {\n if (landingChecked) return;\n landingChecked = true;\n try {\n if (previewQuery()) sessionStorage.setItem(PREVIEW_KEY, '1');\n } catch {\n // Storage may be blocked; the flag then lasts for the landing URL only.\n }\n}\n\n/**\n * True for a preview tab: the remembered flag, or `_preview=1` on a landing\n * URL not read yet. Reads only; never consumes the landing check.\n */\nfunction isPreview(): boolean {\n if (!landingChecked && previewQuery()) return true;\n try {\n return sessionStorage.getItem(PREVIEW_KEY) === '1';\n } catch {\n return false;\n }\n}\n\n/**\n * Reports one event. Fire and forget: never awaited, never throws. The\n * first event of a page load carries the full URL (allowlisted query\n * included) and the referrer origin so campaign tags are counted once;\n * later events carry the path only.\n *\n * An identical `page_view` (same path) in the same tick is sent once.\n *\n * Events of one tick are queued and sent together, in call order, by one\n * request (MAX_BATCH events each), so the landing `page_view` and a\n * `product_view` from the same render reach commerce as one batch.\n */\nexport function track(\n type: AnalyticsEventType,\n extra: AnalyticsExtra = {},\n): void {\n try {\n if (!config) return;\n readLanding();\n if (isPreview()) return;\n // React StrictMode runs effects twice: one view per path and tick.\n if (type === 'page_view') {\n const path = safePath();\n if (queuedViews.includes(path)) return;\n queuedViews.push(path);\n }\n const url = (first ? safePath() + safeQuery() : safePath()).slice(\n 0,\n MAX_URL,\n );\n const referrer = first ? referrerOrigin() : null;\n first = false;\n const { productId } = extra;\n if (queue.length === 0) queueMicrotask(flush);\n queue.push({ type, url, referrer, ...(productId ? { productId } : {}) });\n } catch {\n // Analytics must never break the page.\n }\n}\n\n/**\n * Posts `body` as JSON to `path` on the configured commerce origin with the\n * publishable key. Fire and forget: `keepalive` lets it outlive the page,\n * errors are swallowed.\n */\nfunction send(cfg: AnalyticsConfig, path: string, body: unknown): void {\n void fetch(`${cfg.baseUrl}${path}`, {\n method: 'POST',\n keepalive: true,\n headers: {\n 'content-type': 'application/json',\n 'x-konfiqo-publishable-key': cfg.publishableKey,\n },\n body: JSON.stringify(body),\n }).catch(() => undefined);\n}\n\n/** Sends the queued events, MAX_BATCH per request. */\nfunction flush(): void {\n try {\n const events = queue;\n queue = [];\n queuedViews = [];\n if (!config) return;\n // Read now, not when tracked: a choice made meanwhile already counts.\n const consent = { analytics: analyticsConsent() };\n for (let i = 0; i < events.length; i += MAX_BATCH) {\n send(config, '/v1/events', {\n events: events.slice(i, i + MAX_BATCH),\n consent,\n });\n }\n } catch {\n // Analytics must never break the page.\n }\n}\n\n/**\n * Records a consent decision with commerce. Fire and forget, never throws.\n * Not from the store editor's preview tab (the seller's own choices).\n */\nexport function recordConsent(record: ConsentRecord): void {\n try {\n if (!config || isPreview()) return;\n send(config, '/v1/consents', record);\n } catch {\n // Recording must never break the page.\n }\n}\n","import { useEffect } from 'react';\nimport { configureAnalytics, track } from './analytics';\n\n/** Props of {@link AnalyticsTracker}. */\nexport interface AnalyticsTrackerProps {\n /** The commerce API origin (the `baseUrl` the storefront client uses). */\n baseUrl: string;\n /** The store's publishable key. */\n publishableKey: string;\n /**\n * The current route's path, from your router (for example Next.js\n * `usePathname()`). Each new value sends one `page_view`.\n */\n pathname: string;\n}\n\n/**\n * Configures analytics and sends a `page_view` on mount and every route change.\n *\n * Pages whose URL carries a buyer secret are protected by path. On an\n * order-status page the URL sent is `/orders/:id`, and on both\n * `/orders/…` and `/cart/recover` the query is left out. A custom storefront must serve its\n * order-status and cart-recovery pages only at those paths, or not render\n * this component there.\n */\nexport function AnalyticsTracker({\n baseUrl,\n publishableKey,\n pathname,\n}: AnalyticsTrackerProps) {\n // Idempotent assignment, done during render so that effects of the\n // components below (which run first) can already track.\n configureAnalytics({ baseUrl, publishableKey });\n useEffect(() => {\n track('page_view');\n }, [pathname]);\n return null;\n}\n","import type { AdPixels } from '@konfiqo/storefront-sdk';\n\n/**\n * What the pixel layer is told about; mapped onto each platform's events.\n *\n * Ids match the rows of the store's product feed, which are variants: a\n * known variant is sent as the item (`product`); a product page before a\n * variant is chosen sends the product id as the group (`product_group`).\n * `purchase` items carry variant ids.\n */\nexport type PixelEvent =\n | { name: 'page_view' }\n | {\n name: 'view_item';\n productId: string;\n /** The selected variant, when one is chosen. */\n variantId?: string;\n priceMinor: number;\n }\n | {\n name: 'add_to_cart';\n productId: string;\n variantId: string;\n priceMinor: number;\n quantity: number;\n }\n | { name: 'begin_checkout'; valueMinor: number }\n | {\n name: 'purchase';\n orderId: string;\n valueMinor: number;\n /** `id` is the variant id. */\n items: { id: string; quantity: number; priceMinor: number }[];\n };\n\ntype ContentType = 'product' | 'product_group';\n\n/** The feed row an item event names: the variant when known, else the group. */\nfunction itemOf(e: { productId: string; variantId?: string }): {\n id: string;\n type: ContentType;\n} {\n return e.variantId\n ? { id: e.variantId, type: 'product' }\n : { id: e.productId, type: 'product_group' };\n}\n\n/** The currency used when `configurePixels` is given none. */\nconst DEFAULT_CURRENCY = 'TRY';\nconst PURCHASE_KEY = 'px_purchase_';\n/**\n * Set (per store host: localStorage is per origin) once pixels were loaded\n * under a grant; a later denied page clears their cookies once and drops it.\n */\nconst GRANT_MARKER_KEY = 'px_granted';\n\ntype Fn = (...args: unknown[]) => void;\ntype PixelWindow = Window & {\n fbq?: Fn;\n _fbq?: unknown;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ttq?: any;\n TiktokAnalyticsObject?: string;\n gtag?: Fn;\n dataLayer?: unknown[];\n};\n\nconst win = (): PixelWindow => window as unknown as PixelWindow;\n\nlet pixels: AdPixels | undefined;\n/** The store's currency (every price is in it). */\nlet currency = DEFAULT_CURRENCY;\nlet granted = false;\n/** Platforms whose script has been added (once per page load). */\nconst loaded = new Set<'meta' | 'tiktok' | 'google'>();\n/** Whether `configurePixels` has run on this page load. */\nlet configured = false;\n/** At most this many events are held before the first configuration. */\nconst MAX_EARLY = 20;\n/**\n * Events fired before the first `configurePixels` (a product page's mount\n * effect runs before the consent is read): sent by the first configuration\n * under a grant, dropped by one without.\n */\nconst early: PixelEvent[] = [];\n\n/**\n * For tests only, not for production code: forgets the configuration, the\n * grant and which scripts were loaded, so each test starts as a fresh page\n * load (storage and cookies are kept). Call it in `beforeEach`.\n */\nexport function resetPixels(): void {\n pixels = undefined;\n currency = DEFAULT_CURRENCY;\n granted = false;\n optedOut = false;\n loaded.clear();\n configured = false;\n early.length = 0;\n}\n\n/** Major units (minor / 100). */\nconst major = (minor: number) => minor / 100;\n\nfunction addScript(src: string): void {\n const el = document.createElement('script');\n el.async = true;\n el.src = src;\n document.head.appendChild(el);\n}\n\nfunction loadMeta(id: string): void {\n const w = win();\n if (!w.fbq) {\n // The standard stub: queues calls until fbevents.js takes over.\n const fbq = function (...args: unknown[]) {\n const f = fbq as unknown as {\n callMethod?: (...a: unknown[]) => void;\n queue: unknown[];\n };\n if (f.callMethod) f.callMethod(...args);\n else f.queue.push(args);\n };\n Object.assign(fbq, {\n push: fbq,\n loaded: true,\n version: '2.0',\n queue: [] as unknown[],\n });\n w.fbq = fbq;\n w._fbq = fbq;\n }\n // No automatic PageView on history changes: page views are sent by\n // `firePixel` (none on pages whose URL carries a buyer secret).\n (w.fbq as unknown as { disablePushState?: boolean }).disablePushState = true;\n addScript('https://connect.facebook.net/en_US/fbevents.js');\n w.fbq('init', id);\n}\n\nconst TT_METHODS = [\n 'page',\n 'track',\n 'identify',\n 'instances',\n 'debug',\n 'on',\n 'off',\n 'once',\n 'ready',\n 'alias',\n 'group',\n 'enableCookie',\n 'disableCookie',\n 'holdConsent',\n 'revokeConsent',\n 'grantConsent',\n];\n\n/** TikTok's official base code (`ttq.load` bookkeeping `events.js` reads). */\nfunction loadTikTok(id: string): void {\n const w = win();\n w.TiktokAnalyticsObject = 'ttq';\n type Queue = unknown[] & Record<string, unknown>;\n const ttq = (w.ttq = w.ttq ?? ([] as unknown)) as unknown as Queue & {\n methods: string[];\n setAndDefer: (t: Queue, m: string) => void;\n instance: (id: string) => Queue;\n load: (id: string, opts?: { partner?: string }) => void;\n _i: Record<string, Queue & { _u?: string }>;\n _t: Record<string, number>;\n _o: Record<string, unknown>;\n };\n ttq.methods = TT_METHODS;\n ttq.setAndDefer = (t, m) => {\n t[m] = (...args: unknown[]) => {\n t.push([m, ...args]);\n };\n };\n for (const m of ttq.methods) ttq.setAndDefer(ttq, m);\n ttq.instance = (name) => {\n const inst = ttq._i[name] ?? ([] as unknown as Queue);\n for (const m of ttq.methods) ttq.setAndDefer(inst, m);\n return inst;\n };\n ttq.load = (name, opts) => {\n const src = 'https://analytics.tiktok.com/i18n/pixel/events.js';\n ttq._i = ttq._i ?? {};\n ttq._i[name] = [] as unknown as Queue & { _u?: string };\n ttq._i[name]._u = src;\n ttq._t = ttq._t ?? {};\n ttq._t[name] = Date.now();\n ttq._o = ttq._o ?? {};\n ttq._o[name] = opts ?? {};\n addScript(`${src}?sdkid=${encodeURIComponent(name)}&lib=ttq`);\n };\n ttq.load(id);\n}\n\nfunction loadGoogle(g: NonNullable<AdPixels['google']>): void {\n const w = win();\n const ids = [g.ga4Id, g.adsId].filter((v): v is string => !!v);\n if (ids.length === 0) return;\n w.dataLayer = w.dataLayer ?? [];\n if (!w.gtag) {\n w.gtag = function () {\n // gtag.js reads `arguments` objects, not arrays.\n // eslint-disable-next-line prefer-rest-params\n w.dataLayer!.push(arguments);\n };\n }\n addScript(\n `https://www.googletagmanager.com/gtag/js?id=${encodeURIComponent(ids[0]!)}`,\n );\n w.gtag('js', new Date());\n // Host-only cookies everywhere (GA4, Ads and the conversion linker): on a\n // default store domain the parent is shared by every store.\n const cookieDomain = location.hostname;\n w.gtag('set', { cookie_domain: cookieDomain });\n // Page views are sent by `firePixel`, once per route change.\n for (const id of ids) {\n w.gtag('config', id, {\n send_page_view: false,\n cookie_domain: cookieDomain,\n });\n }\n}\n\n/**\n * Whether this page's URL carries a buyer secret: the order page\n * (`/orders/{id}?token=…`) and the cart-recovery link (`/cart/recover?t=…`).\n * Platform scripts read the page URL and send it on, so pixels load nothing\n * and send nothing there; the server's events still report the purchase.\n * Store analytics scrubs the same pages (`/orders/:id`, no query).\n *\n * The paths are fixed: a custom storefront must serve its order-status and\n * cart-recovery pages only at `/orders/…` and `/cart/recover`, or send no\n * analytics or pixel events from them.\n */\nexport function onSecretPage(\n path: string = typeof location === 'undefined' ? '' : location.pathname,\n): boolean {\n return path.startsWith('/orders/') || path.startsWith('/cart/recover');\n}\n\n/** Loads each enabled platform's script once, on the first grant. */\nfunction loadAll(p: AdPixels): void {\n if (p.meta && !loaded.has('meta')) {\n loaded.add('meta');\n loadMeta(p.meta.pixelId);\n }\n if (p.tiktok && !loaded.has('tiktok')) {\n loaded.add('tiktok');\n loadTikTok(p.tiktok.pixelId);\n }\n if (p.google && !loaded.has('google')) {\n loaded.add('google');\n loadGoogle(p.google);\n }\n}\n\ntype Platform = 'meta' | 'tiktok' | 'google';\n\n/** Each platform's first-party cookies: exact names and name prefixes. */\nconst PLATFORM_COOKIES: Record<\n Platform,\n { names: string[]; prefixes: string[] }\n> = {\n meta: { names: ['_fbp', '_fbc'], prefixes: [] },\n tiktok: {\n names: ['_ttp', '_tt_enable_cookie', 'ttcsid'],\n prefixes: ['ttcsid_'],\n },\n google: { names: ['_ga', '_gcl_au', '_gcl_aw'], prefixes: ['_ga_'] },\n};\n\nfunction platformsOf(p: AdPixels): Platform[] {\n return (['meta', 'tiktok', 'google'] as const).filter((k) => !!p[k]);\n}\n\nfunction readMarker(): boolean {\n try {\n return localStorage.getItem(GRANT_MARKER_KEY) !== null;\n } catch {\n return false;\n }\n}\n\nfunction writeMarker(on: boolean): void {\n try {\n if (on) localStorage.setItem(GRANT_MARKER_KEY, '1');\n else localStorage.removeItem(GRANT_MARKER_KEY);\n } catch {\n // Storage blocked: a later denied page simply clears nothing.\n }\n}\n\nconst PROBE = '_px_probe';\n\n/**\n * The registrable domain (eTLD+1) the libraries write to, found the way they\n * find it: the shortest parent of the host that accepts a cookie (browsers\n * refuse a public suffix). The host itself when none does.\n */\nfunction registrableDomain(host: string): string {\n const parts = host.split('.');\n for (let i = parts.length - 2; i > 0; i--) {\n const candidate = parts.slice(i).join('.');\n document.cookie = `${PROBE}=1; Path=/; Domain=${candidate}`;\n if (document.cookie.split(';').some((c) => c.trim() === `${PROBE}=1`)) {\n document.cookie = `${PROBE}=; Max-Age=0; Path=/; Domain=${candidate}`;\n return candidate;\n }\n }\n return host;\n}\n\n/**\n * Deletes the cookies of the platforms configured in `p` that this page\n * sees, on the host (host-only and `Domain=host`) and, unless `onlyHost`,\n * on the registrable domain. Never on a public suffix or another parent.\n */\nfunction clearCookies(p: AdPixels, onlyHost: boolean): void {\n try {\n const spec = platformsOf(p).map((k) => PLATFORM_COOKIES[k]);\n const present = document.cookie\n .split(';')\n .map((c) => c.split('=')[0]!.trim())\n .filter(Boolean);\n const names = present.filter((n) =>\n spec.some(\n (s) => s.names.includes(n) || s.prefixes.some((x) => n.startsWith(x)),\n ),\n );\n if (names.length === 0) return;\n const host = location.hostname;\n const domains: (string | undefined)[] = [undefined, host];\n if (!onlyHost && !/^[\\d.]+$/.test(host) && !host.includes(':')) {\n const site = registrableDomain(host);\n if (site !== host) domains.push(site);\n }\n for (const name of names) {\n for (const domain of domains) {\n document.cookie = `${name}=; Max-Age=0; Path=/${domain ? `; Domain=${domain}` : ''}`;\n }\n }\n } catch {\n // Cookies may be blocked: nothing to delete.\n }\n}\n\n/** Whether the platforms were told to stop (undone by a later grant). */\nlet optedOut = false;\n\nconst GOOGLE_CONSENT = (v: 'granted' | 'denied') => ({\n ad_storage: v,\n analytics_storage: v,\n ad_user_data: v,\n ad_personalization: v,\n});\n\nfunction googleIds(g?: AdPixels['google']): string[] {\n return [g?.ga4Id, g?.adsId].filter((v): v is string => !!v);\n}\n\n/** Withdrawal: each loaded library's own opt-out (scripts stay in memory). */\nfunction optOut(p: AdPixels): void {\n optedOut = true;\n const w = win() as unknown as Record<string, unknown>;\n for (const id of googleIds(p.google)) w[`ga-disable-${id}`] = true;\n if (loaded.has('google') && typeof w.gtag === 'function') {\n (w.gtag as Fn)('consent', 'update', GOOGLE_CONSENT('denied'));\n }\n if (loaded.has('meta') && typeof w.fbq === 'function') {\n (w.fbq as Fn)('consent', 'revoke');\n }\n const ttq = w.ttq as Record<string, unknown> | undefined;\n if (loaded.has('tiktok') && typeof ttq?.disableCookie === 'function') {\n (ttq.disableCookie as Fn)();\n }\n}\n\n/** A later grant after a withdrawal: undo {@link optOut}. */\nfunction optIn(p: AdPixels): void {\n optedOut = false;\n const w = win() as unknown as Record<string, unknown>;\n for (const id of googleIds(p.google)) w[`ga-disable-${id}`] = false;\n if (loaded.has('google') && typeof w.gtag === 'function') {\n (w.gtag as Fn)('consent', 'update', GOOGLE_CONSENT('granted'));\n }\n if (loaded.has('meta') && typeof w.fbq === 'function') {\n (w.fbq as Fn)('consent', 'grant');\n }\n const ttq = w.ttq as Record<string, unknown> | undefined;\n if (loaded.has('tiktok') && typeof ttq?.enableCookie === 'function') {\n (ttq.enableCookie as Fn)();\n }\n}\n\n/**\n * Sets the store's pixels and whether the shopper granted `marketing`.\n * Scripts load once, on the first grant. Platform cookies are deleted only\n * on a withdrawal on this page, or on a denied page when this browser\n * loaded the store's pixels under an earlier grant (the marker), and only\n * those of the platforms configured. `hostOnly` (a default store domain)\n * keeps the deletion to the host. `currency` (ISO 4217, default `'TRY'`)\n * is the currency of every price and value sent to the platforms.\n */\nexport function configurePixels(\n next: AdPixels | undefined,\n isGranted: boolean,\n opts: { hostOnly?: boolean; currency?: string } = {},\n): void {\n const held = configured ? [] : early.splice(0);\n configured = true;\n try {\n pixels = next;\n currency = opts.currency ?? DEFAULT_CURRENCY;\n const was = granted;\n granted = isGranted && !!next;\n if (granted && next) {\n if (optedOut) optIn(next);\n // On a secret page the scripts wait for the next page view elsewhere.\n if (!onSecretPage()) loadAll(next);\n if (platformsOf(next).length > 0) writeMarker(true);\n } else if (next) {\n // Live libraries are told to stop.\n if (was) optOut(next);\n if (was || readMarker()) {\n clearCookies(next, opts.hostOnly ?? false);\n writeMarker(false);\n }\n }\n // Without a grant `send` drops them: a later grant never sends them.\n for (const e of held) send(e);\n } catch {\n // Pixels must never break the page.\n }\n}\n\n/** Whether `firePixel` would reach the platforms now. */\nexport function pixelsActive(): boolean {\n return granted && !!pixels;\n}\n\n/** Whether this browser already reported the purchase. */\nfunction purchased(orderId: string): boolean {\n try {\n return localStorage.getItem(PURCHASE_KEY + orderId) !== null;\n } catch {\n return false;\n }\n}\n\nfunction markPurchased(orderId: string): void {\n try {\n localStorage.setItem(PURCHASE_KEY + orderId, '1');\n } catch {\n // Storage blocked: the server's event id still dedupes.\n }\n}\n\n/**\n * Reports `e` to every enabled platform; a no-op without a grant. Before\n * the page's first `configurePixels`, the newest 20 events are held for it.\n */\nexport function firePixel(e: PixelEvent): void {\n if (!configured) {\n // Nothing is held on the server (module state is shared by requests).\n if (typeof window === 'undefined' || onSecretPage()) return;\n early.push(e);\n if (early.length > MAX_EARLY) early.shift();\n return;\n }\n send(e);\n}\n\nfunction send(e: PixelEvent): void {\n try {\n if (!granted || !pixels || onSecretPage()) return;\n loadAll(pixels);\n if (e.name === 'purchase') {\n if (purchased(e.orderId)) return;\n markPurchased(e.orderId);\n }\n const w = win();\n if (pixels.meta && w.fbq) meta(w.fbq, e);\n if (pixels.tiktok && w.ttq) tiktok(w.ttq, e);\n if (pixels.google && w.gtag) google(w.gtag, pixels.google, e);\n } catch {\n // Pixels must never break the page.\n }\n}\n\nfunction meta(fbq: Fn, e: PixelEvent): void {\n switch (e.name) {\n case 'page_view':\n fbq('track', 'PageView');\n return;\n case 'view_item': {\n const it = itemOf(e);\n fbq('track', 'ViewContent', {\n content_ids: [it.id],\n content_type: it.type,\n value: major(e.priceMinor),\n currency,\n });\n return;\n }\n case 'add_to_cart':\n fbq('track', 'AddToCart', {\n content_ids: [e.variantId],\n content_type: 'product',\n contents: [\n {\n id: e.variantId,\n quantity: e.quantity,\n item_price: major(e.priceMinor),\n },\n ],\n value: major(e.priceMinor * e.quantity),\n currency,\n });\n return;\n case 'begin_checkout':\n fbq('track', 'InitiateCheckout', {\n value: major(e.valueMinor),\n currency,\n });\n return;\n case 'purchase':\n fbq(\n 'track',\n 'Purchase',\n {\n content_ids: e.items.map((i) => i.id),\n content_type: 'product',\n contents: e.items.map((i) => ({\n id: i.id,\n quantity: i.quantity,\n item_price: major(i.priceMinor),\n })),\n value: major(e.valueMinor),\n currency,\n },\n { eventID: e.orderId },\n );\n }\n}\n\nfunction tiktok(ttq: NonNullable<PixelWindow['ttq']>, e: PixelEvent): void {\n const content = (\n id: string,\n quantity: number,\n priceMinor: number,\n type: ContentType = 'product',\n ) => ({\n content_id: id,\n content_type: type,\n quantity,\n price: major(priceMinor),\n });\n switch (e.name) {\n case 'page_view':\n ttq.page!();\n return;\n case 'view_item': {\n const it = itemOf(e);\n ttq.track!('ViewContent', {\n contents: [content(it.id, 1, e.priceMinor, it.type)],\n value: major(e.priceMinor),\n currency,\n });\n return;\n }\n case 'add_to_cart':\n ttq.track!('AddToCart', {\n contents: [content(e.variantId, e.quantity, e.priceMinor)],\n value: major(e.priceMinor * e.quantity),\n currency,\n });\n return;\n case 'begin_checkout':\n ttq.track!('InitiateCheckout', {\n value: major(e.valueMinor),\n currency,\n });\n return;\n case 'purchase':\n ttq.track!(\n 'CompletePayment',\n {\n contents: e.items.map((i) => content(i.id, i.quantity, i.priceMinor)),\n value: major(e.valueMinor),\n currency,\n },\n { event_id: e.orderId },\n );\n }\n}\n\nfunction google(\n gtag: Fn,\n g: NonNullable<AdPixels['google']>,\n e: PixelEvent,\n): void {\n const item = (id: string, quantity: number, priceMinor: number) => ({\n item_id: id,\n quantity,\n price: major(priceMinor),\n });\n switch (e.name) {\n case 'page_view':\n gtag('event', 'page_view');\n return;\n case 'view_item':\n gtag('event', 'view_item', {\n currency,\n value: major(e.priceMinor),\n items: [item(itemOf(e).id, 1, e.priceMinor)],\n });\n return;\n case 'add_to_cart':\n gtag('event', 'add_to_cart', {\n currency,\n value: major(e.priceMinor * e.quantity),\n items: [item(e.variantId, e.quantity, e.priceMinor)],\n });\n return;\n case 'begin_checkout':\n gtag('event', 'begin_checkout', {\n currency,\n value: major(e.valueMinor),\n });\n return;\n case 'purchase':\n gtag('event', 'purchase', {\n transaction_id: e.orderId,\n currency,\n value: major(e.valueMinor),\n items: e.items.map((i) => item(i.id, i.quantity, i.priceMinor)),\n });\n if (g.adsId && g.adsConversionLabel) {\n gtag('event', 'conversion', {\n send_to: `${g.adsId}/${g.adsConversionLabel}`,\n value: major(e.valueMinor),\n currency,\n transaction_id: e.orderId,\n });\n }\n }\n}\n","import { useEffect } from 'react';\nimport type { AdPixels } from '@konfiqo/storefront-sdk';\nimport { configurePixels, firePixel } from './ad-pixels';\nimport { useConsent } from './consent-provider';\n\n/** Props of {@link AdPixelsLoader}. */\nexport interface AdPixelsLoaderProps {\n /**\n * The store's ad pixels (`Store.adPixels`, filtered by the SDK's\n * `pixelsForHost`).\n */\n pixels?: AdPixels;\n /** A default store domain: cookies are cleared on the host only. */\n hostOnly?: boolean;\n /**\n * The store's currency (ISO 4217) for every price sent to the platforms.\n * Default `'TRY'`.\n */\n currency?: string;\n /**\n * The current route's path, from your router (for example Next.js\n * `usePathname()`). Each new value reports one page view.\n */\n pathname: string;\n}\n\n/**\n * Loads the store's ad pixels once the shopper granted `marketing` for the\n * current cookie version (no reload needed), stops them on withdrawal, and\n * reports a page view on every route change. Nothing is configured until\n * the browser's choice has been read (hydration), so a stored grant never\n * looks like a refusal. Must be inside a `ConsentProvider`.\n *\n * Pages whose URL carries a buyer secret (`/orders/…` and `/cart/recover`,\n * see `onSecretPage`) load no pixel script and send no pixel event. A\n * custom storefront must serve its order-status and cart-recovery pages\n * only at those paths, or not render this component there.\n */\nexport function AdPixelsLoader({\n pixels,\n hostOnly = false,\n currency = 'TRY',\n pathname,\n}: AdPixelsLoaderProps) {\n const { stored, known } = useConsent();\n const granted = stored?.granted.includes('marketing') ?? false;\n useEffect(() => {\n if (!known) return;\n configurePixels(pixels, granted, { hostOnly, currency });\n }, [pixels, granted, known, hostOnly, currency]);\n useEffect(() => {\n // Declared after the configure effect, so the scripts exist by now.\n if (granted) firePixel({ name: 'page_view' });\n }, [granted, pathname]);\n return null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;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SAAQE,UAAS,OAAO,UAAUD,SAAQ,CAAC;AAC/C,gCAAU,MAAM;AAEd,QAAIC,SAAS,WAAU,EAAE,MAAM,YAAY,CAAC;AAAA,EAC9C,GAAG,CAACA,UAAS,QAAQ,CAAC;AACtB,SAAO;AACT;","names":["import_storefront_sdk","config","import_react","toError","import_react","import_react","import_storefront_sdk","import_react","import_react","import_storefront_sdk","import_react","import_storefront_sdk","import_jsx_runtime","import_react","import_storefront_sdk","import_jsx_runtime","CheckoutChallenge","import_react","import_storefront_sdk","import_jsx_runtime","Markdoc","import_react","granted","import_jsx_runtime","granted","import_react","send","send","import_react","pixels","currency","granted"]}