@asteby/storefront-react 0.11.0 → 0.12.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.
- package/README.md +25 -0
- package/dist/checkout.cjs +673 -51
- package/dist/checkout.cjs.map +1 -1
- package/dist/checkout.css +230 -0
- package/dist/checkout.d.cts +323 -4
- package/dist/checkout.d.ts +323 -4
- package/dist/checkout.js +652 -45
- package/dist/checkout.js.map +1 -1
- package/dist/{chunk-3ZJTDFHE.js → chunk-ODIQR6TG.js} +5 -4
- package/dist/chunk-ODIQR6TG.js.map +1 -0
- package/dist/payments.cjs +171 -40
- package/dist/payments.cjs.map +1 -1
- package/dist/payments.css +14 -1
- package/dist/payments.d.cts +37 -1
- package/dist/payments.d.ts +37 -1
- package/dist/payments.js +169 -40
- package/dist/payments.js.map +1 -1
- package/package.json +2 -2
- package/dist/chunk-3ZJTDFHE.js.map +0 -1
package/dist/payments.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/payments/sdk-loader.ts","../src/payments/mercadopago.ts","../src/payments/theme.ts","../src/payments/use-embedded-payment.ts","../src/payments/payment-brick.tsx","../src/payments/adapter.ts","../src/payments/payment-method.messages.ts","../src/payments/payment-method.tsx"],"names":["paymentMessages","PaymentBrick","useRef","useEffect","useMemo","choiceValue","useState","formatMoney","jsxs","Fragment","jsx"],"mappings":";;;;;;;;;;;AAeA,IAAM,OAAA,uBAAc,GAAA,EAA2B;AAExC,SAAS,cAAA,CAAe,KAAa,OAAA,EAA2C;AACrF,EAAA,IAAI,MAAA;AACJ,EAAA,IAAI;AACF,IAAA,MAAA,GAAS,IAAI,IAAI,GAAG,CAAA;AAAA,EACtB,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,OAAA,CAAQ,MAAA,CAAO,IAAI,KAAA,CAAM,0BAA0B,CAAC,CAAA;AAAA,EAC7D;AACA,EAAA,IAAI,MAAA,CAAO,QAAA,KAAa,QAAA,IAAY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AA,MAAM,GAAA,GAAM,CAAA,CAAE,aAAA,IAAiB,CAAA,CAAE,EAAA;AACjC,MAAA,IAAI,EAAE,KAAA,KAAU,MAAA,IAAU,IAAA,CAAK,GAAA,CAAI,GAAG,CAAA,EAAG;AACzC,MAAA,IAAA,CAAK,IAAI,GAAG,CAAA;AACZ,MAAA,GAAA,CAAI,KAAK,EAAE,GAAA,EAAK,SAAS,CAAA,CAAE,QAAA,IAAY,MAAM,CAAA;AAC7C,MAAA,IAAI,GAAA,CAAI,WAAW,CAAA,EAAG;AAAA,IACxB;AACA,IAAA,OAAO,GAAA;AAAA,EACT;AACA,EAAA,OAAO,EAAC;AACV","file":"payments.js","sourcesContent":["/**\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 // El encabezado del Brick (\"Tarjeta de crédito o débito\" + banderas de tarjetas\n // aceptadas) lo dibuja Mercado Pago, repite lo que la tienda ya muestra en su propia\n // fila de método de pago y se veía cortado (p. ej. AMEX partido). hideFormTitle oculta\n // la línea del título y las banderas.\n hideFormTitle: 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","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 { PaymentOptionKey } from '@asteby/storefront'\n\n/** Texts of the \"Payment method\" section. Override any of them with the `messages` prop. */\nexport type PaymentMethodMessages = {\n legend: string\n /** Button label before the total: \"Pagar $1,200.00\". */\n pay: string\n /** Button label for card and cash, before the total. */\n placeOrder: string\n /** Button label when the buyer leaves for the provider's page. */\n payRedirect: string\n /** Button label for the first step (address) of a two-step checkout. */\n continue: string\n /** Button label when the address must be saved again. */\n retryAddress: string\n processing: string\n redirectNote: string\n cashPoints: string\n cashMore: string\n cashNote: string\n secureCard: string\n pickDeliveryFirst: string\n updatingTotal: string\n syncFailed: string\n /** The shipping quote expired or changed: fresh rates are loading. */\n quoteChanged: string\n rebuildCart: string\n noPaymentTitle: string\n noPayment: string\n paymentNote: string\n /** Fallback names for the provider options when the server sends no `label`. */\n options: Record<PaymentOptionKey, string>\n}\n\nconst ES: PaymentMethodMessages = {\n legend: 'Método de pago',\n pay: 'Pagar',\n placeOrder: 'Realizar el pedido',\n payRedirect: 'Continuar al pago',\n continue: 'Continuar',\n retryAddress: 'Guardar dirección y continuar',\n processing: 'Procesando…',\n redirectNote: 'Te llevamos a la página del proveedor para terminar el pago y regresas aquí.',\n cashPoints: 'Elige dónde pagar en efectivo',\n cashMore: 'Ver más puntos de pago',\n cashNote: 'Al hacer el pedido te damos una ficha con la referencia y la fecha límite. El pedido se confirma cuando pagas.',\n secureCard: 'Tus datos de tarjeta los captura directamente nuestro proveedor de pagos; la tienda nunca los ve.',\n pickDeliveryFirst: 'Elige primero la entrega para ver el total y pagar con tarjeta.',\n updatingTotal: 'Actualizando el total…',\n syncFailed: 'No pudimos actualizar el total con tu entrega. Puedes continuar al sitio del proveedor para pagar con tarjeta.',\n quoteChanged: 'Las tarifas de envío se actualizaron. Revisa tu envío para ver el total.',\n rebuildCart: 'Volver a armar mi carrito',\n noPaymentTitle: 'Por ahora no hay formas de pago disponibles',\n noPayment: 'Intenta de nuevo en unos minutos o escríbenos para completar tu pedido.',\n paymentNote: 'El pago se procesa de forma segura con nuestro proveedor de pagos.',\n options: {\n card: 'Tarjeta de crédito o débito',\n cash: 'Efectivo',\n wallet: 'Cuenta del proveedor de pagos',\n credits: 'Pagos sin tarjeta',\n },\n}\n\nconst EN: PaymentMethodMessages = {\n legend: 'Payment method',\n pay: 'Pay',\n placeOrder: 'Place order',\n payRedirect: 'Continue to payment',\n continue: 'Continue',\n retryAddress: 'Save address and continue',\n processing: 'Processing…',\n redirectNote: \"We'll take you to the provider's page to finish paying, then bring you back here.\",\n cashPoints: 'Choose where to pay in cash',\n cashMore: 'Show more payment points',\n cashNote: 'When you place the order you get a slip with the reference and the deadline. The order is confirmed once you pay.',\n secureCard: 'Your card details are captured directly by our payment provider; the shop never sees them.',\n pickDeliveryFirst: 'Choose delivery first to see the total and pay by card.',\n updatingTotal: 'Updating the total…',\n syncFailed: \"We couldn't update the total with your delivery. You can continue to the provider's site to pay by card.\",\n quoteChanged: 'Shipping rates were updated. Check your delivery to see the total.',\n rebuildCart: 'Rebuild my cart',\n noPaymentTitle: 'No payment methods are available right now',\n noPayment: 'Try again in a few minutes or contact us to complete your order.',\n paymentNote: 'Payment is processed securely by our payment provider.',\n options: {\n card: 'Credit or debit card',\n cash: 'Cash',\n wallet: 'Payment provider account',\n credits: 'Pay without a card',\n },\n}\n\n/** Messages for a locale (`es*` default, `en*`), with optional overrides. */\nexport function paymentMethodMessages(locale?: string | null, overrides?: Partial<Omit<PaymentMethodMessages, 'options'>> & { options?: Partial<PaymentMethodMessages['options']> } | null): PaymentMethodMessages {\n const base = (locale ?? 'es-MX').toLowerCase().startsWith('en') ? EN : ES\n if (!overrides) return base\n const { options, ...rest } = overrides\n return { ...base, ...rest, options: { ...base.options, ...options } }\n}\n","import { useEffect, useMemo, useRef, useState, useSyncExternalStore, type MouseEvent, type ReactNode, type RefObject } from 'react'\nimport { formatMoney, type Money, type PaymentOptionKey } from '@asteby/storefront'\nimport { useResolvedLocale } from '../locale.js'\nimport { createFetchTransport, type PaymentTransport } from './adapter.js'\nimport type { PayChoice, PayChoices } from './choices.js'\nimport { paymentMethodMessages, type PaymentMethodMessages } from './payment-method.messages.js'\nimport { PaymentBrick, type PaymentBrickHandle, type PaymentBrickProps } from './payment-brick.js'\nimport type { PaymentEvent } from './use-embedded-payment.js'\nimport type { PaymentOutcome } from '@asteby/storefront'\nimport { BrandMark } from '../checkout/brand-mark.js'\nimport { findBrand } from '../checkout/brands.js'\n\n/** Name of the radio group that carries the chosen row (`method` or `method|option`). */\nexport const PAYMENT_CHOICE_FIELD = 'payment_choice'\n/** Name of the radio group that carries the chosen cash point. */\nexport const CASH_POINT_FIELD = 'cash_point'\n\n/** Fields of the page form (contact, delivery, address, method) for the JSON POST of the embedded payment. */\nexport function formFields(form: HTMLFormElement | null | undefined): Record<string, string> {\n const out: Record<string, string> = {}\n if (!form) return out\n for (const [k, v] of new FormData(form).entries()) if (typeof v === 'string') out[k] = v\n return out\n}\n\nexport type PaymentMethodClassNames = Partial<\n Record<\n 'root' | 'legend' | 'choice' | 'radioLabel' | 'radio' | 'labelText' | 'hint' | 'icon' | 'brands' | 'panel' | 'cashPoint' | 'cashPointInput' | 'cashMore' | 'note' | 'alert' | 'status' | 'brickWrap' | 'brick' | 'submit' | 'rebuild',\n string\n >\n>\n\nexport type PaymentMethodTestIds = Partial<\n Record<'method' | 'submit' | 'cash' | 'redirectNote' | 'card' | 'syncing' | 'syncFailed' | 'rebuild' | 'noPayment', string>\n>\n\nexport type PaymentMethodSectionProps = {\n /** From `buildPayChoices(payment.methods)`. */\n choices: PayChoices\n /** The server total (`cart.cost.total`). Shown on the button and passed to the card form. Never computed here. */\n amount: Money\n /** Cart (or checkout) id: scopes the stored attempt id so a reload reuses it. */\n scope?: string\n /** The page `<form>`: its fields travel with the card payment and it is validated before charging. */\n formRef: RefObject<HTMLFormElement | null>\n /** POST endpoint that charges the card (`handlers.pay` on the server). */\n payUrl: string\n /** POST endpoint that re-reads the payment (`handlers.status`). Enables the 3DS / review polling. */\n statusUrl?: string\n /** Row preselected. Default: `choices.defaultValue`. */\n defaultChoice?: string | null\n /** Value of the delivery group; the card form waits until it is `deliveryReady` and `syncDelivery` has settled. */\n delivery?: string\n /** `false` while the buyer has not chosen a delivery that fixes the total (e.g. address pending). Default true. */\n deliveryReady?: boolean\n /**\n * Saves the chosen delivery on the server cart so the server total includes it. Resolve `true` once the new total\n * has been read back (the `amount` prop is then up to date). Called once per delivery, whatever the payment row (so\n * the total on the button and in the shop's summary always holds the chosen delivery). Without it nothing waits.\n *\n * Resolve `'requote'` when the server refused the rate because the quote expired or changed and the shop is loading\n * fresh rates: the section then says so (`quoteChanged`, a status, not an error), keeps the card in the page and\n * tries again with the next delivery value. `false` is a real failure (the card degrades to the redirect).\n */\n syncDelivery?: (delivery: string) => Promise<boolean | 'requote'>\n /** A two-step checkout still collecting the address: the button reads \"continue\" and no card form shows. */\n addressFirst?: boolean\n /** The address must be saved again before paying. */\n retryAddress?: boolean\n /** Disables the button (the shop is not ready to take payment). */\n blocked?: boolean\n /** The page form is submitting. */\n busy?: boolean\n /** Names of fields with a server error (`payment_method`, `cash_point`). */\n invalid?: ReadonlySet<string>\n nonce?: string\n locale?: string\n messages?: Parameters<typeof paymentMethodMessages>[1]\n /** Name for a plain method (`PaymentMethod` without options). Default: the key as it comes. */\n methodLabel?: (methodKey: string) => { label: string; hint?: string }\n /** Per-row icon by option (`card`, `cash`, `wallet`, `credits`) or `plain`. Replaces the default marks of that row. */\n icons?: Partial<Record<PaymentOptionKey | 'plain', ReactNode>>\n /**\n * Brand marks (`BrandMark`): the provider's mark on its account / no-card rows and on a plain method, the cash point\n * marks on the cash row and next to each point, and `cardBrands` on the card row. Default true; `false` keeps the\n * rows text-only.\n */\n brandMarks?: boolean\n /** Card networks drawn on the card row (`visa`, `mastercard`, `amex`, `carnet`…), as the shop's provider accepts them. */\n cardBrands?: readonly string[]\n /** How to print the total on the button. Default `formatMoney`. */\n renderAmount?: (amount: Money) => ReactNode\n /** Anchor to the cart for the \"rebuild\" action when the cart expired. Default: plain `<a href>`. */\n rebuildHref?: string\n renderLink?: (props: { href: string; className?: string; children: ReactNode; testId?: string }) => ReactNode\n /** Called once the order is closed in the page (approved, under review or voucher). Navigate to the thank-you page. */\n onDone: (outcome: PaymentOutcome) => void\n /** The server total changed under the buyer: re-read the cart (the card form remounts with the new amount). */\n onAmountChanged?: () => void\n onEvent?: (event: PaymentEvent) => void\n classNames?: PaymentMethodClassNames\n testIds?: PaymentMethodTestIds\n /** Hide the section button (drive the form some other way). Card payments then need `PaymentMethodHandle`-less flows. */\n hideSubmit?: boolean\n /** Replaces the transport built from `payUrl` / `statusUrl`. */\n transport?: PaymentTransport\n /** Extra props for the card form (`adapter`, `adapters`, `messages`, `minHeight`, `storage`, timeouts...). */\n brickProps?: Partial<Omit<PaymentBrickProps, 'client' | 'amount' | 'transport' | 'onResult' | 'onEvent' | 'onFallback'>>\n}\n\nconst useHydrated = () =>\n useSyncExternalStore(\n () => () => {},\n () => true,\n () => false,\n )\n\n/**\n * \"Payment method\", hybrid. Card: the provider's secure form INSIDE the page (`PaymentBrick`) with the shop's own\n * button. Cash: payment points and a voucher on order. Provider account and no-card payments redirect. Without\n * JavaScript, or if the card form does not load, everything falls back to the plain redirect flow (the page form's\n * normal submit); the cash point radios and the notes work without JavaScript with the `payments.css` sheet.\n *\n * Money: the form amount is the server total passed in `amount` (already holding the chosen delivery); nothing is added\n * or recalculated here.\n *\n * Accessibility: one labelled `fieldset` with native radios; notes in `role=\"status\"`, problems in `role=\"alert\"`; the\n * button explains its busy state and is never silently disabled while the card form is loading.\n */\nexport function PaymentMethodSection(props: PaymentMethodSectionProps) {\n const {\n choices,\n amount,\n scope,\n formRef,\n payUrl,\n statusUrl,\n delivery = '',\n deliveryReady = true,\n syncDelivery,\n addressFirst = false,\n retryAddress = false,\n blocked = false,\n busy = false,\n invalid,\n nonce,\n methodLabel,\n icons,\n brandMarks = true,\n cardBrands = [],\n renderAmount,\n rebuildHref,\n renderLink,\n onDone,\n onAmountChanged,\n onEvent,\n classNames: cx = {},\n testIds = {},\n hideSubmit,\n brickProps,\n } = props\n const locale = useResolvedLocale(props.locale)\n const m = useMemo(() => paymentMethodMessages(locale, props.messages), [locale, props.messages])\n const hydrated = useHydrated()\n const [choiceValue, setChoiceValue] = useState(props.defaultChoice ?? choices.defaultValue)\n const selected = choices.choices.find((c) => c.value === choiceValue) ?? null\n const noPayment = choices.choices.length === 0\n const tid = (k: keyof PaymentMethodTestIds) => (testIds[k] ? { 'data-testid': testIds[k] } : {})\n\n const [fallback, setFallback] = useState(false)\n const [ready, setReady] = useState(false)\n const [processing, setProcessing] = useState(false)\n const [expired, setExpired] = useState(false)\n const brick = useRef<PaymentBrickHandle>(null)\n\n const cardChosen = selected?.mode === 'card' && !retryAddress && !addressFirst\n const cardActive = hydrated && cardChosen && !fallback\n\n // The server total must hold the chosen delivery before the card form mounts, and before any total is printed on the\n // button: the shop saves it on the cart and re-reads the cart. Once per delivery, for every payment row (cash and\n // redirect included, otherwise the button and the summary show the cart without shipping).\n const wantSync = hydrated && selected !== null && !addressFirst && !retryAddress && deliveryReady && Boolean(syncDelivery)\n const [sync, setSync] = useState<{ key: string; ok: boolean; requote?: boolean } | null>(null)\n const syncRef = useRef(syncDelivery)\n syncRef.current = syncDelivery\n useEffect(() => {\n if (!wantSync || !syncRef.current) return\n if (sync?.key === delivery && sync.ok) return\n let cancelled = false\n syncRef.current(delivery).then(\n (ok) => !cancelled && setSync(ok === 'requote' ? { key: delivery, ok: false, requote: true } : { key: delivery, ok }),\n () => !cancelled && setSync({ key: delivery, ok: false }),\n )\n return () => {\n cancelled = true\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [wantSync, delivery])\n const settled = sync?.key === delivery\n const synced = !syncDelivery || (settled && sync!.ok)\n const requote = wantSync && settled && sync!.requote === true\n const syncFailed = wantSync && settled && !sync!.ok && !requote\n const brickReady = cardActive && deliveryReady && synced && !syncFailed\n\n const transport = useMemo(\n () =>\n props.transport ??\n createFetchTransport(payUrl, {\n ...(statusUrl ? { refreshUrl: statusUrl } : {}),\n buildBody: (request) => ({ ...request, fields: formFields(formRef.current) }),\n }),\n [props.transport, payUrl, statusUrl, formRef],\n )\n\n const handleEvent = (e: PaymentEvent) => {\n if (e.type === 'form_ready') setReady(true)\n if (e.type === 'submit') setProcessing(true)\n if (e.type === 'tokenize_error' || e.type === 'retry') setProcessing(e.type === 'retry')\n if (e.type === 'result' && e.status === 'rejected') setProcessing(false)\n if (e.type === 'error') {\n setProcessing(false)\n if (e.kind === 'price_mismatch') onAmountChanged?.()\n if (e.kind === 'expired') setExpired(true)\n }\n onEvent?.(e)\n }\n\n // While the delivery is being saved the amount is stale: the button reads without it.\n const total = wantSync && (!settled || requote) ? null : renderAmount ? renderAmount(amount) : formatMoney(amount, locale)\n const label: ReactNode = retryAddress ? (\n m.retryAddress\n ) : addressFirst ? (\n m.continue\n ) : selected?.mode === 'plain' || !selected ? (\n <>\n {m.pay}\n {total ? <> {total}</> : null}\n </>\n ) : selected.mode === 'redirect' || (selected.mode === 'card' && (fallback || syncFailed)) ? (\n m.payRedirect\n ) : (\n <>\n {m.placeOrder}\n {total ? <> {total}</> : null}\n </>\n )\n\n function onPayClick(event: MouseEvent<HTMLButtonElement>) {\n // Redirect, cash, plain method, or a card without a usable form: the page form's normal submit.\n if (!cardActive || syncFailed) return\n event.preventDefault()\n const form = formRef.current\n if (form && !form.reportValidity()) return // required fields: the browser explains which is missing\n if (brickReady) void brick.current?.submit()\n }\n\n const cardNotice = (k: 'syncing' | 'syncFailed' | 'pickDelivery' | 'requote', node: ReactNode) =>\n k === 'syncFailed' ? (\n <p role=\"alert\" className={cx.alert} data-sf-pay-notice=\"sync-failed\" {...tid('syncFailed')}>\n {node}\n </p>\n ) : (\n <p role=\"status\" className={cx.status} data-sf-pay-notice={k} {...(k === 'syncing' ? tid('syncing') : {})}>\n {node}\n </p>\n )\n\n const Link = renderLink ?? (({ href, className, children, testId }) => (\n <a href={href} className={className} {...(testId ? { 'data-testid': testId } : {})}>\n {children}\n </a>\n ))\n\n return (\n <fieldset id=\"pago\" className={cx.root} data-sf-pay-method>\n <legend className={cx.legend}>{m.legend}</legend>\n {choices.choices.map((choice) => {\n const { label: rowLabel, hint } = rowText(choice, m, methodLabel)\n const checked = choice.value === choiceValue\n const slot = choice.option ?? 'plain'\n const icon = icons?.[slot] ?? (brandMarks ? defaultIcon(choice) : null)\n const marks = brandMarks ? rowMarks(choice, cardBrands) : []\n return (\n <div key={choice.value} className={cx.choice} data-sf-pay-choice>\n <label className={cx.radioLabel}>\n <input\n type=\"radio\"\n name={PAYMENT_CHOICE_FIELD}\n value={choice.value}\n checked={checked}\n onChange={() => setChoiceValue(choice.value)}\n aria-invalid={invalid?.has('payment_method') || undefined}\n data-mode={choice.mode}\n required\n className={cx.radio}\n {...tid('method')}\n />\n {icon ? (\n <span className={cx.icon} aria-hidden=\"true\">\n {icon}\n </span>\n ) : null}\n <span className={cx.labelText}>\n {rowLabel}\n {hint ? <span className={cx.hint}> {hint}</span> : null}\n </span>\n {marks.length ? (\n <span className={cx.brands} data-sf-pay-brands={choice.option ?? 'plain'} aria-hidden=\"true\">\n {marks.map((mk) => (\n <BrandMark key={mk.key} brand={mk.key} logoUrl={mk.logoUrl ?? null} size={20} />\n ))}\n </span>\n ) : null}\n </label>\n {/* Always in the HTML and visible only with its radio checked (payments.css :has): without JavaScript the cash point is also chosen. */}\n <ChoicePanel choice={choice} m={m} invalid={invalid} cx={cx} tid={tid} hidden={hydrated && !checked} marks={brandMarks} />\n </div>\n )\n })}\n\n {noPayment ? (\n <div role=\"alert\" className={cx.alert} data-sf-pay-notice=\"no-payment\" {...tid('noPayment')}>\n <p>\n <strong>{m.noPaymentTitle}</strong>\n </p>\n <p>{m.noPayment}</p>\n </div>\n ) : null}\n\n {cardChosen && hydrated && choices.cardClient ? (\n <div className={cx.brickWrap} data-sf-pay-card {...tid('card')}>\n {fallback\n ? null\n : !deliveryReady\n ? cardNotice('pickDelivery', m.pickDeliveryFirst)\n : syncFailed\n ? cardNotice('syncFailed', m.syncFailed)\n : requote\n ? cardNotice('requote', m.quoteChanged)\n : !synced\n ? cardNotice('syncing', m.updatingTotal)\n : null}\n {brickReady || fallback ? (\n <PaymentBrick\n {...brickProps}\n ref={brick}\n client={choices.cardClient}\n amount={amount}\n transport={transport}\n {...(nonce ? { nonce } : {})}\n locale={locale}\n {...(scope ? { scope } : {})}\n enabled={brickReady}\n {...(cx.brick ? { className: cx.brick } : {})}\n onEvent={handleEvent}\n onFallback={() => setFallback(true)}\n onResult={(o) => {\n // Approved, under review or voucher: the order is already closed and the receipt is in the cookie.\n if (o.kind === 'approved' || o.kind === 'in_review' || o.kind === 'voucher') onDone(o)\n }}\n />\n ) : null}\n <p className={cx.note}>{m.secureCard}</p>\n {expired && rebuildHref ? Link({ href: rebuildHref, ...(cx.rebuild ? { className: cx.rebuild } : {}), children: m.rebuildCart, ...(testIds.rebuild ? { testId: testIds.rebuild } : {}) }) : null}\n </div>\n ) : null}\n\n {noPayment || choices.choices.some((c) => c.option) ? null : <p className={cx.note}>{m.paymentNote}</p>}\n\n {hideSubmit ? null : (\n <button\n type=\"submit\"\n onClick={onPayClick}\n className={cx.submit}\n disabled={busy || blocked}\n aria-disabled={blocked || (brickReady && (!ready || processing)) || undefined}\n aria-busy={processing || undefined}\n data-sf-pay-method-submit\n {...tid('submit')}\n >\n {busy || processing ? m.processing : label}\n </button>\n )}\n </fieldset>\n )\n}\n\nfunction rowText(choice: PayChoice, m: PaymentMethodMessages, methodLabel: PaymentMethodSectionProps['methodLabel']): { label: string; hint?: string } {\n if (choice.mode === 'plain') return methodLabel ? methodLabel(choice.methodKey) : { label: choice.methodKey }\n return { label: choice.label ?? (choice.option ? m.options[choice.option] : undefined) ?? choice.option ?? choice.methodKey }\n}\n\nfunction ChoicePanel({\n choice,\n m,\n invalid,\n cx,\n tid,\n hidden,\n marks = true,\n}: {\n choice: PayChoice\n m: PaymentMethodMessages\n invalid: ReadonlySet<string> | undefined\n cx: PaymentMethodClassNames\n tid: (k: keyof PaymentMethodTestIds) => { 'data-testid'?: string }\n hidden: boolean\n marks?: boolean\n}) {\n if (choice.mode === 'redirect') {\n return (\n <p className={cx.panel} hidden={hidden} data-sf-pay-panel=\"redirect\" {...tid('redirectNote')}>\n {m.redirectNote}\n </p>\n )\n }\n if (choice.mode !== 'cash') return null\n const main = choice.points.filter((p) => p.group === 'main')\n const more = choice.points.filter((p) => p.group !== 'main')\n const row = (p: PayChoice['points'][number], i: number, first: boolean) => (\n <label key={p.id} className={cx.cashPoint} data-sf-pay-point>\n <input type=\"radio\" name={CASH_POINT_FIELD} value={p.id} defaultChecked={first && i === 0} className={cx.cashPointInput} aria-invalid={invalid?.has('cash_point') || undefined} />\n {marks ? <BrandMark brand={p.payment_point || p.id} logoUrl={p.logo_url ?? null} size={22} /> : null}\n <span>{p.label}</span>\n </label>\n )\n return (\n <div className={cx.panel} hidden={hidden} data-sf-pay-panel=\"cash\" {...tid('cash')}>\n <fieldset>\n <legend>{m.cashPoints}</legend>\n <div data-sf-pay-points>{main.map((p, i) => row(p, i, true))}</div>\n {more.length ? (\n <details>\n <summary className={cx.cashMore} style={{ minHeight: 44 }}>\n {m.cashMore}\n </summary>\n <div data-sf-pay-points>{more.map((p, i) => row(p, i, false))}</div>\n </details>\n ) : null}\n </fieldset>\n <p className={cx.note}>{m.cashNote}</p>\n </div>\n )\n}\n\nconst glyph = (d: string) => (\n <svg viewBox=\"0 0 24 24\" width=\"24\" height=\"24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.7\" strokeLinecap=\"round\" strokeLinejoin=\"round\" focusable=\"false\" data-sf-pay-glyph>\n <path d={d} />\n </svg>\n)\nconst CARD_GLYPH = 'M3 6.5h18v11H3zM3 10h18M6.5 14.5h4'\nconst CASH_GLYPH = 'M3 7h18v10H3zM12 14.5a2.5 2.5 0 1 0 0-5a2.5 2.5 0 0 0 0 5zM6 10v4M18 10v4'\n\n/** Leading icon of a row: the provider's mark on its own account / no-card rows; a neutral glyph for card and cash. */\nfunction defaultIcon(choice: PayChoice): ReactNode {\n // By option, not mode: a card row without the in-page form still is a card.\n if (choice.option === 'card') return glyph(CARD_GLYPH)\n if (choice.option === 'cash') return glyph(CASH_GLYPH)\n return findBrand(choice.methodKey) ? <BrandMark brand={choice.methodKey} size={24} /> : null\n}\n\n/** Trailing marks of a row: card networks on the card row, the first cash points on the cash row. */\nfunction rowMarks(choice: PayChoice, cardBrands: readonly string[]): Array<{ key: string; logoUrl?: string | null }> {\n if (choice.option === 'card') return cardBrands.map((key) => ({ key }))\n if (choice.option === 'cash') {\n const seen = new Set<string>()\n const out: Array<{ key: string; logoUrl?: string | null }> = []\n for (const p of choice.points) {\n const key = p.payment_point || p.id\n if (p.group !== 'main' || seen.has(key)) continue\n seen.add(key)\n out.push({ key, logoUrl: p.logo_url ?? null })\n if (out.length === 4) break\n }\n return out\n }\n return []\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/payments/sdk-loader.ts","../src/payments/mercadopago.ts","../src/payments/theme.ts","../src/payments/use-embedded-payment.ts","../src/payments/payment-brick.tsx","../src/payments/adapter.ts","../src/payments/payment-method.messages.ts","../src/payments/payment-method.tsx"],"names":["paymentMessages","PaymentBrick","useRef","useEffect","useMemo","choiceValue","useState","formatMoney","jsxs","Fragment","jsx"],"mappings":";;;;;;;;;;;AAeA,IAAM,OAAA,uBAAc,GAAA,EAA2B;AAExC,SAAS,cAAA,CAAe,KAAa,OAAA,EAA2C;AACrF,EAAA,IAAI,MAAA;AACJ,EAAA,IAAI;AACF,IAAA,MAAA,GAAS,IAAI,IAAI,GAAG,CAAA;AAAA,EACtB,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,OAAA,CAAQ,MAAA,CAAO,IAAI,KAAA,CAAM,0BA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AAA,CAAO,SAAA,EAAW,IAAA,EAAM,EAAA,EAAI,CAAA,GAAK,IAAA;AAC1F;AAEA,SAAS,iBAAiB,IAAA,EAAyC;AACjE,EAAA,MAAM,EAAA,GAAK,IAAA,EAAM,aAAA,CAAgC,CAAA,YAAA,EAAe,gBAAgB,CAAA,UAAA,CAAY,CAAA;AAC5F,EAAA,OAAO,IAAI,KAAA,IAAS,IAAA;AACtB;AAGA,SAAS,QAAA,CAAS,QAAmB,UAAA,EAAgF;AACnH,EAAA,IAAI,MAAA,CAAO,MAAA,KAAW,MAAA,EAAQ,OAAO,UAAA,CAAW,IAAI,CAAC,GAAA,MAAS,EAAE,GAAA,EAAI,CAAE,CAAA;AACtE,EAAA,IAAI,MAAA,CAAO,WAAW,MAAA,EAAQ;AAC5B,IAAA,MAAM,IAAA,uBAAW,GAAA,EAAY;AAC7B,IAAA,MAAM,MAAuD,EAAC;AAC9D,IAAA,KAAA,MAAW,CAAA,IAAK,OAAO,MAAA,EAAQ;AAC7B,MAAA,MAAM,GAAA,GAAM,CAAA,CAAE,aAAA,IAAiB,CAAA,CAAE,EAAA;AACjC,MAAA,IAAI,EAAE,KAAA,KAAU,MAAA,IAAU,IAAA,CAAK,GAAA,CAAI,GAAG,CAAA,EAAG;AACzC,MAAA,IAAA,CAAK,IAAI,GAAG,CAAA;AACZ,MAAA,GAAA,CAAI,KAAK,EAAE,GAAA,EAAK,SAAS,CAAA,CAAE,QAAA,IAAY,MAAM,CAAA;AAC7C,MAAA,IAAI,GAAA,CAAI,WAAW,CAAA,EAAG;AAAA,IACxB;AACA,IAAA,OAAO,GAAA;AAAA,EACT;AACA,EAAA,OAAO,EAAC;AACV","file":"payments.js","sourcesContent":["/**\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 // El encabezado del Brick (\"Tarjeta de crédito o débito\" + banderas de tarjetas\n // aceptadas) lo dibuja Mercado Pago, repite lo que la tienda ya muestra en su propia\n // fila de método de pago y se veía cortado (p. ej. AMEX partido). hideFormTitle oculta\n // la línea del título y las banderas.\n hideFormTitle: true,\n // Dark page: the Brick's `dark` base theme, so it does not draw a white card; the shop tokens refine it.\n style: { theme: opts.colorScheme === 'dark' ? 'dark' : '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","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 '--sf-pay-radius-small': 'borderRadiusSmall',\n '--sf-pay-radius-large': 'borderRadiusLarge',\n '--sf-pay-outline-secondary': 'outlineSecondaryColor',\n '--sf-pay-primary-variant': 'baseColorFirstVariant',\n '--sf-pay-input-border-width': 'inputBorderWidth',\n '--sf-pay-form-padding': 'formPadding',\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\n/**\n * Light or dark for the provider form, so it does not paint a white card inside a dark page. Order: the\n * `--sf-pay-scheme` token (`light` / `dark`), then the element's `color-scheme` (`light dark` follows the system\n * preference). `null` when nothing says it (the provider default).\n */\nexport function readPaymentScheme(el: Element | null | undefined): 'light' | 'dark' | null {\n if (!el || typeof getComputedStyle !== 'function') return null\n const style = getComputedStyle(el)\n const token = style.getPropertyValue('--sf-pay-scheme').trim()\n if (token === 'dark' || token === 'light') return token\n const cs = (style.getPropertyValue('color-scheme') || (style as unknown as { colorScheme?: string }).colorScheme || '').toLowerCase()\n const dark = /\\bdark\\b/.test(cs)\n const light = /\\blight\\b/.test(cs)\n if (dark && !light) return 'dark'\n if (light && !dark) return 'light'\n if (dark && light && typeof matchMedia === 'function') return matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'\n return null\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 { readPaymentScheme, 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 /** Overrides the light / dark scheme read from the page (`--sf-pay-scheme` or `color-scheme`). */\n colorScheme?: 'light' | 'dark'\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 colorScheme = live.current.colorScheme ?? readPaymentScheme(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 ...(colorScheme ? { colorScheme } : {}),\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 /** Light or dark page (see `readPaymentScheme`): the adapter picks the provider's matching base theme. */\n colorScheme?: 'light' | 'dark'\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 { PaymentOptionKey } from '@asteby/storefront'\n\n/** Texts of the \"Payment method\" section. Override any of them with the `messages` prop. */\nexport type PaymentMethodMessages = {\n legend: string\n /** Button label before the total: \"Pagar $1,200.00\". */\n pay: string\n /** Button label for card and cash, before the total. */\n placeOrder: string\n /** Button label for cash (the buyer gets a payment slip and pays later), before the total. */\n placeOrderCash: string\n /** Button label while no delivery is chosen yet. */\n chooseDelivery: string\n /** Button label when the buyer leaves for the provider's page. */\n payRedirect: string\n /** Button label for the first step (address) of a two-step checkout. */\n continue: string\n /** Button label when the address must be saved again. */\n retryAddress: string\n processing: string\n redirectNote: string\n cashPoints: string\n cashMore: string\n cashNote: string\n secureCard: string\n pickDeliveryFirst: string\n updatingTotal: string\n syncFailed: string\n /** The shipping quote expired or changed: fresh rates are loading. */\n quoteChanged: string\n rebuildCart: string\n noPaymentTitle: string\n noPayment: string\n paymentNote: string\n /** Fallback names for the provider options when the server sends no `label`. */\n options: Record<PaymentOptionKey, string>\n}\n\nconst ES: PaymentMethodMessages = {\n legend: 'Método de pago',\n pay: 'Pagar',\n placeOrder: 'Realizar el pedido',\n placeOrderCash: 'Generar ficha de pago',\n chooseDelivery: 'Elige la entrega para continuar',\n payRedirect: 'Continuar al pago',\n continue: 'Continuar',\n retryAddress: 'Guardar dirección y continuar',\n processing: 'Procesando…',\n redirectNote: 'Te llevamos a la página del proveedor para terminar el pago y regresas aquí.',\n cashPoints: 'Elige dónde pagar en efectivo',\n cashMore: 'Ver más puntos de pago',\n cashNote: 'Al hacer el pedido te damos una ficha con la referencia y la fecha límite. El pedido se confirma cuando pagas.',\n secureCard: 'Tus datos de tarjeta los captura directamente nuestro proveedor de pagos; la tienda nunca los ve.',\n pickDeliveryFirst: 'Elige primero la entrega para ver el total y pagar con tarjeta.',\n updatingTotal: 'Actualizando el total…',\n syncFailed: 'No pudimos actualizar el total con tu entrega. Puedes continuar al sitio del proveedor para pagar con tarjeta.',\n quoteChanged: 'Las tarifas de envío se actualizaron. Revisa tu envío para ver el total.',\n rebuildCart: 'Volver a armar mi carrito',\n noPaymentTitle: 'Por ahora no hay formas de pago disponibles',\n noPayment: 'Intenta de nuevo en unos minutos o escríbenos para completar tu pedido.',\n paymentNote: 'El pago se procesa de forma segura con nuestro proveedor de pagos.',\n options: {\n card: 'Tarjeta de crédito o débito',\n cash: 'Efectivo',\n wallet: 'Cuenta del proveedor de pagos',\n credits: 'Pagos sin tarjeta',\n },\n}\n\nconst EN: PaymentMethodMessages = {\n legend: 'Payment method',\n pay: 'Pay',\n placeOrder: 'Place order',\n placeOrderCash: 'Get payment slip',\n chooseDelivery: 'Choose delivery to continue',\n payRedirect: 'Continue to payment',\n continue: 'Continue',\n retryAddress: 'Save address and continue',\n processing: 'Processing…',\n redirectNote: \"We'll take you to the provider's page to finish paying, then bring you back here.\",\n cashPoints: 'Choose where to pay in cash',\n cashMore: 'Show more payment points',\n cashNote: 'When you place the order you get a slip with the reference and the deadline. The order is confirmed once you pay.',\n secureCard: 'Your card details are captured directly by our payment provider; the shop never sees them.',\n pickDeliveryFirst: 'Choose delivery first to see the total and pay by card.',\n updatingTotal: 'Updating the total…',\n syncFailed: \"We couldn't update the total with your delivery. You can continue to the provider's site to pay by card.\",\n quoteChanged: 'Shipping rates were updated. Check your delivery to see the total.',\n rebuildCart: 'Rebuild my cart',\n noPaymentTitle: 'No payment methods are available right now',\n noPayment: 'Try again in a few minutes or contact us to complete your order.',\n paymentNote: 'Payment is processed securely by our payment provider.',\n options: {\n card: 'Credit or debit card',\n cash: 'Cash',\n wallet: 'Payment provider account',\n credits: 'Pay without a card',\n },\n}\n\n/** Messages for a locale (`es*` default, `en*`), with optional overrides. */\nexport function paymentMethodMessages(locale?: string | null, overrides?: Partial<Omit<PaymentMethodMessages, 'options'>> & { options?: Partial<PaymentMethodMessages['options']> } | null): PaymentMethodMessages {\n const base = (locale ?? 'es-MX').toLowerCase().startsWith('en') ? EN : ES\n if (!overrides) return base\n const { options, ...rest } = overrides\n return { ...base, ...rest, options: { ...base.options, ...options } }\n}\n","import { useEffect, useMemo, useRef, useState, useSyncExternalStore, type MouseEvent, type ReactNode, type RefObject } from 'react'\nimport { formatMoney, type Money, type PaymentOptionKey } from '@asteby/storefront'\nimport { useResolvedLocale } from '../locale.js'\nimport { createFetchTransport, type PaymentTransport } from './adapter.js'\nimport type { PayChoice, PayChoices } from './choices.js'\nimport { paymentMethodMessages, type PaymentMethodMessages } from './payment-method.messages.js'\nimport { PaymentBrick, type PaymentBrickHandle, type PaymentBrickProps } from './payment-brick.js'\nimport type { PaymentEvent } from './use-embedded-payment.js'\nimport type { PaymentOutcome } from '@asteby/storefront'\nimport { BrandMark } from '../checkout/brand-mark.js'\nimport { findBrand } from '../checkout/brands.js'\n\n/** Name of the radio group that carries the chosen row (`method` or `method|option`). */\nexport const PAYMENT_CHOICE_FIELD = 'payment_choice'\n/** Name of the radio group that carries the chosen cash point. */\nexport const CASH_POINT_FIELD = 'cash_point'\n\n/** Fields of the page form (contact, delivery, address, method) for the JSON POST of the embedded payment. */\nexport function formFields(form: HTMLFormElement | null | undefined): Record<string, string> {\n const out: Record<string, string> = {}\n if (!form) return out\n for (const [k, v] of new FormData(form).entries()) if (typeof v === 'string') out[k] = v\n return out\n}\n\nexport type PaymentMethodClassNames = Partial<\n Record<\n 'root' | 'legend' | 'choice' | 'radioLabel' | 'radio' | 'labelText' | 'hint' | 'icon' | 'brands' | 'panel' | 'cashPoint' | 'cashPointInput' | 'cashMore' | 'note' | 'alert' | 'status' | 'brickWrap' | 'brick' | 'submit' | 'rebuild',\n string\n >\n>\n\nexport type PaymentMethodTestIds = Partial<\n Record<'method' | 'submit' | 'cash' | 'redirectNote' | 'card' | 'syncing' | 'syncFailed' | 'rebuild' | 'noPayment', string>\n>\n\nexport type PaymentMethodSectionProps = {\n /** From `buildPayChoices(payment.methods)`. */\n choices: PayChoices\n /** The server total (`cart.cost.total`). Shown on the button and passed to the card form. Never computed here. */\n amount: Money\n /** Cart (or checkout) id: scopes the stored attempt id so a reload reuses it. */\n scope?: string\n /** The page `<form>`: its fields travel with the card payment and it is validated before charging. */\n formRef: RefObject<HTMLFormElement | null>\n /** POST endpoint that charges the card (`handlers.pay` on the server). */\n payUrl: string\n /** POST endpoint that re-reads the payment (`handlers.status`). Enables the 3DS / review polling. */\n statusUrl?: string\n /** Row preselected. Default: `choices.defaultValue`. */\n defaultChoice?: string | null\n /** Value of the delivery group; the card form waits until it is `deliveryReady` and `syncDelivery` has settled. */\n delivery?: string\n /** `false` while the buyer has not chosen a delivery that fixes the total (e.g. address pending). Default true. */\n deliveryReady?: boolean\n /**\n * Saves the chosen delivery on the server cart so the server total includes it. Resolve `true` once the new total\n * has been read back (the `amount` prop is then up to date). Called once per delivery, whatever the payment row (so\n * the total on the button and in the shop's summary always holds the chosen delivery). Without it nothing waits.\n *\n * Resolve `'requote'` when the server refused the rate because the quote expired or changed and the shop is loading\n * fresh rates: the section then says so (`quoteChanged`, a status, not an error), keeps the card in the page and\n * tries again with the next delivery value. `false` is a real failure (the card degrades to the redirect).\n */\n syncDelivery?: (delivery: string) => Promise<boolean | 'requote'>\n /** A two-step checkout still collecting the address: the button reads \"continue\" and no card form shows. */\n addressFirst?: boolean\n /** The address must be saved again before paying. */\n retryAddress?: boolean\n /** Disables the button (the shop is not ready to take payment). */\n blocked?: boolean\n /** The page form is submitting. */\n busy?: boolean\n /** Names of fields with a server error (`payment_method`, `cash_point`). */\n invalid?: ReadonlySet<string>\n nonce?: string\n locale?: string\n messages?: Parameters<typeof paymentMethodMessages>[1]\n /** Name for a plain method (`PaymentMethod` without options). Default: the key as it comes. */\n methodLabel?: (methodKey: string) => { label: string; hint?: string }\n /** Per-row icon by option (`card`, `cash`, `wallet`, `credits`) or `plain`. Replaces the default marks of that row. */\n icons?: Partial<Record<PaymentOptionKey | 'plain', ReactNode>>\n /**\n * Brand marks (`BrandMark`): the provider's mark on its account / no-card rows and on a plain method, the cash point\n * marks on the cash row and next to each point, and `cardBrands` on the card row. Default true; `false` keeps the\n * rows text-only.\n */\n brandMarks?: boolean\n /** Card networks drawn on the card row (`visa`, `mastercard`, `amex`, `carnet`…), as the shop's provider accepts them. */\n cardBrands?: readonly string[]\n /** How to print the total on the button. Default `formatMoney`. */\n renderAmount?: (amount: Money) => ReactNode\n /** Anchor to the cart for the \"rebuild\" action when the cart expired. Default: plain `<a href>`. */\n rebuildHref?: string\n renderLink?: (props: { href: string; className?: string; children: ReactNode; testId?: string }) => ReactNode\n /** Called once the order is closed in the page (approved, under review or voucher). Navigate to the thank-you page. */\n onDone: (outcome: PaymentOutcome) => void\n /** The server total changed under the buyer: re-read the cart (the card form remounts with the new amount). */\n onAmountChanged?: () => void\n onEvent?: (event: PaymentEvent) => void\n classNames?: PaymentMethodClassNames\n testIds?: PaymentMethodTestIds\n /** Hide the section button (drive the form some other way). Card payments then need `PaymentMethodHandle`-less flows. */\n hideSubmit?: boolean\n /** Replaces the transport built from `payUrl` / `statusUrl`. */\n transport?: PaymentTransport\n /** Extra props for the card form (`adapter`, `adapters`, `messages`, `minHeight`, `storage`, timeouts...). */\n brickProps?: Partial<Omit<PaymentBrickProps, 'client' | 'amount' | 'transport' | 'onResult' | 'onEvent' | 'onFallback'>>\n /**\n * Remember the chosen row (and cash point) for this `scope` in `sessionStorage`, so a reload, the \"back\" button from\n * the provider or the address step does not ask to choose again. Used only while that row is still published.\n * Default true (needs `scope`); `false` turns it off. Nothing personal is stored: only the row value.\n */\n rememberChoice?: boolean\n /**\n * Cash points shown before \"more payment points\". Default: every point the provider marks `main`. With a number, the\n * first N `main` points show and the rest join the \"more\" list (a remembered point inside it opens the list).\n */\n cashPointsVisible?: number\n /**\n * Name of the page form field with the buyer's e-mail. Its value is handed to the card form, so the provider does not\n * ask for the e-mail again. Default `email`; `null` to never pass it. `brickProps.email` wins.\n */\n payerEmailField?: string | null\n}\n\nconst CHOICE_STORAGE_PREFIX = 'sf:pay-choice:'\n\ntype StoredChoice = { choice: string; point?: string | null }\n\nfunction readStoredChoice(scope: string | undefined): StoredChoice | null {\n if (!scope || typeof window === 'undefined') return null\n try {\n const raw = window.sessionStorage.getItem(CHOICE_STORAGE_PREFIX + scope)\n if (!raw) return null\n const v = JSON.parse(raw) as StoredChoice\n return typeof v?.choice === 'string' ? v : null\n } catch {\n return null\n }\n}\n\nfunction writeStoredChoice(scope: string | undefined, value: StoredChoice): void {\n if (!scope || typeof window === 'undefined') return\n try {\n window.sessionStorage.setItem(CHOICE_STORAGE_PREFIX + scope, JSON.stringify(value))\n } catch {\n /* private mode or storage full: the choice simply is not remembered */\n }\n}\n\nconst EMAIL_RE = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\nconst useHydrated = () =>\n useSyncExternalStore(\n () => () => {},\n () => true,\n () => false,\n )\n\n/**\n * \"Payment method\", hybrid. Card: the provider's secure form INSIDE the page (`PaymentBrick`) with the shop's own\n * button. Cash: payment points and a voucher on order. Provider account and no-card payments redirect. Without\n * JavaScript, or if the card form does not load, everything falls back to the plain redirect flow (the page form's\n * normal submit); the cash point radios and the notes work without JavaScript with the `payments.css` sheet.\n *\n * Money: the form amount is the server total passed in `amount` (already holding the chosen delivery); nothing is added\n * or recalculated here.\n *\n * Accessibility: one labelled `fieldset` with native radios; notes in `role=\"status\"`, problems in `role=\"alert\"`; the\n * button explains its busy state and is never silently disabled while the card form is loading.\n */\nexport function PaymentMethodSection(props: PaymentMethodSectionProps) {\n const {\n choices,\n amount,\n scope,\n formRef,\n payUrl,\n statusUrl,\n delivery = '',\n deliveryReady = true,\n syncDelivery,\n addressFirst = false,\n retryAddress = false,\n blocked = false,\n busy = false,\n invalid,\n nonce,\n methodLabel,\n icons,\n brandMarks = true,\n cardBrands = [],\n renderAmount,\n rebuildHref,\n renderLink,\n onDone,\n onAmountChanged,\n onEvent,\n classNames: cx = {},\n testIds = {},\n hideSubmit,\n brickProps,\n rememberChoice = true,\n cashPointsVisible,\n payerEmailField = 'email',\n } = props\n const locale = useResolvedLocale(props.locale)\n const m = useMemo(() => paymentMethodMessages(locale, props.messages), [locale, props.messages])\n const hydrated = useHydrated()\n const [choiceValue, setChoiceValueState] = useState(props.defaultChoice ?? choices.defaultValue)\n const remember = rememberChoice && Boolean(scope)\n const rootRef = useRef<HTMLFieldSetElement>(null)\n const [storedPoint, setStoredPoint] = useState<string | null>(null)\n const setChoiceValue = (v: string) => {\n setChoiceValueState(v)\n if (remember) writeStoredChoice(scope, { choice: v, point: readCheckedPoint(rootRef.current) })\n }\n // After hydration: the row (and cash point) chosen earlier in this cart, if the server still publishes it. The server\n // HTML keeps the default row, so the page works the same without JavaScript.\n useEffect(() => {\n if (!remember) return\n const stored = readStoredChoice(scope)\n if (!stored) return\n if (choices.choices.some((c) => c.value === stored.choice)) setChoiceValueState(stored.choice)\n if (stored.point) setStoredPoint(stored.point)\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [remember, scope])\n useEffect(() => {\n if (!storedPoint || !rootRef.current) return\n const input = Array.from(rootRef.current.querySelectorAll<HTMLInputElement>(`input[name=\"${CASH_POINT_FIELD}\"]`)).find((i) => i.value === storedPoint)\n if (input) input.checked = true\n }, [storedPoint, choiceValue])\n const onPointChange = (point: string) => {\n if (remember && choiceValue) writeStoredChoice(scope, { choice: choiceValue, point })\n }\n const selected = choices.choices.find((c) => c.value === choiceValue) ?? null\n const noPayment = choices.choices.length === 0\n const tid = (k: keyof PaymentMethodTestIds) => (testIds[k] ? { 'data-testid': testIds[k] } : {})\n\n const [fallback, setFallback] = useState(false)\n const [ready, setReady] = useState(false)\n const [processing, setProcessing] = useState(false)\n const [expired, setExpired] = useState(false)\n const brick = useRef<PaymentBrickHandle>(null)\n\n const cardChosen = selected?.mode === 'card' && !retryAddress && !addressFirst\n const cardActive = hydrated && cardChosen && !fallback\n\n // The server total must hold the chosen delivery before the card form mounts, and before any total is printed on the\n // button: the shop saves it on the cart and re-reads the cart. Once per delivery, for every payment row (cash and\n // redirect included, otherwise the button and the summary show the cart without shipping).\n const wantSync = hydrated && selected !== null && !addressFirst && !retryAddress && deliveryReady && Boolean(syncDelivery)\n const [sync, setSync] = useState<{ key: string; ok: boolean; requote?: boolean } | null>(null)\n const syncRef = useRef(syncDelivery)\n syncRef.current = syncDelivery\n useEffect(() => {\n if (!wantSync || !syncRef.current) return\n if (sync?.key === delivery && sync.ok) return\n let cancelled = false\n syncRef.current(delivery).then(\n (ok) => !cancelled && setSync(ok === 'requote' ? { key: delivery, ok: false, requote: true } : { key: delivery, ok }),\n () => !cancelled && setSync({ key: delivery, ok: false }),\n )\n return () => {\n cancelled = true\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [wantSync, delivery])\n const settled = sync?.key === delivery\n const synced = !syncDelivery || (settled && sync!.ok)\n const requote = wantSync && settled && sync!.requote === true\n const syncFailed = wantSync && settled && !sync!.ok && !requote\n const brickReady = cardActive && deliveryReady && synced && !syncFailed\n\n const transport = useMemo(\n () =>\n props.transport ??\n createFetchTransport(payUrl, {\n ...(statusUrl ? { refreshUrl: statusUrl } : {}),\n buildBody: (request) => ({ ...request, fields: formFields(formRef.current) }),\n }),\n [props.transport, payUrl, statusUrl, formRef],\n )\n\n const handleEvent = (e: PaymentEvent) => {\n if (e.type === 'form_ready') setReady(true)\n if (e.type === 'submit') setProcessing(true)\n if (e.type === 'tokenize_error' || e.type === 'retry') setProcessing(e.type === 'retry')\n if (e.type === 'result' && e.status === 'rejected') setProcessing(false)\n if (e.type === 'error') {\n setProcessing(false)\n if (e.kind === 'price_mismatch') onAmountChanged?.()\n if (e.kind === 'expired') setExpired(true)\n }\n onEvent?.(e)\n }\n\n // The buyer's e-mail from the page form: the provider form then skips its own e-mail block. Read on mount and on\n // every committed change of that field; a form mounted before the e-mail was typed is mounted again once with it.\n const [payerEmail, setPayerEmail] = useState<string | undefined>(undefined)\n useEffect(() => {\n const form = formRef.current\n if (!payerEmailField || !form) return\n const selector = `[name=\"${typeof CSS !== 'undefined' && CSS.escape ? CSS.escape(payerEmailField) : payerEmailField}\"]`\n const read = () => {\n const v = String(form.querySelector<HTMLInputElement>(selector)?.value ?? '').trim()\n setPayerEmail(EMAIL_RE.test(v) ? v : undefined)\n }\n read()\n const onChange = (e: Event) => {\n if ((e.target as HTMLInputElement | null)?.name === payerEmailField) read()\n }\n form.addEventListener('change', onChange)\n return () => form.removeEventListener('change', onChange)\n }, [formRef, payerEmailField])\n\n // While the delivery is being saved the amount is stale: the button reads without it.\n const total = wantSync && (!settled || requote) ? null : renderAmount ? renderAmount(amount) : formatMoney(amount, locale)\n const label: ReactNode = retryAddress ? (\n m.retryAddress\n ) : addressFirst ? (\n m.continue\n ) : !deliveryReady && selected ? (\n // Says what is missing instead of a button that silently does nothing.\n m.chooseDelivery\n ) : selected?.mode === 'cash' ? (\n <>\n {m.placeOrderCash}\n {total ? <> {total}</> : null}\n </>\n ) : selected?.mode === 'plain' || !selected ? (\n <>\n {m.pay}\n {total ? <> {total}</> : null}\n </>\n ) : selected.mode === 'redirect' || (selected.mode === 'card' && (fallback || syncFailed)) ? (\n m.payRedirect\n ) : (\n <>\n {m.placeOrder}\n {total ? <> {total}</> : null}\n </>\n )\n\n function onPayClick(event: MouseEvent<HTMLButtonElement>) {\n // No delivery yet: point at it (the browser or the shop's validation explains the required field) instead of paying.\n if (!addressFirst && !retryAddress && !deliveryReady && selected) {\n event.preventDefault()\n formRef.current?.reportValidity()\n return\n }\n // Redirect, cash, plain method, or a card without a usable form: the page form's normal submit.\n if (!cardActive || syncFailed) return\n event.preventDefault()\n const form = formRef.current\n if (form && !form.reportValidity()) return // required fields: the browser explains which is missing\n if (brickReady) void brick.current?.submit()\n }\n\n const cardNotice = (k: 'syncing' | 'syncFailed' | 'pickDelivery' | 'requote', node: ReactNode) =>\n k === 'syncFailed' ? (\n <p role=\"alert\" className={cx.alert} data-sf-pay-notice=\"sync-failed\" {...tid('syncFailed')}>\n {node}\n </p>\n ) : (\n <p role=\"status\" className={cx.status} data-sf-pay-notice={k} {...(k === 'syncing' ? tid('syncing') : {})}>\n {node}\n </p>\n )\n\n const Link = renderLink ?? (({ href, className, children, testId }) => (\n <a href={href} className={className} {...(testId ? { 'data-testid': testId } : {})}>\n {children}\n </a>\n ))\n\n return (\n <fieldset id=\"pago\" ref={rootRef} className={cx.root} data-sf-pay-method>\n <legend className={cx.legend}>{m.legend}</legend>\n {choices.choices.map((choice) => {\n const { label: rowLabel, hint } = rowText(choice, m, methodLabel)\n const checked = choice.value === choiceValue\n const slot = choice.option ?? 'plain'\n const icon = icons?.[slot] ?? (brandMarks ? defaultIcon(choice) : null)\n const marks = brandMarks ? rowMarks(choice, cardBrands) : []\n const brandMarkIcon = !icons?.[slot] && brandMarks && choice.option !== 'card' && choice.option !== 'cash' && !!findBrand(choice.methodKey)\n return (\n <div key={choice.value} className={cx.choice} data-sf-pay-choice>\n <label className={cx.radioLabel}>\n <input\n type=\"radio\"\n name={PAYMENT_CHOICE_FIELD}\n value={choice.value}\n checked={checked}\n onChange={() => setChoiceValue(choice.value)}\n aria-invalid={invalid?.has('payment_method') || undefined}\n data-mode={choice.mode}\n required\n className={cx.radio}\n {...tid('method')}\n />\n {icon ? (\n // The default mark of a provider row is as wide as its logo: it does not take the shop's `icon` box (a fixed\n // square would let the logo spill over the radio and the text).\n <span className={brandMarkIcon ? undefined : cx.icon} data-sf-pay-icon={brandMarkIcon ? 'mark' : undefined} aria-hidden=\"true\">\n {icon}\n </span>\n ) : null}\n <span className={cx.labelText}>\n {rowLabel}\n {hint ? <span className={cx.hint}> {hint}</span> : null}\n </span>\n {marks.length ? (\n <span className={cx.brands} data-sf-pay-brands={choice.option ?? 'plain'} aria-hidden=\"true\">\n {marks.map((mk) => (\n <BrandMark key={mk.key} brand={mk.key} logoUrl={mk.logoUrl ?? null} size={20} />\n ))}\n </span>\n ) : null}\n </label>\n {/* Always in the HTML and visible only with its radio checked (payments.css :has): without JavaScript the cash point is also chosen. */}\n <ChoicePanel choice={choice} m={m} invalid={invalid} cx={cx} tid={tid} hidden={hydrated && !checked} marks={brandMarks} visible={cashPointsVisible} openMore={storedPoint} onPointChange={onPointChange} />\n {/* The card form opens right under its own row (not after every row), so it reads as part of that choice. */}\n {choice.mode === 'card' && checked && cardChosen && hydrated && choices.cardClient ? (\n <div className={cx.brickWrap} data-sf-pay-card {...tid('card')}>\n {fallback\n ? null\n : !deliveryReady\n ? cardNotice('pickDelivery', m.pickDeliveryFirst)\n : syncFailed\n ? cardNotice('syncFailed', m.syncFailed)\n : requote\n ? cardNotice('requote', m.quoteChanged)\n : !synced\n ? cardNotice('syncing', m.updatingTotal)\n : null}\n {brickReady || fallback ? (\n <PaymentBrick\n key={payerEmail || brickProps?.email ? 'with-email' : 'without-email'}\n {...brickProps}\n ref={brick}\n client={choices.cardClient}\n amount={amount}\n transport={transport}\n {...(nonce ? { nonce } : {})}\n locale={locale}\n {...(scope ? { scope } : {})}\n {...(payerEmail && !brickProps?.email ? { email: payerEmail } : {})}\n enabled={brickReady}\n {...(cx.brick ? { className: cx.brick } : {})}\n onEvent={handleEvent}\n onFallback={() => setFallback(true)}\n onResult={(o) => {\n // Approved, under review or voucher: the order is already closed and the receipt is in the cookie.\n if (o.kind === 'approved' || o.kind === 'in_review' || o.kind === 'voucher') onDone(o)\n }}\n />\n ) : null}\n <p className={cx.note}>{m.secureCard}</p>\n {expired && rebuildHref ? Link({ href: rebuildHref, ...(cx.rebuild ? { className: cx.rebuild } : {}), children: m.rebuildCart, ...(testIds.rebuild ? { testId: testIds.rebuild } : {}) }) : null}\n </div>\n ) : null}\n </div>\n )\n })}\n\n {noPayment ? (\n <div role=\"alert\" className={cx.alert} data-sf-pay-notice=\"no-payment\" {...tid('noPayment')}>\n <p>\n <strong>{m.noPaymentTitle}</strong>\n </p>\n <p>{m.noPayment}</p>\n </div>\n ) : null}\n\n {noPayment || choices.choices.some((c) => c.option) ? null : <p className={cx.note}>{m.paymentNote}</p>}\n\n {hideSubmit ? null : (\n <button\n type=\"submit\"\n onClick={onPayClick}\n className={cx.submit}\n disabled={busy || blocked}\n aria-disabled={blocked || (brickReady && (!ready || processing)) || undefined}\n aria-busy={processing || undefined}\n data-sf-pay-method-submit\n {...tid('submit')}\n >\n {busy || processing ? m.processing : label}\n </button>\n )}\n </fieldset>\n )\n}\n\nfunction rowText(choice: PayChoice, m: PaymentMethodMessages, methodLabel: PaymentMethodSectionProps['methodLabel']): { label: string; hint?: string } {\n if (choice.mode === 'plain') return methodLabel ? methodLabel(choice.methodKey) : { label: choice.methodKey }\n return { label: choice.label ?? (choice.option ? m.options[choice.option] : undefined) ?? choice.option ?? choice.methodKey }\n}\n\nfunction ChoicePanel({\n choice,\n m,\n invalid,\n cx,\n tid,\n hidden,\n marks = true,\n visible,\n openMore,\n onPointChange,\n}: {\n choice: PayChoice\n m: PaymentMethodMessages\n invalid: ReadonlySet<string> | undefined\n cx: PaymentMethodClassNames\n tid: (k: keyof PaymentMethodTestIds) => { 'data-testid'?: string }\n hidden: boolean\n marks?: boolean\n visible?: number | undefined\n openMore?: string | null\n onPointChange?: (point: string) => void\n}) {\n if (choice.mode === 'redirect') {\n return (\n <p className={cx.panel} hidden={hidden} data-sf-pay-panel=\"redirect\" {...tid('redirectNote')}>\n {m.redirectNote}\n </p>\n )\n }\n if (choice.mode !== 'cash') return null\n const allMain = choice.points.filter((p) => p.group === 'main')\n const cut = typeof visible === 'number' && visible > 0 ? visible : allMain.length\n const main = allMain.slice(0, cut)\n const more = [...allMain.slice(cut), ...choice.points.filter((p) => p.group !== 'main')]\n const moreOpen = Boolean(openMore && more.some((p) => p.id === openMore))\n const row = (p: PayChoice['points'][number], i: number, first: boolean) => (\n <label key={p.id} className={cx.cashPoint} data-sf-pay-point>\n <input\n type=\"radio\"\n name={CASH_POINT_FIELD}\n value={p.id}\n defaultChecked={first && i === 0}\n className={cx.cashPointInput}\n aria-invalid={invalid?.has('cash_point') || undefined}\n {...(onPointChange ? { onChange: () => onPointChange(p.id) } : {})}\n />\n {marks ? <BrandMark brand={p.payment_point || p.id} logoUrl={p.logo_url ?? null} size={22} /> : null}\n <span>{p.label}</span>\n </label>\n )\n return (\n <div className={cx.panel} hidden={hidden} data-sf-pay-panel=\"cash\" {...tid('cash')}>\n <fieldset>\n <legend>{m.cashPoints}</legend>\n <div data-sf-pay-points>{main.map((p, i) => row(p, i, true))}</div>\n {more.length ? (\n <details {...(moreOpen ? { open: true } : {})}>\n <summary className={cx.cashMore} style={{ minHeight: 44 }}>\n {m.cashMore}\n </summary>\n <div data-sf-pay-points>{more.map((p, i) => row(p, i, false))}</div>\n </details>\n ) : null}\n </fieldset>\n <p className={cx.note}>{m.cashNote}</p>\n </div>\n )\n}\n\nconst glyph = (d: string) => (\n <svg viewBox=\"0 0 24 24\" width=\"24\" height=\"24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.7\" strokeLinecap=\"round\" strokeLinejoin=\"round\" focusable=\"false\" data-sf-pay-glyph>\n <path d={d} />\n </svg>\n)\nconst CARD_GLYPH = 'M3 6.5h18v11H3zM3 10h18M6.5 14.5h4'\nconst CASH_GLYPH = 'M3 7h18v10H3zM12 14.5a2.5 2.5 0 1 0 0-5a2.5 2.5 0 0 0 0 5zM6 10v4M18 10v4'\n\n/** Leading icon of a row: the provider's mark on its own account / no-card rows; a neutral glyph for card and cash. */\nfunction defaultIcon(choice: PayChoice): ReactNode {\n // By option, not mode: a card row without the in-page form still is a card.\n if (choice.option === 'card') return glyph(CARD_GLYPH)\n if (choice.option === 'cash') return glyph(CASH_GLYPH)\n return findBrand(choice.methodKey) ? <BrandMark brand={choice.methodKey} size={24} /> : null\n}\n\nfunction readCheckedPoint(root: HTMLElement | null): string | null {\n const el = root?.querySelector<HTMLInputElement>(`input[name=\"${CASH_POINT_FIELD}\"]:checked`)\n return el?.value ?? null\n}\n\n/** Trailing marks of a row: card networks on the card row, the first cash points on the cash row. */\nfunction rowMarks(choice: PayChoice, cardBrands: readonly string[]): Array<{ key: string; logoUrl?: string | null }> {\n if (choice.option === 'card') return cardBrands.map((key) => ({ key }))\n if (choice.option === 'cash') {\n const seen = new Set<string>()\n const out: Array<{ key: string; logoUrl?: string | null }> = []\n for (const p of choice.points) {\n const key = p.payment_point || p.id\n if (p.group !== 'main' || seen.has(key)) continue\n seen.add(key)\n out.push({ key, logoUrl: p.logo_url ?? null })\n if (out.length === 4) break\n }\n return out\n }\n return []\n}\n"]}
|