@asteby/storefront-react 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/dialog.tsx","../src/context.tsx","../src/locale.ts","../src/payments/sdk-loader.ts","../src/payments/mercadopago.ts","../src/theme.tsx","../src/payments/theme.ts","../src/payments/use-embedded-payment.ts","../src/payments/payment-brick.tsx","../src/payments/adapter.ts","../src/payments/csp.ts"],"names":["useRef","useEffect","useCallback","createContext","useContext","useMemo","paymentMessages","useId","useState","generateIdempotencyKey","paymentOutcome","paymentErrorView","formatVoucherExpiry","jsx","jsxs","forwardRef","PaymentBrick","useImperativeHandle","formatMoney","Fragment"],"mappings":";;;;;;;AAkBO,SAAS,cAAA,CAAe,EAAE,IAAA,EAAM,OAAA,EAAS,cAAa,EAA0B;AACrF,EAAA,MAAM,GAAA,GAAMA,aAAiC,IAAI,CAAA;AACjD,EAAA,MAAM,MAAA,GAASA,aAAuB,IAAI,CAAA;AAC1C,EAAA,MAAM,UAAA,GAAaA,aAAO,OAAO,CAAA;AACjC,EAAA,UAAA,CAAW,OAAA,GAAU,OAAA;AAErB,EAAAC,eAAA,CAAU,MAAM;AACd,IAAA,MAAM,KAAK,GAAA,CAAI,OAAA;AACf,IAAA,IAAI,CAAC,EAAA,IAAM,CAAC,IAAA,EAAM;AAClB,IAAA,MAAA,CAAO,OAAA,GAAU,OAAO,QAAA,KAAa,WAAA,GAAc,SAAS,aAAA,GAAgB,IAAA;AAC5E,IAAA,MAAM,QAAA,GAAW,OAAO,EAAA,CAAG,SAAA,KAAc,UAAA;AACzC,IAAA,IAAI,CAAC,GAAG,IAAA,EAAM;AACZ,MAAA,IAAI,QAAA,EAAU;AACZ,QAAA,IAAI;AACF,UAAA,EAAA,CAAG,SAAA,EAAU;AAAA,QACf,CAAA,CAAA,MAAQ;AACN,UAAA,EAAA,CAAG,YAAA,CAAa,QAAQ,EAAE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OAAA,CAAQ,KAAA,EAAO,OAAO,CAAC,CAAC,CAAA;AAAA,IACrF,GAAA,CAAI,SAAA,EAAW,CAAC,QAAA,EAAU,SAAS,GAAG,OAAA,CAAQ,GAAG,IAAA,CAAK,KAAK,CAAA,EAAG,OAAA,CAAQ,KAAA,EAAO,GAAG,CAAC,CAAC,CAAA;AAAA,IAClF,kCAAA;AAAA,IACA,GAAA,CAAI,aAAA,EAAe,CAAC,QAAA,EAAU,GAAG,OAAA,CAAQ,GAAG,IAAA,CAAK,MAAM,CAAA,EAAG,OAAA,CAAQ,KAAA,EAAO,IAAI,CAAC,CAAC,CAAA;AAAA,IAC/E,wBAAA;AAAA,IACA,iBAAA;AAAA,IACA;AAAA,GACF;AACA,EAAA,IAAI,OAAA,CAAQ,SAAA,IAAa,2BAAA,CAA4B,IAAA,CAAK,OAAA,CAAQ,SAAS,CAAA,EAAG,KAAA,CAAM,IAAA,CAAK,CAAA,WAAA,EAAc,OAAA,CAAQ,SAAS,CAAA,CAAE,CAAA;AAC1H,EAAA,OAAO,KAAA,CAAM,KAAK,IAAI,CAAA;AACxB;AAGO,SAAS,qBAAqB,UAAA,EAA6B;AAChE,EAAA,OAAO,aAAa,qCAAA,GAAwC,yBAAA;AAC9D","file":"payments.cjs","sourcesContent":["import { useCallback, useEffect, useRef, type RefObject } from 'react'\n\nexport type DialogCloseReason = 'esc' | 'x' | 'backdrop' | 'action'\n\ntype UseModalDialogOptions = {\n open: boolean\n /** Called for Esc and backdrop clicks. The owner decides whether to close. */\n onClose: (reason: DialogCloseReason) => void\n /** Element focused when the dialog opens. Default: the element marked `data-sf-autofocus`, else the dialog itself. */\n initialFocus?: RefObject<HTMLElement | null>\n}\n\n/**\n * Native `<dialog>` wiring: `showModal()` (focus trap and inert background come from the browser),\n * Esc and backdrop clicks routed to `onClose`, and focus restored to the opener on close.\n * Falls back to the `open` attribute where `showModal` does not exist (old browsers, some test DOMs)\n * with an Esc key handler.\n */\nexport function useModalDialog({ open, onClose, initialFocus }: UseModalDialogOptions) {\n const ref = useRef<HTMLDialogElement | null>(null)\n const opener = useRef<Element | null>(null)\n const onCloseRef = useRef(onClose)\n onCloseRef.current = onClose\n\n useEffect(() => {\n const el = ref.current\n if (!el || !open) return\n opener.current = typeof document !== 'undefined' ? document.activeElement : null\n const hasModal = typeof el.showModal === 'function'\n if (!el.open) {\n if (hasModal) {\n try {\n el.showModal()\n } catch {\n el.setAttribute('open', '')\n }\n } else el.setAttribute('open', '')\n }\n const target = initialFocus?.current ?? el.querySelector<HTMLElement>('[data-sf-autofocus]') ?? el\n if (!target.hasAttribute('tabindex') && target === el) el.setAttribute('tabindex', '-1')\n target.focus({ preventScroll: true })\n\n const onCancel = (e: Event) => {\n e.preventDefault() // we close through state so the owner can navigate/track first\n onCloseRef.current('esc')\n }\n const onKey = (e: KeyboardEvent) => {\n if (e.key === 'Escape') {\n e.preventDefault()\n onCloseRef.current('esc')\n }\n }\n el.addEventListener('cancel', onCancel)\n if (!hasModal) el.addEventListener('keydown', onKey)\n return () => {\n el.removeEventListener('cancel', onCancel)\n el.removeEventListener('keydown', onKey)\n if (el.open) {\n if (typeof el.close === 'function') {\n try {\n el.close()\n } catch {\n el.removeAttribute('open')\n }\n } else el.removeAttribute('open')\n }\n const back = opener.current\n if (back instanceof HTMLElement && back.isConnected) back.focus({ preventScroll: true })\n }\n }, [open])\n\n /** Click on the backdrop (the dialog element itself, outside its content box). */\n const onBackdropClick = useCallback((e: { target: EventTarget; currentTarget: EventTarget }) => {\n if (e.target === e.currentTarget) onCloseRef.current('backdrop')\n }, [])\n\n return { ref, onBackdropClick }\n}\n\n/** `prefers-reduced-motion: reduce`, read after hydration (false on the server). */\nexport function prefersReducedMotion(): boolean {\n try {\n return typeof window !== 'undefined' && !!window.matchMedia?.('(prefers-reduced-motion: reduce)').matches\n } catch {\n return false\n }\n}\n","import { createContext, useContext, useMemo, type ReactNode } from 'react'\nimport { createStorefrontClient, type Shop, type StorefrontClient, type StorefrontClientOptions } from '@asteby/storefront'\n\nexport type StorefrontContextValue = {\n /** Client for browser-side calls (use a public `pk_` token). */\n client: StorefrontClient | null\n shop: Shop | null\n /** BCP 47 locale used for formatting (defaults to `shop.locale`, then `es-MX`). */\n locale: string\n /** ISO 4217 currency (defaults to `shop.currency_code`, then `MXN`). */\n currency: string\n}\n\nconst StorefrontContext = createContext<StorefrontContextValue | null>(null)\n\nexport type StorefrontProviderProps = {\n /** A ready client. Takes precedence over `config`. */\n client?: StorefrontClient\n /** Options to create the browser client (use a `pk_` token). */\n config?: StorefrontClientOptions\n /** Shop info loaded on the server (root loader). */\n shop?: Shop | null\n locale?: string\n currency?: string\n children?: ReactNode\n}\n\n/**\n * Makes the storefront client, shop, locale and currency available to the\n * tree. SSR-safe: creating the client does not touch `window`.\n */\nexport function StorefrontProvider({ client, config, shop = null, locale, currency, children }: StorefrontProviderProps) {\n const configKey = config ? `${config.baseUrl}|${config.token}|${config.locale ?? ''}|${config.customerToken ?? ''}` : ''\n const resolvedClient = useMemo(\n () => client ?? (config ? createStorefrontClient(config) : null),\n [client, configKey],\n )\n const value = useMemo<StorefrontContextValue>(\n () => ({\n client: resolvedClient,\n shop,\n locale: locale ?? config?.locale ?? shop?.locale ?? 'es-MX',\n currency: currency ?? shop?.currency_code ?? 'MXN',\n }),\n [resolvedClient, shop, locale, currency, config?.locale],\n )\n return <StorefrontContext.Provider value={value}>{children}</StorefrontContext.Provider>\n}\n\n/** Storefront context. Throws outside `<StorefrontProvider>`. */\nexport function useStorefront(): StorefrontContextValue {\n const ctx = useContext(StorefrontContext)\n if (!ctx) throw new Error('useStorefront must be used inside <StorefrontProvider>')\n return ctx\n}\n\n/** Storefront context or `null` outside a provider (for components that work standalone). */\nexport function useOptionalStorefront(): StorefrontContextValue | null {\n return useContext(StorefrontContext)\n}\n\n/** The client from context; throws when the provider has none. */\nexport function useStorefrontClient(): StorefrontClient {\n const { client } = useStorefront()\n if (!client) throw new Error('<StorefrontProvider> needs a `client` or `config` for browser-side calls')\n return client\n}\n","import { useOptionalStorefront } from './context.js'\n\n/** Locale of a component: its own prop, else the `StorefrontProvider`'s, else `es-MX`. */\nexport function useResolvedLocale(locale?: string | null): string {\n const sf = useOptionalStorefront()\n return locale ?? sf?.locale ?? 'es-MX'\n}\n","/**\n * Loads a provider script once, with timeout, CSP nonce and an origin allowlist.\n * The URL comes from the server (`PaymentClient.sdk_url`) but is still checked:\n * https only and, when `allowedOrigins` is given, an exact origin match.\n */\nexport type LoadScriptOptions = {\n nonce?: string\n timeoutMs: number\n /** Exact origins allowed for the script (`https://sdk.mercadopago.com`). Omitted: any https origin. */\n allowedOrigins?: readonly string[]\n /** `true` when the SDK global is already there (skips the insert). */\n isLoaded?: () => boolean\n document?: Document\n}\n\nconst pending = new Map<string, Promise<void>>()\n\nexport function loadPaymentSdk(url: string, options: LoadScriptOptions): Promise<void> {\n let parsed: URL\n try {\n parsed = new URL(url)\n } catch {\n return Promise.reject(new Error('payment sdk: invalid url'))\n }\n if (parsed.protocol !== 'https:' || parsed.username || parsed.password) return Promise.reject(new Error('payment sdk: https required'))\n if (options.allowedOrigins && !options.allowedOrigins.includes(parsed.origin)) return Promise.reject(new Error('payment sdk: origin not allowed'))\n if (options.isLoaded?.()) return Promise.resolve()\n const doc = options.document ?? (typeof document !== 'undefined' ? document : undefined)\n if (!doc) return Promise.reject(new Error('payment sdk: no document (server)'))\n\n const key = parsed.toString()\n const existing = pending.get(key)\n if (existing) return existing\n\n const p = new Promise<void>((resolve, reject) => {\n const script = doc.createElement('script')\n script.src = key\n script.async = true\n if (options.nonce) script.nonce = options.nonce\n script.dataset.sfPaymentSdk = 'true'\n let done = false\n const finish = (err?: Error) => {\n if (done) return\n done = true\n clearTimeout(timer)\n if (err) {\n script.remove()\n pending.delete(key) // allow a later retry\n reject(err)\n } else resolve()\n }\n const timer = setTimeout(() => finish(new Error('payment sdk: timeout')), options.timeoutMs)\n script.onload = () => finish()\n script.onerror = () => finish(new Error('payment sdk: failed to load'))\n doc.head.appendChild(script)\n })\n pending.set(key, p)\n return p\n}\n\n/** Test helper: forgets the loaded-script cache. */\nexport function resetPaymentSdkCache(): void {\n pending.clear()\n}\n","import { loadPaymentSdk } from './sdk-loader.js'\nimport type { MountedPaymentForm, PaymentFormAdapter, PaymentFormData, PaymentFormMountOptions } from './adapter.js'\n\n/** The `PaymentClient.kind` the addon `mercadopago` declares. */\nexport const MERCADOPAGO_BRICKS_KIND = 'mercadopago_bricks'\n\ntype MpController = { getFormData(): Promise<Record<string, unknown> | undefined | null>; unmount(): void | Promise<void> }\ntype MpBricks = { create(brick: string, containerId: string, settings: Record<string, unknown>): Promise<MpController> }\nexport type MercadoPagoCtor = new (publicKey: string, options?: { locale?: string }) => { bricks(): MpBricks }\n\nexport type MercadoPagoAdapterOptions = {\n /** Exact origins allowed for `sdk_url`. Default: Mercado Pago's SDK origin only. */\n allowedSdkOrigins?: readonly string[]\n /** Resolves the SDK constructor. Default: `window.MercadoPago`. Inject a fake in tests. */\n getSdk?: () => MercadoPagoCtor | undefined\n /** Reads the anti-fraud device id. Default: `window.MP_DEVICE_SESSION_ID`. */\n getDeviceSessionId?: () => string | undefined\n}\n\n/**\n * The only fields that may leave the browser, and the only place that decides it. Anything else the SDK returns\n * (notably `transaction_amount`, the amount: the server owns it) is dropped. Strings only, bounded length.\n */\nexport function sanitizeMercadoPagoFormData(data: Record<string, unknown> | null | undefined): Record<string, unknown> {\n const d = data ?? {}\n const str = (v: unknown, max = 256) => (typeof v === 'string' && v.length > 0 && v.length <= max ? v : undefined)\n const out: Record<string, unknown> = {}\n const token = str(d.token, 128)\n if (token) out.token = token\n const pm = str(d.payment_method_id, 64)\n if (pm) out.payment_method_id = pm\n const issuer = typeof d.issuer_id === 'number' ? String(d.issuer_id) : str(d.issuer_id, 32)\n if (issuer) out.issuer_id = issuer\n const inst = typeof d.installments === 'number' ? d.installments : Number.parseInt(String(d.installments ?? ''), 10)\n if (Number.isInteger(inst) && inst >= 1 && inst <= 48) out.installments = inst\n const payer = d.payer as { email?: unknown; identification?: { type?: unknown; number?: unknown } } | undefined\n if (payer && typeof payer === 'object') {\n const p: Record<string, unknown> = {}\n const email = str(payer.email, 254)\n if (email) p.email = email\n const idType = str(payer.identification?.type, 16)\n const idNumber = str(payer.identification?.number, 32)\n if (idType && idNumber) p.identification = { type: idType, number: idNumber }\n if (Object.keys(p).length) out.payer = p\n }\n return out\n}\n\n/**\n * Card Payment Brick adapter. The payment button is hidden: the shop's own button calls `collect()` (MP's\n * `getFormData()`), which tokenises inside MP's iframes. Card data never touches this code.\n */\nexport function mercadoPagoBricksAdapter(options: MercadoPagoAdapterOptions = {}): PaymentFormAdapter {\n const allowed = options.allowedSdkOrigins ?? ['https://sdk.mercadopago.com']\n const getSdk =\n options.getSdk ?? (() => (typeof window !== 'undefined' ? (window as unknown as { MercadoPago?: MercadoPagoCtor }).MercadoPago : undefined))\n const getDevice =\n options.getDeviceSessionId ?? (() => (typeof window !== 'undefined' ? (window as unknown as { MP_DEVICE_SESSION_ID?: string }).MP_DEVICE_SESSION_ID : undefined))\n\n return {\n kind: MERCADOPAGO_BRICKS_KIND,\n async load(client, { nonce, timeoutMs }) {\n await loadPaymentSdk(client.sdk_url, { ...(nonce ? { nonce } : {}), timeoutMs, allowedOrigins: allowed, isLoaded: () => !!getSdk() })\n if (!getSdk()) throw new Error('payment sdk: MercadoPago global missing after load')\n },\n async mount(opts: PaymentFormMountOptions): Promise<MountedPaymentForm> {\n const Ctor = getSdk()\n if (!Ctor) throw new Error('payment sdk: not loaded')\n const { client, container } = opts\n const card = client.options?.find((o) => o.key === 'card')\n const mp = new Ctor(client.public_key, { locale: opts.locale ?? client.locale ?? 'es-MX' })\n const amount = Number.parseFloat(opts.amount.amount)\n const controller = await mp.bricks().create('cardPayment', container.id, {\n initialization: { amount, ...(opts.email ? { payer: { email: opts.email } } : {}) },\n customization: {\n paymentMethods: { minInstallments: 1, ...(card?.max_installments ? { maxInstallments: card.max_installments } : {}) },\n visual: {\n hidePaymentButton: true,\n style: { theme: 'default', ...(opts.theme && Object.keys(opts.theme).length ? { customVariables: opts.theme } : {}) },\n },\n },\n callbacks: {\n onReady: () => opts.onReady(),\n onError: (e: { type?: string; message?: string; cause?: string } | undefined) => {\n opts.onError({ critical: e?.type === 'critical', ...(e?.cause ? { message: String(e.cause) } : {}) })\n },\n onSubmit: async () => undefined,\n },\n })\n let gone = false\n return {\n async collect(): Promise<PaymentFormData> {\n if (gone) throw new Error('payment form is unmounted')\n const raw = await controller.getFormData()\n const provider_data = sanitizeMercadoPagoFormData(raw)\n if (!provider_data.token) throw new Error('payment form incomplete')\n const device = getDevice()\n return { provider_data, ...(typeof device === 'string' && device ? { device_session_id: device } : {}) }\n },\n async unmount() {\n gone = true\n try {\n await controller.unmount()\n } catch {\n /* the provider may already have removed it */\n }\n },\n }\n },\n }\n}\n","/**\n * Server-side theme (S3): turns the content theme from\n * `content.theme()` into CSS custom properties so the first SSR byte already\n * carries the store's brand — no localStorage, no anti-flicker script.\n *\n * Token naming follows `@asteby/metacore-theme`: camelCase keys become\n * kebab-case (`primaryForeground` → `--primary-foreground`), and each color is\n * also exposed as a Tailwind 4 theme variable (`--color-primary-foreground`).\n * metacore-theme ships its tokens as static CSS with no reusable naming\n * helper, so this module is standalone and does not depend on it.\n */\nimport type { Theme } from '@asteby/storefront'\n\nexport type ThemeCssOptions = {\n /** Selector that receives the variables (default `:root`). */\n selector?: string\n /**\n * Variable names for color tokens:\n * `both` (default) → `--color-<name>` and `--<name>`;\n * `color` → only `--color-<name>` (Tailwind 4); `metacore` → only `--<name>`.\n */\n naming?: 'both' | 'color' | 'metacore'\n /** Fallback stack appended to every font (default system sans-serif). */\n fontFallback?: string\n}\n\nconst DEFAULT_FONT_FALLBACK = 'ui-sans-serif, system-ui, -apple-system, \"Segoe UI\", sans-serif'\nconst MONO_FALLBACK = 'ui-monospace, SFMono-Regular, Menlo, monospace'\n\n/** `primaryForeground`, `primary_foreground`, `--color-primary-foreground` → `primary-foreground`. */\nexport function tokenName(key: string): string {\n return key\n .trim()\n .replace(/^-+/, '')\n .replace(/^color-/, '')\n .replace(/([a-z0-9])([A-Z])/g, '$1-$2')\n .replace(/[\\s_.]+/g, '-')\n .toLowerCase()\n .replace(/[^a-z0-9-]/g, '')\n .replace(/-+/g, '-')\n .replace(/^-|-$/g, '')\n}\n\n/** Rejects values that could escape the declaration or the `<style>` element. */\nexport function isSafeCssValue(value: string): boolean {\n if (!value || value.length > 200) return false\n if (/[;{}<>\\\\]/.test(value)) return false\n if (/url\\s*\\(|expression\\s*\\(|@import/i.test(value)) return false\n return true\n}\n\nfunction fontStack(family: string, role: string, fallback: string): string | null {\n const name = family.replace(/[\"']/g, '').trim()\n if (!name || !isSafeCssValue(name)) return null\n return `\"${name}\", ${role === 'mono' ? MONO_FALLBACK : fallback}`\n}\n\n/** CSS declarations (`--x:value`) for a theme, without selector. */\nexport function themeToCssVariables(theme: Partial<Theme> | null | undefined, options: ThemeCssOptions = {}): Record<string, string> {\n const naming = options.naming ?? 'both'\n const vars: Record<string, string> = {}\n for (const [key, raw] of Object.entries(theme?.tokens ?? {})) {\n const name = tokenName(key)\n const value = String(raw).trim()\n if (!name || !isSafeCssValue(value)) continue\n if (naming !== 'metacore') vars[`--color-${name}`] = value\n if (naming !== 'color') vars[`--${name}`] = value\n }\n const fallback = options.fontFallback ?? DEFAULT_FONT_FALLBACK\n for (const [role, family] of Object.entries(theme?.fonts ?? {})) {\n const name = tokenName(role)\n const stack = typeof family === 'string' ? fontStack(family, name, fallback) : null\n if (name && stack) vars[`--font-${name}`] = stack\n }\n if (theme?.radius && isSafeCssValue(theme.radius.trim())) vars['--radius'] = theme.radius.trim()\n return vars\n}\n\n/** `:root{--color-primary:#0f766e;--primary:#0f766e;...}` from a content theme. */\nexport function themeToCss(theme: Partial<Theme> | null | undefined, options: ThemeCssOptions = {}): string {\n const vars = themeToCssVariables(theme, options)\n const body = Object.entries(vars)\n .map(([k, v]) => `${k}:${v}`)\n .join(';')\n if (!body) return ''\n const selector = (options.selector ?? ':root').replace(/[{}<>]/g, '')\n return `${selector}{${body}}`\n}\n\n/** Google Fonts stylesheet URL for the theme fonts (or `null` when there are none). */\nexport function themeFontsHref(theme: Partial<Theme> | null | undefined, weights: number[] = [400, 500, 600, 700]): string | null {\n const families = [...new Set(Object.values(theme?.fonts ?? {}).map((f) => String(f).replace(/[\"']/g, '').trim()).filter((f) => f && isSafeCssValue(f)))]\n if (!families.length) return null\n const params = families.map((f) => `family=${encodeURIComponent(f).replace(/%20/g, '+')}:wght@${weights.join(';')}`).join('&')\n return `https://fonts.googleapis.com/css2?${params}&display=swap`\n}\n\nexport type ThemeStyleProps = ThemeCssOptions & {\n theme: Partial<Theme> | null | undefined\n nonce?: string\n id?: string\n}\n\n/** Emits the theme variables as a `<style>` (render it in `<head>` from the root route). */\nexport function ThemeStyle({ theme, nonce, id = 'storefront-theme', ...options }: ThemeStyleProps) {\n const css = themeToCss(theme, options)\n if (!css) return null\n return <style id={id} nonce={nonce} data-storefront-theme=\"\" dangerouslySetInnerHTML={{ __html: css }} />\n}\n","import { isSafeCssValue } from '../theme.js'\n\n/** CSS custom properties (set by the shop in its stylesheet) -> provider widget variables. */\nexport const PAYMENT_THEME_TOKENS = {\n '--sf-pay-text': 'textPrimaryColor',\n '--sf-pay-text-muted': 'textSecondaryColor',\n '--sf-pay-background': 'formBackgroundColor',\n '--sf-pay-input-background': 'inputBackgroundColor',\n '--sf-pay-primary': 'baseColor',\n '--sf-pay-primary-contrast': 'buttonTextColor',\n '--sf-pay-error': 'errorColor',\n '--sf-pay-success': 'successColor',\n '--sf-pay-outline': 'outlinePrimaryColor',\n '--sf-pay-radius': 'borderRadiusMedium',\n} as const\n\n/**\n * Reads the `--sf-pay-*` tokens from an element's computed style, so the provider form follows the shop's\n * theme without the shop copying colors into JavaScript. Unsafe or empty values are skipped.\n */\nexport function readPaymentTheme(el: Element | null | undefined, tokens: Record<string, string> = PAYMENT_THEME_TOKENS): Record<string, string> {\n const out: Record<string, string> = {}\n if (!el || typeof getComputedStyle !== 'function') return out\n const style = getComputedStyle(el)\n for (const [cssVar, key] of Object.entries(tokens)) {\n const value = style.getPropertyValue(cssVar).trim()\n if (value && isSafeCssValue(value)) out[key] = value\n }\n return out\n}\n","import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'\nimport {\n generateIdempotencyKey,\n paymentErrorView,\n paymentIdempotencyKey,\n paymentMessages,\n paymentOutcome,\n type Money,\n type PaymentAttemptResult,\n type PaymentClient,\n type PaymentErrorKind,\n type PaymentErrorView,\n type PaymentMessages,\n type PaymentOutcome,\n type PaymentOutcomeKind,\n} from '@asteby/storefront'\nimport type { MountedPaymentForm, PaymentFormAdapter, PaymentTransport } from './adapter.js'\nimport { mercadoPagoBricksAdapter } from './mercadopago.js'\nimport { readPaymentTheme } from './theme.js'\n\nexport type EmbeddedPaymentStatus =\n | 'idle' // no client / disabled / not hydrated\n | 'loading' // loading the provider SDK and mounting\n | 'ready'\n | 'processing'\n | OutcomeStatus\n | 'network_error' // no answer: `retry()` repeats the SAME attempt\n | 'blocked' // 409/429 and the like: do not retry (see `error.kind`)\n | 'fallback' // the secure form is unusable: switch to a redirect payment\n\ntype OutcomeStatus = PaymentOutcomeKind\n\nexport type PaymentFallbackReason = 'sdk_timeout' | 'sdk_error' | 'form_error' | 'unsupported_provider' | 'no_client'\n\n/** Anonymous funnel events: no personal or card data. */\nexport type PaymentEvent =\n | { type: 'form_ready'; ms: number }\n | { type: 'form_failed'; reason: PaymentFallbackReason }\n | { type: 'tokenize_error' }\n | { type: 'submit' }\n | { type: 'result'; status: PaymentOutcomeKind; decline_code: string | null }\n | { type: 'error'; kind: PaymentErrorKind }\n | { type: 'retry' }\n\nexport type UseEmbeddedPaymentOptions = {\n /** Provider data from `paymentMethods[].client`. `null`/absent: nothing to mount (status `idle`). */\n client: PaymentClient | null | undefined\n /** The total computed by the server. The Brick is remounted when it changes. Never calculate it in the shop. */\n amount: Money\n transport: PaymentTransport\n /** Mount only while the card option is selected. Default true. */\n enabled?: boolean\n email?: string\n locale?: string\n /** Replaces the adapter chosen from `client.kind`. */\n adapter?: PaymentFormAdapter\n /** Extra adapters by `kind`. Mercado Pago is built in. */\n adapters?: Record<string, PaymentFormAdapter>\n /** CSP nonce for the inserted script. */\n nonce?: string\n /** Time to wait for the form to be ready before falling back. Default 8000. */\n sdkTimeoutMs?: number\n /** Automatic resubmits (same attempt) after a network failure before showing the retry button. Default 2. */\n autoRetries?: number\n /** Base delay for the backoff between automatic retries. Default 600. */\n retryDelayMs?: number\n /** Poll interval/timeout for a pending 3DS challenge or review when `transport.refresh` exists. */\n pollIntervalMs?: number\n pollTimeoutMs?: number\n /** Where the attempt id is kept so a reload/retry reuses it. Default `sessionStorage`; `null` disables. Never holds card data. */\n storage?: Pick<Storage, 'getItem' | 'setItem' | 'removeItem'> | null\n /** Scope of the stored attempt (e.g. the checkout or cart id). Default `default`. */\n scope?: string\n messages?: Partial<PaymentMessages>\n /** Called with the classified outcome of every definitive answer. */\n onResult?: (outcome: PaymentOutcome, result: PaymentAttemptResult) => void\n /** Called for `redirect` outcomes. Default: `location.assign(url)` (https only). */\n onRedirect?: (url: string) => void\n onFallback?: (reason: PaymentFallbackReason) => void\n onEvent?: (event: PaymentEvent) => void\n /** Overrides the theme read from `--sf-pay-*` tokens. */\n theme?: Record<string, string>\n /** Test hooks. */\n newAttemptId?: () => string\n}\n\nexport type EmbeddedPaymentState = {\n status: EmbeddedPaymentStatus\n /** Text to show for the current state (decline reason, review notice, error...). */\n message: string | null\n outcome: PaymentOutcome | null\n error: PaymentErrorView | null\n fallbackReason: PaymentFallbackReason | null\n attemptsLeft: number | null\n /** Id of the current attempt (stable across network retries). */\n attemptId: string | null\n /** `true` while loading, mounting or processing. */\n busy: boolean\n /** Attach to the element the provider renders into. */\n containerRef: (el: HTMLElement | null) => void\n containerId: string\n /** Tokenises and sends. No-ops while another submit is in flight (double click safe). */\n submit: () => Promise<void>\n /** Repeats the last submit with the SAME attempt after a network failure. */\n retry: () => Promise<void>\n /** After a rejection: clears the message (the form is remounted by the hook). */\n dismiss: () => void\n}\n\nconst DEFAULT_ADAPTERS: Record<string, PaymentFormAdapter> = {}\n\nfunction defaultAdapterFor(kind: string): PaymentFormAdapter | undefined {\n if (kind === 'mercadopago_bricks') return (DEFAULT_ADAPTERS[kind] ??= mercadoPagoBricksAdapter())\n return undefined\n}\n\nfunction safeStorage(): Pick<Storage, 'getItem' | 'setItem' | 'removeItem'> | null {\n try {\n return typeof sessionStorage !== 'undefined' ? sessionStorage : null\n } catch {\n return null\n }\n}\n\nconst sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms))\n\n/**\n * Embedded payment state machine for one card form.\n *\n * Guarantees:\n * - The amount is the server's: it is passed to the provider widget and echoed as `expected_total`; never computed.\n * - One idempotency key per attempt (`attempt`), kept in `storage`, reused on network retries and rotated only\n * after a definitive answer (a rejected card needs a new token, hence a new attempt).\n * - Card data never reaches this code or storage: only the provider token, held in memory until the answer.\n * - A double click returns the in-flight promise instead of sending twice.\n */\nexport function useEmbeddedPayment(options: UseEmbeddedPaymentOptions): EmbeddedPaymentState {\n const {\n client,\n amount,\n transport,\n enabled = true,\n locale,\n sdkTimeoutMs = 8000,\n autoRetries = 2,\n retryDelayMs = 600,\n pollIntervalMs = 2000,\n pollTimeoutMs = 60_000,\n scope = 'default',\n } = options\n const msgs = useMemo(() => paymentMessages(locale, options.messages), [locale, options.messages])\n const rawId = useId()\n const containerId = useMemo(() => `sf-pay-${rawId.replace(/[^a-zA-Z0-9_-]/g, '')}`, [rawId])\n\n const [status, setStatus] = useState<EmbeddedPaymentStatus>('idle')\n const [outcome, setOutcome] = useState<PaymentOutcome | null>(null)\n const [error, setError] = useState<PaymentErrorView | null>(null)\n const [fallbackReason, setFallbackReason] = useState<PaymentFallbackReason | null>(null)\n const [attemptsLeft, setAttemptsLeft] = useState<number | null>(null)\n const [attemptId, setAttemptId] = useState<string | null>(null)\n const [container, setContainer] = useState<HTMLElement | null>(null)\n const [mountKey, setMountKey] = useState(0)\n\n // Latest props without re-triggering effects.\n const live = useRef({ ...options, msgs })\n live.current = { ...options, msgs }\n const form = useRef<MountedPaymentForm | null>(null)\n const inFlight = useRef<Promise<void> | null>(null)\n const pendingData = useRef<{ provider_data: Record<string, unknown>; device_session_id?: string } | null>(null)\n const alive = useRef(true)\n const generation = useRef(0)\n const statusRef = useRef<EmbeddedPaymentStatus>('idle')\n statusRef.current = status\n\n useEffect(() => {\n alive.current = true\n return () => {\n alive.current = false\n }\n }, [])\n\n const storageKey = `sf:pay:attempt:${scope}`\n const store = options.storage === undefined ? safeStorage() : options.storage\n const emit = useCallback((e: PaymentEvent) => live.current.onEvent?.(e), [])\n\n const readAttempt = useCallback((): string => {\n try {\n const saved = store?.getItem(storageKey)\n if (saved) return saved\n } catch {\n /* private mode */\n }\n const fresh = (live.current.newAttemptId ?? generateIdempotencyKey)()\n try {\n store?.setItem(storageKey, fresh)\n } catch {\n /* keep in memory only */\n }\n return fresh\n }, [store, storageKey])\n\n const rotateAttempt = useCallback(() => {\n try {\n store?.removeItem(storageKey)\n } catch {\n /* ignore */\n }\n setAttemptId(null)\n }, [store, storageKey])\n\n const fallback = useCallback(\n (reason: PaymentFallbackReason) => {\n setFallbackReason(reason)\n setStatus('fallback')\n emit({ type: 'form_failed', reason })\n live.current.onFallback?.(reason)\n },\n [emit],\n )\n\n // Mount / remount the provider form. Re-runs when the server total, client or mount key changes.\n const amountKey = `${amount.amount}|${amount.currency_code}`\n const kind = client?.kind\n const publicKey = client?.public_key\n useEffect(() => {\n if (!enabled || !client) {\n setStatus((s) => (s === 'loading' || s === 'ready' ? 'idle' : s))\n return\n }\n const adapter = live.current.adapter ?? live.current.adapters?.[client.kind] ?? defaultAdapterFor(client.kind)\n if (!adapter) {\n fallback('unsupported_provider')\n return\n }\n if (!container) return\n const my = ++generation.current\n const started = Date.now()\n let mounted: MountedPaymentForm | null = null\n setStatus('loading')\n const stale = () => my !== generation.current || !alive.current\n // Fails this mount once: later callbacks of the same mount are ignored.\n const fail = (reason: PaymentFallbackReason) => {\n if (stale()) return\n generation.current++\n clearTimeout(timer)\n const m = mounted ?? form.current\n mounted = null\n form.current = null\n if (m) void Promise.resolve(m.unmount())\n fallback(reason)\n }\n const timer = setTimeout(() => {\n if (statusRef.current !== 'ready') fail('sdk_timeout')\n }, sdkTimeoutMs)\n\n container.id = containerId\n ;(async () => {\n try {\n await adapter.load(client, { ...(live.current.nonce ? { nonce: live.current.nonce } : {}), timeoutMs: sdkTimeoutMs })\n if (stale()) return\n const theme = live.current.theme ?? readPaymentTheme(container)\n const m = await adapter.mount({\n container,\n client,\n amount: live.current.amount,\n ...(live.current.email ? { email: live.current.email } : {}),\n ...(live.current.locale ? { locale: live.current.locale } : {}),\n theme,\n onReady: () => {\n if (stale()) return\n clearTimeout(timer)\n setStatus((s) => (s === 'loading' ? 'ready' : s))\n emit({ type: 'form_ready', ms: Date.now() - started })\n },\n onError: (e) => {\n if (stale()) return\n if (e.critical) fail('form_error')\n },\n })\n if (stale()) {\n void Promise.resolve(m.unmount())\n return\n }\n mounted = m\n form.current = m\n } catch (err) {\n fail(err instanceof Error && /timeout/i.test(err.message) ? 'sdk_timeout' : 'sdk_error')\n }\n })()\n\n return () => {\n clearTimeout(timer)\n generation.current++\n const m = mounted ?? form.current\n mounted = null\n form.current = null\n if (m) void Promise.resolve(m.unmount())\n }\n // `client` identity changes with every loader run; its identity-defining fields are listed instead.\n }, [enabled, container, kind, publicKey, amountKey, mountKey, sdkTimeoutMs, containerId])\n\n const finish = useCallback(\n (result: PaymentAttemptResult) => {\n const o = paymentOutcome(result, live.current.locale, live.current.messages)\n pendingData.current = null\n setOutcome(o)\n setError(null)\n setAttemptsLeft(o.attempts_left)\n setStatus(o.kind)\n emit({ type: 'result', status: o.kind, decline_code: o.decline_code })\n if (o.kind === 'approved') rotateAttempt()\n if (o.kind === 'rejected' || o.kind === 'cancelled') {\n // The token is single-use: a new attempt and a fresh form.\n rotateAttempt()\n setMountKey((k) => k + 1)\n }\n live.current.onResult?.(o, result)\n if (o.kind === 'redirect' && o.redirect_url) {\n if (live.current.onRedirect) live.current.onRedirect(o.redirect_url)\n else if (typeof window !== 'undefined') window.location.assign(o.redirect_url)\n }\n },\n [emit, rotateAttempt],\n )\n\n const send = useCallback(\n async (data: { provider_data: Record<string, unknown>; device_session_id?: string }, attempt: string) => {\n const ctl = new AbortController()\n const maxRetries = live.current.autoRetries ?? autoRetries\n for (let n = 0; ; n++) {\n try {\n const result = await transport.submit(\n {\n option: 'card',\n attempt,\n idempotencyKey: attempt,\n provider_data: data.provider_data,\n ...(data.device_session_id ? { device_session_id: data.device_session_id } : {}),\n expected_total: live.current.amount,\n },\n { signal: ctl.signal },\n )\n if (!alive.current) return\n finish(result)\n return\n } catch (err) {\n if (!alive.current) return\n const view = paymentErrorView(err, live.current.locale, live.current.messages)\n if (view.retrySameAttempt && n < maxRetries) {\n await sleep((live.current.retryDelayMs ?? retryDelayMs) * 2 ** n)\n if (!alive.current) return\n continue\n }\n emit({ type: 'error', kind: view.kind })\n setError(view)\n if (view.kind === 'network') {\n pendingData.current = data // memory only, for `retry()` with the same attempt\n setStatus('network_error')\n } else if (view.kind === 'price_mismatch') {\n pendingData.current = null\n rotateAttempt()\n setMountKey((k) => k + 1)\n setStatus('ready')\n } else if (view.kind === 'generic') {\n pendingData.current = null\n rotateAttempt()\n setMountKey((k) => k + 1)\n setStatus('ready')\n } else {\n pendingData.current = null\n setStatus('blocked')\n }\n return\n }\n }\n },\n [autoRetries, emit, finish, retryDelayMs, rotateAttempt, transport],\n )\n\n const submit = useCallback((): Promise<void> => {\n if (inFlight.current) return inFlight.current\n const m = form.current\n if (!m || (statusRef.current !== 'ready' && statusRef.current !== 'network_error')) return Promise.resolve()\n const run = (async () => {\n setStatus('processing')\n setError(null)\n setOutcome(null)\n emit({ type: 'submit' })\n let data\n try {\n data = await m.collect()\n } catch {\n emit({ type: 'tokenize_error' })\n setError({ kind: 'generic', message: live.current.msgs['error.card_data'], retrySameAttempt: false, canRetry: true })\n setStatus('ready')\n return\n }\n const attempt = readAttempt()\n setAttemptId(attempt)\n await send(data, attempt)\n })().finally(() => {\n inFlight.current = null\n })\n inFlight.current = run\n return run\n }, [emit, readAttempt, send])\n\n const retry = useCallback((): Promise<void> => {\n if (inFlight.current) return inFlight.current\n const data = pendingData.current\n if (!data) return submit()\n emit({ type: 'retry' })\n const run = (async () => {\n setStatus('processing')\n setError(null)\n const attempt = readAttempt()\n setAttemptId(attempt)\n await send(data, attempt)\n })().finally(() => {\n inFlight.current = null\n })\n inFlight.current = run\n return run\n }, [emit, readAttempt, send, submit])\n\n // Poll a pending 3DS challenge / review until it resolves or the window closes.\n useEffect(() => {\n if ((status !== 'challenge' && status !== 'in_review') || !transport.refresh) return\n let stop = false\n const ctl = new AbortController()\n const until = Date.now() + pollTimeoutMs\n ;(async () => {\n while (!stop && Date.now() < until) {\n await sleep(pollIntervalMs)\n if (stop || !alive.current) return\n try {\n const r = await transport.refresh!({ signal: ctl.signal })\n if (stop || !alive.current) return\n const o = paymentOutcome(r, live.current.locale, live.current.messages)\n if (o.kind !== status) {\n finish(r)\n return\n }\n } catch {\n /* keep polling until the window closes */\n }\n }\n })()\n return () => {\n stop = true\n ctl.abort()\n }\n }, [status, transport, pollIntervalMs, pollTimeoutMs, finish])\n\n const dismiss = useCallback(() => {\n setError(null)\n setOutcome((o) => (o?.kind === 'rejected' ? null : o))\n }, [])\n\n // After a rejection the hook remounts the form; the rejection text stays visible via `outcome` until the next submit.\n const message =\n status === 'processing'\n ? msgs['state.processing']\n : status === 'fallback'\n ? msgs['state.fallback']\n : (error?.message ?? outcome?.message ?? (status === 'loading' ? msgs['state.loading'] : null))\n\n return {\n status,\n message,\n outcome,\n error,\n fallbackReason,\n attemptsLeft,\n attemptId,\n busy: status === 'loading' || status === 'processing',\n containerRef: setContainer,\n containerId,\n submit,\n retry,\n dismiss,\n }\n}\n\nexport { paymentIdempotencyKey }\n","import { forwardRef, useEffect, useImperativeHandle, useRef, type CSSProperties, type ReactNode } from 'react'\nimport { formatMoney, formatVoucherExpiry, paymentMessages, type Money, type PaymentClient, type PaymentMessages, type PaymentOutcome } from '@asteby/storefront'\nimport { useModalDialog } from '../dialog.js'\nimport { useResolvedLocale } from '../locale.js'\nimport { useEmbeddedPayment, type EmbeddedPaymentState, type UseEmbeddedPaymentOptions } from './use-embedded-payment.js'\n\nexport type VoucherCardProps = {\n outcome: PaymentOutcome\n locale?: string\n messages?: Partial<PaymentMessages>\n className?: string\n}\n\n/**\n * Cash/SPEI voucher: point, exact amount, reference, barcode/CLABE and deadline, all from the server.\n * The link only renders for https URLs (already filtered by `paymentOutcome`).\n */\nexport function VoucherCard({ outcome, locale, messages, className }: VoucherCardProps) {\n const v = outcome.voucher\n if (!v) return null\n const m = paymentMessages(locale, messages)\n const expiry = formatVoucherExpiry(v.expires_at, locale, messages)\n return (\n <section className={className} data-sf-voucher aria-labelledby=\"sf-voucher-title\">\n <h3 id=\"sf-voucher-title\">{m['voucher.title']}</h3>\n <dl>\n <div>\n <dt>{m['voucher.point']}</dt>\n <dd>{v.payment_point}</dd>\n </div>\n {v.amount && (\n <div>\n <dt>{m['voucher.amount']}</dt>\n <dd>{formatMoney(v.amount, locale)}</dd>\n </div>\n )}\n <div>\n <dt>{m['voucher.reference']}</dt>\n <dd data-sf-voucher-reference>{v.reference}</dd>\n </div>\n {v.clabe && (\n <div>\n <dt>{m['voucher.clabe']}</dt>\n <dd>{v.clabe}</dd>\n </div>\n )}\n {v.barcode && (\n <div>\n <dt>{m['voucher.barcode']}</dt>\n <dd>{v.barcode}</dd>\n </div>\n )}\n </dl>\n {expiry && <p data-sf-voucher-expiry>{expiry}</p>}\n {v.voucher_url && (\n <p>\n <a href={v.voucher_url} target=\"_blank\" rel=\"noopener noreferrer\">\n {m['voucher.open']}\n </a>\n </p>\n )}\n <p>{m['voucher.email']}</p>\n </section>\n )\n}\n\nexport type PaymentChallengeProps = {\n outcome: PaymentOutcome\n locale?: string\n messages?: Partial<PaymentMessages>\n /** Replace the default iframe (e.g. mount the provider's status screen). */\n render?: (outcome: PaymentOutcome) => ReactNode\n onCancel?: () => void\n}\n\n/** 3DS inside the page: a modal dialog with title and focus trap. Default content is the bank's https iframe. */\nexport function PaymentChallenge({ outcome, locale, messages, render, onCancel }: PaymentChallengeProps) {\n const m = paymentMessages(locale, messages)\n const { ref } = useModalDialog({ open: true, onClose: () => onCancel?.() })\n const url = outcome.challenge?.url\n return (\n <dialog ref={ref} aria-labelledby=\"sf-challenge-title\" data-sf-challenge>\n <div>\n <h2 id=\"sf-challenge-title\" data-sf-autofocus tabIndex={-1}>\n {m['challenge.title']}\n </h2>\n {render ? (\n render(outcome)\n ) : url ? (\n <iframe src={url} title={m['challenge.title']} style={{ width: '100%', minHeight: 420, border: 0 }} />\n ) : (\n <p>{m['state.challenge']}</p>\n )}\n {onCancel && (\n <button type=\"button\" onClick={onCancel} style={{ minWidth: 44, minHeight: 44 }}>\n {m['action.cancel']}\n </button>\n )}\n </div>\n </dialog>\n )\n}\n\nexport type PaymentBrickHandle = EmbeddedPaymentState\n\nexport type PaymentBrickProps = Omit<UseEmbeddedPaymentOptions, 'amount'> & {\n /** The server's total. Shown on the button and passed to the provider widget. */\n amount: Money\n /** When set, renders the shop's pay button with this label. Otherwise drive it through the ref. */\n submitLabel?: ReactNode\n /** Hide the total next to the label. */\n hideAmountInButton?: boolean\n /** Rendered instead of the built-in voucher card. */\n renderVoucher?: (outcome: PaymentOutcome) => ReactNode\n renderChallenge?: (outcome: PaymentOutcome) => ReactNode\n /** Height reserved for the provider form so the page does not jump. Default 360. */\n minHeight?: number | string\n className?: string\n style?: CSSProperties\n}\n\n/**\n * Card form for an embedded payment. Headless: no styles of its own, only `data-*` hooks and CSS variables\n * (`--sf-pay-*`, read for the provider widget; `--sf-pay-min-height` for the reserved height).\n *\n * Accessibility: the container is labelled and `aria-busy` while loading; every message goes through one\n * `role=\"status\"` region (or `role=\"alert\"` for errors, which also takes focus); the button explains why it is\n * busy and never silently disables.\n *\n * Use the `ref` to get the same state the hook returns (`submit`, `retry`, `status`...) when the shop owns the button.\n */\nexport const PaymentBrick = forwardRef<PaymentBrickHandle, PaymentBrickProps>(function PaymentBrick(props, ref) {\n const { submitLabel, hideAmountInButton, renderVoucher, renderChallenge, minHeight = 360, className, style, ...hookOptions } = props\n const locale = useResolvedLocale(props.locale)\n const state = useEmbeddedPayment({ ...hookOptions, locale })\n useImperativeHandle(ref, () => state)\n const m = paymentMessages(locale, props.messages)\n const alertRef = useRef<HTMLDivElement | null>(null)\n\n const isError = !!state.error || state.outcome?.kind === 'rejected' || state.status === 'blocked'\n // Move focus to the explanation when a problem appears.\n useEffect(() => {\n if (isError) alertRef.current?.focus()\n }, [isError, state.message])\n\n if (state.status === 'fallback') {\n return (\n <div className={className} style={style} data-sf-pay-status=\"fallback\">\n <p role=\"status\" data-sf-pay-fallback>\n {m['state.fallback']}\n </p>\n </div>\n )\n }\n\n const outcome = state.outcome\n const showForm = state.status !== 'approved' && state.status !== 'voucher' && state.status !== 'in_review' && state.status !== 'redirect' && state.status !== 'expired'\n const busy = state.busy\n const total = formatMoney(props.amount, locale)\n const label = state.status === 'processing' ? m['state.processing'] : (submitLabel ?? m['action.pay'])\n\n return (\n <div className={className} style={style} data-sf-pay-status={state.status}>\n {showForm && (\n <div\n ref={state.containerRef}\n role=\"group\"\n aria-label={m['form.label']}\n aria-busy={state.status === 'loading' || state.status === 'processing'}\n data-sf-pay-container\n style={{ minHeight: `var(--sf-pay-min-height, ${typeof minHeight === 'number' ? `${minHeight}px` : minHeight})` }}\n />\n )}\n\n {isError ? (\n <div ref={alertRef} role=\"alert\" tabIndex={-1} data-sf-pay-alert data-sf-pay-code={state.error?.kind ?? outcome?.decline_code ?? undefined}>\n {state.message}\n {state.status === 'network_error' && (\n <button type=\"button\" onClick={() => void state.retry()} style={{ minHeight: 44 }}>\n {m['action.retry']}\n </button>\n )}\n </div>\n ) : (\n <p role=\"status\" aria-live=\"polite\" data-sf-pay-message>\n {state.message}\n </p>\n )}\n\n {outcome?.kind === 'voucher' && (renderVoucher ? renderVoucher(outcome) : <VoucherCard outcome={outcome} locale={locale} {...(props.messages ? { messages: props.messages } : {})} />)}\n {outcome?.kind === 'challenge' && (\n <PaymentChallenge outcome={outcome} locale={locale} {...(props.messages ? { messages: props.messages } : {})} {...(renderChallenge ? { render: renderChallenge } : {})} />\n )}\n\n {submitLabel !== undefined && showForm && (\n <button\n type=\"button\"\n onClick={() => void state.submit()}\n aria-busy={busy}\n aria-disabled={state.status !== 'ready'}\n data-sf-pay-submit\n style={{ minHeight: 44 }}\n >\n {label}\n {!hideAmountInButton && state.status !== 'processing' && <> · {total}</>}\n </button>\n )}\n </div>\n )\n})\n\nexport type { PaymentClient }\n","/**\n * Replaceable ports of the embedded payment. The shop (or another provider)\n * implements these; the hook and component only talk to them.\n *\n * Two ports, on purpose:\n * - `PaymentFormAdapter` = the provider SDK in the browser (Mercado Pago Bricks, Stripe Elements...).\n * It mounts a secure form and returns only what the SDK allows to travel (a one-use token).\n * - `PaymentTransport` = how the browser reaches the shop SERVER. The browser never calls OPS: the shop's\n * route forwards to `client.checkouts.pay(...)` with its private token. The HTTP contract between\n * the shop route and OPS lives in `@asteby/storefront` (`checkouts.pay`); the shop route is free to\n * shape its own JSON as long as it answers with a `PaymentAttemptResult`.\n */\nimport type { Money, PaymentAttemptResult, PaymentClient } from '@asteby/storefront'\n\nexport type PaymentFormError = {\n /** `true`: the form cannot be used (SDK blocked, iframe failed). The hook falls back to a redirect. */\n critical: boolean\n /** Short, non-sensitive text for logs. Never card data. */\n message?: string\n}\n\nexport type PaymentFormMountOptions = {\n /** Element the provider renders into. Its `id` is set by the hook. */\n container: HTMLElement\n client: PaymentClient\n /** Total computed by the server. Only passed to the provider widget; never calculated here. */\n amount: Money\n email?: string\n locale?: string\n /** Visual tokens read from CSS variables (see `readPaymentTheme`). */\n theme?: Record<string, string>\n onReady: () => void\n onError: (error: PaymentFormError) => void\n}\n\n/** What a mounted form hands back at submit time. */\nexport type PaymentFormData = {\n /** Sent to the server as `provider_data`. Must never contain amounts or raw card data. */\n provider_data: Record<string, unknown>\n /** Anti-fraud device fingerprint, if the SDK exposes one. */\n device_session_id?: string\n}\n\nexport interface MountedPaymentForm {\n /** Tokenises the card inside the provider iframes. Rejects when the form is invalid (the provider shows the field errors). */\n collect(): Promise<PaymentFormData>\n unmount(): void | Promise<void>\n}\n\nexport interface PaymentFormAdapter {\n /** `PaymentClient.kind` this adapter serves. */\n readonly kind: string\n /** Loads the provider script (once). Rejects on timeout, blocked script or invalid URL. */\n load(client: PaymentClient, options: { nonce?: string; timeoutMs: number }): Promise<void>\n mount(options: PaymentFormMountOptions): Promise<MountedPaymentForm>\n}\n\n/** Everything the shop server needs for one attempt. No card data: only the provider token and choices. */\nexport type PaymentSubmitRequest = {\n option: 'card'\n /** Stable per attempt: the same attempt always carries the same key, so a retry never charges twice. */\n attempt: string\n idempotencyKey: string\n provider_data: Record<string, unknown>\n device_session_id?: string\n /** The total the buyer saw (the server's own number). The server answers 422 `price_mismatch` if it differs. */\n expected_total: Money\n}\n\nexport type PaymentTransport = {\n submit(request: PaymentSubmitRequest, context: { signal: AbortSignal }): Promise<PaymentAttemptResult>\n /** Optional: re-reads the checkout state (3DS challenge, \"in review\"). Same result shape as `submit`. */\n refresh?(context: { signal: AbortSignal }): Promise<PaymentAttemptResult>\n}\n\n/** Error thrown by `createFetchTransport` for non-2xx answers; compatible with `paymentErrorView`. */\nexport class PaymentHttpError extends Error {\n override readonly name = 'PaymentHttpError'\n constructor(\n readonly status: number,\n readonly code: string,\n message?: string,\n /** Raw `error.details` (e.g. the new `cost` of a `price_mismatch`); untrusted shape. */\n readonly details?: unknown,\n ) {\n super(message ?? code)\n }\n}\n\nexport type FetchTransportOptions = {\n fetch?: typeof fetch\n headers?: Record<string, string>\n /** Default `same-origin`. */\n credentials?: RequestCredentials\n /** Shapes the JSON body; the default sends the request as is. */\n buildBody?: (request: PaymentSubmitRequest) => unknown\n /** Same-origin URL that re-reads the state (enables `refresh`). */\n refreshUrl?: string\n}\n\nasync function parse(res: Response): Promise<unknown> {\n const text = await res.text()\n if (!text) return null\n try {\n return JSON.parse(text)\n } catch {\n return null\n }\n}\n\n/**\n * Transport to a same-origin shop route (`POST url` with JSON). Maps `{ error: { code, message, details } }`\n * answers to `PaymentHttpError`. Network failures surface as the original `TypeError`, which the\n * hook treats as retryable with the same attempt.\n */\nexport function createFetchTransport(url: string, options: FetchTransportOptions = {}): PaymentTransport {\n const doFetch = (u: string, init: RequestInit) => (options.fetch ?? globalThis.fetch.bind(globalThis))(u, init)\n async function call(u: string, init: RequestInit): Promise<PaymentAttemptResult> {\n const res = await doFetch(u, { credentials: options.credentials ?? 'same-origin', ...init })\n const body = (await parse(res)) as { error?: { code?: string; message?: string; details?: unknown } } | PaymentAttemptResult | null\n if (!res.ok) {\n const e = (body as { error?: { code?: string; message?: string; details?: unknown } } | null)?.error\n throw new PaymentHttpError(res.status, e?.code ?? 'server_error', e?.message, e?.details)\n }\n const result = body as PaymentAttemptResult | null\n if (!result || typeof result !== 'object' || !result.payment || typeof result.payment.status !== 'string') {\n throw new PaymentHttpError(502, 'invalid_response', 'Unexpected payment response')\n }\n return result\n }\n return {\n submit: (request, { signal }) =>\n call(url, {\n method: 'POST',\n signal,\n headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'Idempotency-Key': request.idempotencyKey, ...options.headers },\n body: JSON.stringify(options.buildBody ? options.buildBody(request) : request),\n }),\n ...(options.refreshUrl\n ? {\n refresh: ({ signal }: { signal: AbortSignal }) =>\n call(options.refreshUrl!, { method: 'POST', signal, headers: { Accept: 'application/json', ...options.headers } }),\n }\n : {}),\n }\n}\n","import type { PaymentClient } from '@asteby/storefront'\n\nexport type PaymentCspOptions = {\n /** Per-request nonce; also set it on the inserted `<script>` and on `<Scripts nonce>`. */\n nonce?: string\n /** Extra origins by directive (e.g. your image CDN). */\n extra?: { script?: string[]; frame?: string[]; connect?: string[]; img?: string[]; form?: string[] }\n /** `report-uri` / `report-to` target for the report-only rollout. */\n reportUri?: string\n}\n\n/** One origin source: `https://host`, `https://*.host`, optional port. Anything else (`;`, spaces, `'unsafe-eval'`) is dropped. */\nconst ORIGIN = /^https:\\/\\/(\\*\\.)?[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*(:\\d{1,5})?$/i\n\nfunction origins(...lists: (readonly string[] | undefined)[]): string[] {\n const out = new Set<string>()\n for (const list of lists) for (const o of list ?? []) if (ORIGIN.test(o)) out.add(o)\n return [...out]\n}\n\n/**\n * Builds the Content-Security-Policy for the payment routes from what each provider declares\n * (`PaymentClient.csp`), so the shop never hard-codes provider hosts. Meant for `/pagar` only,\n * never for the whole site. Roll out as `Content-Security-Policy-Report-Only` first.\n *\n * No SRI on purpose: provider SDK URLs are unversioned and a hash would break payments on any update.\n */\nexport function paymentCsp(clients: readonly (PaymentClient | null | undefined)[], options: PaymentCspOptions = {}): string {\n const list = clients.filter((c): c is PaymentClient => !!c)\n const pick = (k: keyof NonNullable<PaymentClient['csp']>) => list.map((c) => c.csp?.[k])\n const nonce = options.nonce && /^[A-Za-z0-9+/=_-]+$/.test(options.nonce) ? options.nonce : undefined\n const sdkOrigins = list.flatMap((c) => {\n try {\n const u = new URL(c.sdk_url)\n return u.protocol === 'https:' ? [u.origin] : []\n } catch {\n return []\n }\n })\n const dir = (name: string, values: string[]) => `${name} ${values.join(' ')}`\n const parts = [\n \"default-src 'self'\",\n dir('script-src', [\"'self'\", ...(nonce ? [`'nonce-${nonce}'`] : []), ...origins(sdkOrigins, ...pick('script'), options.extra?.script)]),\n dir('frame-src', origins(...pick('frame'), options.extra?.frame).length ? origins(...pick('frame'), options.extra?.frame) : [\"'none'\"]),\n dir('connect-src', [\"'self'\", ...origins(...pick('connect'), options.extra?.connect)]),\n dir('img-src', [\"'self'\", 'data:', ...origins(...pick('img'), options.extra?.img)]),\n \"style-src 'self' 'unsafe-inline'\",\n dir('form-action', [\"'self'\", ...origins(...pick('form'), options.extra?.form)]),\n \"frame-ancestors 'none'\",\n \"base-uri 'self'\",\n \"object-src 'none'\",\n ]\n if (options.reportUri && /^(https:\\/\\/|\\/)[^\\s;,]+$/.test(options.reportUri)) parts.push(`report-uri ${options.reportUri}`)\n return parts.join('; ')\n}\n\n/** `Content-Security-Policy` or, during the rollout week, `Content-Security-Policy-Report-Only`. */\nexport function paymentCspHeaderName(reportOnly: boolean): string {\n return reportOnly ? 'Content-Security-Policy-Report-Only' : 'Content-Security-Policy'\n}\n"]}
@@ -0,0 +1,364 @@
1
+ import * as react from 'react';
2
+ import { ReactNode, CSSProperties } from 'react';
3
+ import { Money, PaymentAttemptResult, PaymentClient, PaymentOutcomeKind, PaymentOutcome, PaymentErrorView, PaymentMessages, PaymentErrorKind } from '@asteby/storefront';
4
+
5
+ /**
6
+ * Replaceable ports of the embedded payment. The shop (or another provider)
7
+ * implements these; the hook and component only talk to them.
8
+ *
9
+ * Two ports, on purpose:
10
+ * - `PaymentFormAdapter` = the provider SDK in the browser (Mercado Pago Bricks, Stripe Elements...).
11
+ * It mounts a secure form and returns only what the SDK allows to travel (a one-use token).
12
+ * - `PaymentTransport` = how the browser reaches the shop SERVER. The browser never calls OPS: the shop's
13
+ * route forwards to `client.checkouts.pay(...)` with its private token. The HTTP contract between
14
+ * the shop route and OPS lives in `@asteby/storefront` (`checkouts.pay`); the shop route is free to
15
+ * shape its own JSON as long as it answers with a `PaymentAttemptResult`.
16
+ */
17
+
18
+ type PaymentFormError = {
19
+ /** `true`: the form cannot be used (SDK blocked, iframe failed). The hook falls back to a redirect. */
20
+ critical: boolean;
21
+ /** Short, non-sensitive text for logs. Never card data. */
22
+ message?: string;
23
+ };
24
+ type PaymentFormMountOptions = {
25
+ /** Element the provider renders into. Its `id` is set by the hook. */
26
+ container: HTMLElement;
27
+ client: PaymentClient;
28
+ /** Total computed by the server. Only passed to the provider widget; never calculated here. */
29
+ amount: Money;
30
+ email?: string;
31
+ locale?: string;
32
+ /** Visual tokens read from CSS variables (see `readPaymentTheme`). */
33
+ theme?: Record<string, string>;
34
+ onReady: () => void;
35
+ onError: (error: PaymentFormError) => void;
36
+ };
37
+ /** What a mounted form hands back at submit time. */
38
+ type PaymentFormData = {
39
+ /** Sent to the server as `provider_data`. Must never contain amounts or raw card data. */
40
+ provider_data: Record<string, unknown>;
41
+ /** Anti-fraud device fingerprint, if the SDK exposes one. */
42
+ device_session_id?: string;
43
+ };
44
+ interface MountedPaymentForm {
45
+ /** Tokenises the card inside the provider iframes. Rejects when the form is invalid (the provider shows the field errors). */
46
+ collect(): Promise<PaymentFormData>;
47
+ unmount(): void | Promise<void>;
48
+ }
49
+ interface PaymentFormAdapter {
50
+ /** `PaymentClient.kind` this adapter serves. */
51
+ readonly kind: string;
52
+ /** Loads the provider script (once). Rejects on timeout, blocked script or invalid URL. */
53
+ load(client: PaymentClient, options: {
54
+ nonce?: string;
55
+ timeoutMs: number;
56
+ }): Promise<void>;
57
+ mount(options: PaymentFormMountOptions): Promise<MountedPaymentForm>;
58
+ }
59
+ /** Everything the shop server needs for one attempt. No card data: only the provider token and choices. */
60
+ type PaymentSubmitRequest = {
61
+ option: 'card';
62
+ /** Stable per attempt: the same attempt always carries the same key, so a retry never charges twice. */
63
+ attempt: string;
64
+ idempotencyKey: string;
65
+ provider_data: Record<string, unknown>;
66
+ device_session_id?: string;
67
+ /** The total the buyer saw (the server's own number). The server answers 422 `price_mismatch` if it differs. */
68
+ expected_total: Money;
69
+ };
70
+ type PaymentTransport = {
71
+ submit(request: PaymentSubmitRequest, context: {
72
+ signal: AbortSignal;
73
+ }): Promise<PaymentAttemptResult>;
74
+ /** Optional: re-reads the checkout state (3DS challenge, "in review"). Same result shape as `submit`. */
75
+ refresh?(context: {
76
+ signal: AbortSignal;
77
+ }): Promise<PaymentAttemptResult>;
78
+ };
79
+ /** Error thrown by `createFetchTransport` for non-2xx answers; compatible with `paymentErrorView`. */
80
+ declare class PaymentHttpError extends Error {
81
+ readonly status: number;
82
+ readonly code: string;
83
+ /** Raw `error.details` (e.g. the new `cost` of a `price_mismatch`); untrusted shape. */
84
+ readonly details?: unknown | undefined;
85
+ readonly name = "PaymentHttpError";
86
+ constructor(status: number, code: string, message?: string,
87
+ /** Raw `error.details` (e.g. the new `cost` of a `price_mismatch`); untrusted shape. */
88
+ details?: unknown | undefined);
89
+ }
90
+ type FetchTransportOptions = {
91
+ fetch?: typeof fetch;
92
+ headers?: Record<string, string>;
93
+ /** Default `same-origin`. */
94
+ credentials?: RequestCredentials;
95
+ /** Shapes the JSON body; the default sends the request as is. */
96
+ buildBody?: (request: PaymentSubmitRequest) => unknown;
97
+ /** Same-origin URL that re-reads the state (enables `refresh`). */
98
+ refreshUrl?: string;
99
+ };
100
+ /**
101
+ * Transport to a same-origin shop route (`POST url` with JSON). Maps `{ error: { code, message, details } }`
102
+ * answers to `PaymentHttpError`. Network failures surface as the original `TypeError`, which the
103
+ * hook treats as retryable with the same attempt.
104
+ */
105
+ declare function createFetchTransport(url: string, options?: FetchTransportOptions): PaymentTransport;
106
+
107
+ type EmbeddedPaymentStatus = 'idle' | 'loading' | 'ready' | 'processing' | OutcomeStatus | 'network_error' | 'blocked' | 'fallback';
108
+ type OutcomeStatus = PaymentOutcomeKind;
109
+ type PaymentFallbackReason = 'sdk_timeout' | 'sdk_error' | 'form_error' | 'unsupported_provider' | 'no_client';
110
+ /** Anonymous funnel events: no personal or card data. */
111
+ type PaymentEvent = {
112
+ type: 'form_ready';
113
+ ms: number;
114
+ } | {
115
+ type: 'form_failed';
116
+ reason: PaymentFallbackReason;
117
+ } | {
118
+ type: 'tokenize_error';
119
+ } | {
120
+ type: 'submit';
121
+ } | {
122
+ type: 'result';
123
+ status: PaymentOutcomeKind;
124
+ decline_code: string | null;
125
+ } | {
126
+ type: 'error';
127
+ kind: PaymentErrorKind;
128
+ } | {
129
+ type: 'retry';
130
+ };
131
+ type UseEmbeddedPaymentOptions = {
132
+ /** Provider data from `paymentMethods[].client`. `null`/absent: nothing to mount (status `idle`). */
133
+ client: PaymentClient | null | undefined;
134
+ /** The total computed by the server. The Brick is remounted when it changes. Never calculate it in the shop. */
135
+ amount: Money;
136
+ transport: PaymentTransport;
137
+ /** Mount only while the card option is selected. Default true. */
138
+ enabled?: boolean;
139
+ email?: string;
140
+ locale?: string;
141
+ /** Replaces the adapter chosen from `client.kind`. */
142
+ adapter?: PaymentFormAdapter;
143
+ /** Extra adapters by `kind`. Mercado Pago is built in. */
144
+ adapters?: Record<string, PaymentFormAdapter>;
145
+ /** CSP nonce for the inserted script. */
146
+ nonce?: string;
147
+ /** Time to wait for the form to be ready before falling back. Default 8000. */
148
+ sdkTimeoutMs?: number;
149
+ /** Automatic resubmits (same attempt) after a network failure before showing the retry button. Default 2. */
150
+ autoRetries?: number;
151
+ /** Base delay for the backoff between automatic retries. Default 600. */
152
+ retryDelayMs?: number;
153
+ /** Poll interval/timeout for a pending 3DS challenge or review when `transport.refresh` exists. */
154
+ pollIntervalMs?: number;
155
+ pollTimeoutMs?: number;
156
+ /** Where the attempt id is kept so a reload/retry reuses it. Default `sessionStorage`; `null` disables. Never holds card data. */
157
+ storage?: Pick<Storage, 'getItem' | 'setItem' | 'removeItem'> | null;
158
+ /** Scope of the stored attempt (e.g. the checkout or cart id). Default `default`. */
159
+ scope?: string;
160
+ messages?: Partial<PaymentMessages>;
161
+ /** Called with the classified outcome of every definitive answer. */
162
+ onResult?: (outcome: PaymentOutcome, result: PaymentAttemptResult) => void;
163
+ /** Called for `redirect` outcomes. Default: `location.assign(url)` (https only). */
164
+ onRedirect?: (url: string) => void;
165
+ onFallback?: (reason: PaymentFallbackReason) => void;
166
+ onEvent?: (event: PaymentEvent) => void;
167
+ /** Overrides the theme read from `--sf-pay-*` tokens. */
168
+ theme?: Record<string, string>;
169
+ /** Test hooks. */
170
+ newAttemptId?: () => string;
171
+ };
172
+ type EmbeddedPaymentState = {
173
+ status: EmbeddedPaymentStatus;
174
+ /** Text to show for the current state (decline reason, review notice, error...). */
175
+ message: string | null;
176
+ outcome: PaymentOutcome | null;
177
+ error: PaymentErrorView | null;
178
+ fallbackReason: PaymentFallbackReason | null;
179
+ attemptsLeft: number | null;
180
+ /** Id of the current attempt (stable across network retries). */
181
+ attemptId: string | null;
182
+ /** `true` while loading, mounting or processing. */
183
+ busy: boolean;
184
+ /** Attach to the element the provider renders into. */
185
+ containerRef: (el: HTMLElement | null) => void;
186
+ containerId: string;
187
+ /** Tokenises and sends. No-ops while another submit is in flight (double click safe). */
188
+ submit: () => Promise<void>;
189
+ /** Repeats the last submit with the SAME attempt after a network failure. */
190
+ retry: () => Promise<void>;
191
+ /** After a rejection: clears the message (the form is remounted by the hook). */
192
+ dismiss: () => void;
193
+ };
194
+ /**
195
+ * Embedded payment state machine for one card form.
196
+ *
197
+ * Guarantees:
198
+ * - The amount is the server's: it is passed to the provider widget and echoed as `expected_total`; never computed.
199
+ * - One idempotency key per attempt (`attempt`), kept in `storage`, reused on network retries and rotated only
200
+ * after a definitive answer (a rejected card needs a new token, hence a new attempt).
201
+ * - Card data never reaches this code or storage: only the provider token, held in memory until the answer.
202
+ * - A double click returns the in-flight promise instead of sending twice.
203
+ */
204
+ declare function useEmbeddedPayment(options: UseEmbeddedPaymentOptions): EmbeddedPaymentState;
205
+
206
+ type VoucherCardProps = {
207
+ outcome: PaymentOutcome;
208
+ locale?: string;
209
+ messages?: Partial<PaymentMessages>;
210
+ className?: string;
211
+ };
212
+ /**
213
+ * Cash/SPEI voucher: point, exact amount, reference, barcode/CLABE and deadline, all from the server.
214
+ * The link only renders for https URLs (already filtered by `paymentOutcome`).
215
+ */
216
+ declare function VoucherCard({ outcome, locale, messages, className }: VoucherCardProps): react.JSX.Element | null;
217
+ type PaymentChallengeProps = {
218
+ outcome: PaymentOutcome;
219
+ locale?: string;
220
+ messages?: Partial<PaymentMessages>;
221
+ /** Replace the default iframe (e.g. mount the provider's status screen). */
222
+ render?: (outcome: PaymentOutcome) => ReactNode;
223
+ onCancel?: () => void;
224
+ };
225
+ /** 3DS inside the page: a modal dialog with title and focus trap. Default content is the bank's https iframe. */
226
+ declare function PaymentChallenge({ outcome, locale, messages, render, onCancel }: PaymentChallengeProps): react.JSX.Element;
227
+ type PaymentBrickHandle = EmbeddedPaymentState;
228
+ type PaymentBrickProps = Omit<UseEmbeddedPaymentOptions, 'amount'> & {
229
+ /** The server's total. Shown on the button and passed to the provider widget. */
230
+ amount: Money;
231
+ /** When set, renders the shop's pay button with this label. Otherwise drive it through the ref. */
232
+ submitLabel?: ReactNode;
233
+ /** Hide the total next to the label. */
234
+ hideAmountInButton?: boolean;
235
+ /** Rendered instead of the built-in voucher card. */
236
+ renderVoucher?: (outcome: PaymentOutcome) => ReactNode;
237
+ renderChallenge?: (outcome: PaymentOutcome) => ReactNode;
238
+ /** Height reserved for the provider form so the page does not jump. Default 360. */
239
+ minHeight?: number | string;
240
+ className?: string;
241
+ style?: CSSProperties;
242
+ };
243
+ /**
244
+ * Card form for an embedded payment. Headless: no styles of its own, only `data-*` hooks and CSS variables
245
+ * (`--sf-pay-*`, read for the provider widget; `--sf-pay-min-height` for the reserved height).
246
+ *
247
+ * Accessibility: the container is labelled and `aria-busy` while loading; every message goes through one
248
+ * `role="status"` region (or `role="alert"` for errors, which also takes focus); the button explains why it is
249
+ * busy and never silently disables.
250
+ *
251
+ * Use the `ref` to get the same state the hook returns (`submit`, `retry`, `status`...) when the shop owns the button.
252
+ */
253
+ declare const PaymentBrick: react.ForwardRefExoticComponent<Omit<UseEmbeddedPaymentOptions, "amount"> & {
254
+ /** The server's total. Shown on the button and passed to the provider widget. */
255
+ amount: Money;
256
+ /** When set, renders the shop's pay button with this label. Otherwise drive it through the ref. */
257
+ submitLabel?: ReactNode;
258
+ /** Hide the total next to the label. */
259
+ hideAmountInButton?: boolean;
260
+ /** Rendered instead of the built-in voucher card. */
261
+ renderVoucher?: (outcome: PaymentOutcome) => ReactNode;
262
+ renderChallenge?: (outcome: PaymentOutcome) => ReactNode;
263
+ /** Height reserved for the provider form so the page does not jump. Default 360. */
264
+ minHeight?: number | string;
265
+ className?: string;
266
+ style?: CSSProperties;
267
+ } & react.RefAttributes<EmbeddedPaymentState>>;
268
+
269
+ /** The `PaymentClient.kind` the addon `mercadopago` declares. */
270
+ declare const MERCADOPAGO_BRICKS_KIND = "mercadopago_bricks";
271
+ type MpController = {
272
+ getFormData(): Promise<Record<string, unknown> | undefined | null>;
273
+ unmount(): void | Promise<void>;
274
+ };
275
+ type MpBricks = {
276
+ create(brick: string, containerId: string, settings: Record<string, unknown>): Promise<MpController>;
277
+ };
278
+ type MercadoPagoCtor = new (publicKey: string, options?: {
279
+ locale?: string;
280
+ }) => {
281
+ bricks(): MpBricks;
282
+ };
283
+ type MercadoPagoAdapterOptions = {
284
+ /** Exact origins allowed for `sdk_url`. Default: Mercado Pago's SDK origin only. */
285
+ allowedSdkOrigins?: readonly string[];
286
+ /** Resolves the SDK constructor. Default: `window.MercadoPago`. Inject a fake in tests. */
287
+ getSdk?: () => MercadoPagoCtor | undefined;
288
+ /** Reads the anti-fraud device id. Default: `window.MP_DEVICE_SESSION_ID`. */
289
+ getDeviceSessionId?: () => string | undefined;
290
+ };
291
+ /**
292
+ * The only fields that may leave the browser, and the only place that decides it. Anything else the SDK returns
293
+ * (notably `transaction_amount`, the amount: the server owns it) is dropped. Strings only, bounded length.
294
+ */
295
+ declare function sanitizeMercadoPagoFormData(data: Record<string, unknown> | null | undefined): Record<string, unknown>;
296
+ /**
297
+ * Card Payment Brick adapter. The payment button is hidden: the shop's own button calls `collect()` (MP's
298
+ * `getFormData()`), which tokenises inside MP's iframes. Card data never touches this code.
299
+ */
300
+ declare function mercadoPagoBricksAdapter(options?: MercadoPagoAdapterOptions): PaymentFormAdapter;
301
+
302
+ /**
303
+ * Loads a provider script once, with timeout, CSP nonce and an origin allowlist.
304
+ * The URL comes from the server (`PaymentClient.sdk_url`) but is still checked:
305
+ * https only and, when `allowedOrigins` is given, an exact origin match.
306
+ */
307
+ type LoadScriptOptions = {
308
+ nonce?: string;
309
+ timeoutMs: number;
310
+ /** Exact origins allowed for the script (`https://sdk.mercadopago.com`). Omitted: any https origin. */
311
+ allowedOrigins?: readonly string[];
312
+ /** `true` when the SDK global is already there (skips the insert). */
313
+ isLoaded?: () => boolean;
314
+ document?: Document;
315
+ };
316
+ declare function loadPaymentSdk(url: string, options: LoadScriptOptions): Promise<void>;
317
+ /** Test helper: forgets the loaded-script cache. */
318
+ declare function resetPaymentSdkCache(): void;
319
+
320
+ type PaymentCspOptions = {
321
+ /** Per-request nonce; also set it on the inserted `<script>` and on `<Scripts nonce>`. */
322
+ nonce?: string;
323
+ /** Extra origins by directive (e.g. your image CDN). */
324
+ extra?: {
325
+ script?: string[];
326
+ frame?: string[];
327
+ connect?: string[];
328
+ img?: string[];
329
+ form?: string[];
330
+ };
331
+ /** `report-uri` / `report-to` target for the report-only rollout. */
332
+ reportUri?: string;
333
+ };
334
+ /**
335
+ * Builds the Content-Security-Policy for the payment routes from what each provider declares
336
+ * (`PaymentClient.csp`), so the shop never hard-codes provider hosts. Meant for `/pagar` only,
337
+ * never for the whole site. Roll out as `Content-Security-Policy-Report-Only` first.
338
+ *
339
+ * No SRI on purpose: provider SDK URLs are unversioned and a hash would break payments on any update.
340
+ */
341
+ declare function paymentCsp(clients: readonly (PaymentClient | null | undefined)[], options?: PaymentCspOptions): string;
342
+ /** `Content-Security-Policy` or, during the rollout week, `Content-Security-Policy-Report-Only`. */
343
+ declare function paymentCspHeaderName(reportOnly: boolean): string;
344
+
345
+ /** CSS custom properties (set by the shop in its stylesheet) -> provider widget variables. */
346
+ declare const PAYMENT_THEME_TOKENS: {
347
+ readonly '--sf-pay-text': "textPrimaryColor";
348
+ readonly '--sf-pay-text-muted': "textSecondaryColor";
349
+ readonly '--sf-pay-background': "formBackgroundColor";
350
+ readonly '--sf-pay-input-background': "inputBackgroundColor";
351
+ readonly '--sf-pay-primary': "baseColor";
352
+ readonly '--sf-pay-primary-contrast': "buttonTextColor";
353
+ readonly '--sf-pay-error': "errorColor";
354
+ readonly '--sf-pay-success': "successColor";
355
+ readonly '--sf-pay-outline': "outlinePrimaryColor";
356
+ readonly '--sf-pay-radius': "borderRadiusMedium";
357
+ };
358
+ /**
359
+ * Reads the `--sf-pay-*` tokens from an element's computed style, so the provider form follows the shop's
360
+ * theme without the shop copying colors into JavaScript. Unsafe or empty values are skipped.
361
+ */
362
+ declare function readPaymentTheme(el: Element | null | undefined, tokens?: Record<string, string>): Record<string, string>;
363
+
364
+ export { type EmbeddedPaymentState, type EmbeddedPaymentStatus, type FetchTransportOptions, type LoadScriptOptions, MERCADOPAGO_BRICKS_KIND, type MercadoPagoAdapterOptions, type MercadoPagoCtor, type MountedPaymentForm, PAYMENT_THEME_TOKENS, PaymentBrick, type PaymentBrickHandle, type PaymentBrickProps, PaymentChallenge, type PaymentChallengeProps, type PaymentCspOptions, type PaymentEvent, type PaymentFallbackReason, type PaymentFormAdapter, type PaymentFormData, type PaymentFormError, type PaymentFormMountOptions, PaymentHttpError, type PaymentSubmitRequest, type PaymentTransport, type UseEmbeddedPaymentOptions, VoucherCard, type VoucherCardProps, createFetchTransport, loadPaymentSdk, mercadoPagoBricksAdapter, paymentCsp, paymentCspHeaderName, readPaymentTheme, resetPaymentSdkCache, sanitizeMercadoPagoFormData, useEmbeddedPayment };