@openrails/billing-ui 0.230.0 → 0.234.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/CHANGELOG.md +117 -9
- package/README.md +88 -39
- package/dist/account/account-billing.d.ts +3 -3
- package/dist/account/cancel-dialog.d.ts +2 -2
- package/dist/account/format.d.ts +4 -4
- package/dist/account/payment-methods-panel.d.ts +7 -9
- package/dist/account/section.d.ts +3 -1
- package/dist/checkout-page.d.ts +6 -1
- package/dist/client/client.d.ts +81 -62
- package/dist/client/generated/currencies.d.ts +1 -0
- package/dist/client/generated/error-codes.d.ts +7 -0
- package/dist/client/generated/routes.d.ts +764 -0
- package/dist/client/generated/wire.d.ts +772 -0
- package/dist/client/index.d.ts +3 -3
- package/dist/client/types.d.ts +498 -393
- package/dist/client-CWX6QpLa.js +920 -0
- package/dist/client-CWX6QpLa.js.map +1 -0
- package/dist/client.js +2 -3
- package/dist/components/methods.d.ts +3 -3
- package/dist/config-DZ97SQG2.js +341 -0
- package/dist/config-DZ97SQG2.js.map +1 -0
- package/dist/frame.d.ts +1 -1
- package/dist/index.d.ts +4 -4
- package/dist/index.js +1447 -1539
- package/dist/index.js.map +1 -1
- package/dist/lib/billing.d.ts +14 -0
- package/dist/lib/money.d.ts +1 -0
- package/dist/lib/period.d.ts +0 -2
- package/dist/lib/rail-meta.d.ts +4 -4
- package/dist/locales/de.js +11 -8
- package/dist/locales/de.js.map +1 -1
- package/dist/locales/en.d.ts +8 -5
- package/dist/locales/en.js +11 -8
- package/dist/locales/en.js.map +1 -1
- package/dist/locales/es.js +11 -8
- package/dist/locales/es.js.map +1 -1
- package/dist/locales/ja.js +11 -8
- package/dist/locales/ja.js.map +1 -1
- package/dist/locales/ko.js +11 -8
- package/dist/locales/ko.js.map +1 -1
- package/dist/locales/zh.js +11 -8
- package/dist/locales/zh.js.map +1 -1
- package/dist/psp.d.ts +10 -21
- package/dist/react/config.d.ts +34 -0
- package/dist/react/context.d.ts +5 -8
- package/dist/react/hooks.d.ts +20 -14
- package/dist/react/index.d.ts +1 -0
- package/dist/react/provider.d.ts +1 -9
- package/dist/react/remote.d.ts +0 -1
- package/dist/react.js +24 -28
- package/dist/react.js.map +1 -1
- package/dist/save-payment-method.d.ts +1 -1
- package/dist/source.d.ts +0 -9
- package/dist/styles.css +1 -1
- package/dist/types.d.ts +114 -55
- package/docs/payment-form-contract.md +23 -40
- package/package.json +3 -3
- package/dist/client/generated/openrails-routes.d.ts +0 -2
- package/dist/client-DhG2jv34.js +0 -771
- package/dist/client-DhG2jv34.js.map +0 -1
- package/dist/errors-T-PRm3vV.js +0 -54
- package/dist/errors-T-PRm3vV.js.map +0 -1
- package/dist/hooks-DLFF-zx5.js +0 -285
- package/dist/hooks-DLFF-zx5.js.map +0 -1
- package/docs/1055-nmi-host-integration.md +0 -28
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/i18n/messages.ts","../src/i18n/context.ts","../src/appearance.ts","../src/scope-context.ts","../src/provider.tsx","../src/scope.tsx","../src/components/ui/button.tsx","../src/lib/period.ts","../src/account/format.ts","../src/components/ui/card.tsx","../src/components/ui/skeleton.tsx","../src/account/section.tsx","../src/components/ui/badge.tsx","../src/account/status-badge.tsx","../src/account/payment-history.tsx","../src/lib/card-brands.ts","../src/components/card-brands.tsx","../src/components/ui/alert-dialog.tsx","../src/components/ui/dialog.tsx","../src/components/ui/spinner.tsx","../src/psp.ts","../src/components/ui/input.tsx","../src/components/ui/label.tsx","../src/lib/billing.ts","../src/components/billing-fields.tsx","../src/components/card-fields.tsx","../src/components/pay-button.tsx","../src/lib/stripe.ts","../src/lib/collect.ts","../src/lib/stripe-appearance.ts","../src/components/stripe-card.tsx","../src/lib/card-entry.ts","../src/tokenized-card-form.tsx","../src/save-payment-method.tsx","../src/account/notice.tsx","../src/account/payment-methods-panel.tsx","../src/components/ui/textarea.tsx","../src/account/cancel-dialog.tsx","../src/components/ui/radio-group.tsx","../src/account/change-card-dialog.tsx","../src/account/subscriptions-panel.tsx","../src/account/account-billing.tsx","../src/authenticate.ts","../src/components/ccbill-fields.tsx","../src/lib/ccbill.ts","../src/lib/rail-meta.ts","../src/components/methods.tsx","../src/components/qr.tsx","../src/components/saved-methods.tsx","../src/components/summary.tsx","../src/components/states.tsx","../src/lib/redirect.ts","../src/checkout.tsx","../src/modal.tsx","../src/frame.ts","../src/checkout-page.tsx","../src/checkout-frame.tsx","../src/source.ts","../src/fixtures.ts"],"sourcesContent":["import { en } from \"../locales/en.ts\"\n\n/**\n * A count-dependent message: CLDR plural categories for the locale, with\n * `other` required. An exact-count key (`\"1\"`) wins over the category, like\n * ICU's `=1`, for locales whose single form differs from `{count}` (毎日).\n */\nexport type PluralMessage = {\n [K in Intl.LDMLPluralRule | \"1\"]?: string\n} & { other: string }\n\ntype Widen<T> = {\n [K in keyof T]: T[K] extends string\n ? string\n : T[K] extends PluralMessage\n ? PluralMessage\n : Widen<T[K]>\n}\n\n/** The complete message tree; English is the reference shape. */\nexport type BillingUiMessages = Widen<typeof en>\n\ntype DeepPartial<T> = {\n [K in keyof T]?: T[K] extends string\n ? string\n : T[K] extends PluralMessage\n ? Partial<PluralMessage>\n : DeepPartial<T[K]>\n}\n\n/** A locale bundle or host override: any subset of the tree. */\nexport type BillingUiMessageBundle = DeepPartial<BillingUiMessages>\n\ntype Paths<T, P extends string = \"\"> = {\n [K in keyof T & string]: T[K] extends string\n ? `${P}${K}`\n : T[K] extends PluralMessage\n ? never\n : Paths<T[K], `${P}${K}.`>\n}[keyof T & string]\n\ntype PluralPaths<T, P extends string = \"\"> = {\n [K in keyof T & string]: T[K] extends string\n ? never\n : T[K] extends PluralMessage\n ? `${P}${K}`\n : PluralPaths<T[K], `${P}${K}.`>\n}[keyof T & string]\n\n/** Dotted key of any message, e.g. `subscriptions.title`. */\nexport type MessageKey = Paths<BillingUiMessages>\n\n/** Dotted key of a count-dependent message, e.g. `interval.every.day`. */\nexport type PluralKey = PluralPaths<BillingUiMessages>\n\nexport type MessageVars = Record<string, string | number>\n\n/**\n * Host translation hook. Receives the bare key (`subscriptions.title`,\n * `errors.not_found`); return nothing or the key itself to use ours.\n */\nexport type BillingUiTranslate = (\n key: string,\n vars?: MessageVars\n) => string | null | undefined\n\n/** Types a locale bundle or override against the message tree. */\nexport function defineMessages(\n bundle: BillingUiMessageBundle\n): BillingUiMessageBundle {\n return bundle\n}\n\nexport const defaultMessages: BillingUiMessages = en\n\ntype Tree = { [key: string]: string | Tree }\n\nfunction mergeInto(target: Tree, source: Tree): Tree {\n const out: Tree = { ...target }\n for (const [key, value] of Object.entries(source)) {\n if (value === undefined || value === null) continue\n const current = out[key]\n if (typeof value === \"string\") {\n if (value !== \"\") out[key] = value\n } else if (typeof current === \"object\") {\n out[key] = mergeInto(current, value)\n } else {\n out[key] = mergeInto({}, value)\n }\n }\n return out\n}\n\n/** Layers bundles over English; later bundles win, missing keys fall back. */\nexport function resolveMessages(\n bundles?: BillingUiMessageBundle | readonly BillingUiMessageBundle[]\n): BillingUiMessages {\n const list = bundles ? (Array.isArray(bundles) ? bundles : [bundles]) : []\n let tree = en as unknown as Tree\n for (const bundle of list) tree = mergeInto(tree, bundle as Tree)\n return tree as unknown as BillingUiMessages\n}\n\nexport function interpolate(template: string, vars?: MessageVars): string {\n if (!vars) return template\n return template.replace(/\\{(\\w+)\\}/g, (match, name: string) =>\n name in vars ? String(vars[name]) : match\n )\n}\n\nfunction lookup(messages: BillingUiMessages, key: string): string | undefined {\n let node: unknown = messages\n for (const part of key.split(\".\")) {\n if (!node || typeof node !== \"object\") return undefined\n node = (node as Tree)[part]\n }\n return typeof node === \"string\" ? node : undefined\n}\n\nexport interface Translator {\n messages: BillingUiMessages\n /** BCP 47 tag used for plural rules and numbers; the runtime's when unset. */\n locale?: string\n t(key: MessageKey, vars?: MessageVars): string\n /**\n * Count-dependent message: tries `<key>.<count>`, then the locale's plural\n * category, then `<key>.other`. `{count}` is locale-formatted.\n */\n plural(key: PluralKey, count: number, vars?: MessageVars): string\n /** Message for an billing error, error code, or thrown value. */\n error(error: unknown, vars?: MessageVars): string\n}\n\nfunction errorCode(error: unknown): string | undefined {\n if (typeof error === \"string\") return error\n if (error && typeof error === \"object\" && \"code\" in error) {\n const code = (error as { code: unknown }).code\n if (typeof code === \"string\") return code\n }\n return undefined\n}\n\nfunction isNetworkError(error: unknown): boolean {\n return error instanceof TypeError && /fetch|network/i.test(error.message)\n}\n\nfunction pluralRules(locale?: string): Intl.PluralRules {\n try {\n return new Intl.PluralRules(locale)\n } catch {\n return new Intl.PluralRules(\"en\")\n }\n}\n\nfunction formatCount(count: number, locale?: string): string {\n try {\n return new Intl.NumberFormat(locale).format(count)\n } catch {\n return String(count)\n }\n}\n\nexport function createTranslator(\n messages: BillingUiMessages,\n hostT?: BillingUiTranslate,\n locale?: string\n): Translator {\n const rules = pluralRules(locale)\n const translate = (key: string, vars?: MessageVars): string | undefined => {\n const hosted = hostT?.(key, vars)\n if (hosted && hosted !== key) return hosted\n const own = lookup(messages, key)\n return own === undefined ? undefined : interpolate(own, vars)\n }\n return {\n messages,\n locale,\n t: (key, vars) => translate(key, vars) ?? key,\n plural(key, count, vars) {\n const all = { ...vars, count: formatCount(count, locale) }\n return (\n translate(`${key}.${count}`, all) ??\n translate(`${key}.${rules.select(count)}`, all) ??\n translate(`${key}.other`, all) ??\n key\n )\n },\n error(error, vars) {\n const code = errorCode(error)\n if (code && code !== \"generic\" && code !== \"network\") {\n const metadata =\n error && typeof error === \"object\" && \"metadata\" in error\n ? (error as { metadata?: MessageVars }).metadata\n : undefined\n const message = translate(`errors.${code}`, { ...metadata, ...vars })\n if (message) return message\n }\n const fallback = isNetworkError(error)\n ? \"errors.network\"\n : \"errors.generic\"\n return translate(fallback, vars) ?? messages.errors.generic\n },\n }\n}\n","import { createContext, useContext } from \"react\"\n\nimport {\n createTranslator,\n defaultMessages,\n type Translator,\n} from \"./messages.ts\"\n\nexport const MessagesContext = createContext<Translator>(\n createTranslator(defaultMessages)\n)\n\n/** English defaults when rendered outside an `BillingUiProvider`. */\nexport function useMessages(): Translator {\n return useContext(MessagesContext)\n}\n","// Integrator theming. The component scopes the standard shadcn token set\n// under its root, so `theme` flips the whole palette and `variables` override\n// individual tokens without the integrator touching our CSS.\nimport type { CSSProperties } from \"react\"\n\n// `inherit` uses the host page's shadcn tokens (`--background`, ...) and its\n// `.dark` class instead of the bundled zinc palette.\nexport type CheckoutTheme = \"light\" | \"dark\" | \"auto\" | \"inherit\"\n\n// The tokens integrators may override. Values are raw CSS color/length\n// strings; they land as custom properties on the checkout root.\nexport interface CheckoutVariables {\n background?: string\n foreground?: string\n card?: string\n mutedForeground?: string\n faintForeground?: string\n border?: string\n input?: string\n primary?: string\n primaryForeground?: string\n destructive?: string\n ring?: string\n radius?: string\n fontFamily?: string\n}\n\nexport interface CheckoutAppearance {\n theme?: CheckoutTheme\n variables?: CheckoutVariables\n}\n\nconst VARIABLE_TO_CSS: Record<keyof CheckoutVariables, string> = {\n background: \"--background\",\n foreground: \"--foreground\",\n card: \"--card\",\n mutedForeground: \"--muted-foreground\",\n faintForeground: \"--orck-faint\",\n border: \"--border\",\n input: \"--input\",\n primary: \"--primary\",\n primaryForeground: \"--primary-foreground\",\n destructive: \"--destructive\",\n ring: \"--ring\",\n radius: \"--radius\",\n fontFamily: \"--orck-font\",\n}\n\nexport function appearanceStyle(\n appearance: CheckoutAppearance | undefined\n): CSSProperties | undefined {\n const variables = appearance?.variables\n if (!variables) return undefined\n const style: Record<string, string> = {}\n for (const [key, value] of Object.entries(variables)) {\n if (!value) continue\n style[VARIABLE_TO_CSS[key as keyof CheckoutVariables]] = value\n }\n return style as CSSProperties\n}\n\nexport function appearanceTheme(\n appearance: CheckoutAppearance | undefined\n): CheckoutTheme {\n return appearance?.theme ?? \"auto\"\n}\n","import { createContext, useContext, type CSSProperties } from \"react\"\n\nimport {\n appearanceStyle,\n appearanceTheme,\n type CheckoutAppearance,\n type CheckoutTheme,\n} from \"./appearance\"\n\nexport type Navigate = (to: string) => void\n\nexport interface UiSettings {\n appearance?: CheckoutAppearance\n locale?: string\n navigate?: Navigate\n}\n\nexport const UiContext = createContext<UiSettings>({})\n\nexport const useUiSettings = (): UiSettings => useContext(UiContext)\n\nexport interface ScopeProps {\n className: string\n \"data-orck-theme\": CheckoutTheme\n style?: CSSProperties\n}\n\n/** Props that make an element a styling root; portals carry them too. */\nexport function useScopeProps(appearance?: CheckoutAppearance): ScopeProps {\n const settings = useUiSettings()\n const resolved = appearance ?? settings.appearance\n return {\n className: \"orck\",\n \"data-orck-theme\": appearanceTheme(resolved),\n style: appearanceStyle(resolved),\n }\n}\n","import { useMemo, type ReactNode } from \"react\"\n\nimport type { CheckoutAppearance } from \"./appearance\"\nimport { MessagesContext } from \"./i18n/context\"\nimport {\n createTranslator,\n resolveMessages,\n type BillingUiMessageBundle,\n type BillingUiTranslate,\n} from \"./i18n/messages\"\nimport { UiContext, type Navigate } from \"./scope-context\"\n\nexport interface BillingUiProviderProps {\n appearance?: CheckoutAppearance\n /** Locale bundle(s) layered over English; later entries win. */\n messages?: BillingUiMessageBundle | readonly BillingUiMessageBundle[]\n /** Host translation hook, consulted before the bundles. */\n t?: BillingUiTranslate\n /** BCP 47 tag for dates, money and plurals; defaults to the browser's. */\n locale?: string\n /** Host router for in-app links (e.g. the plans page). */\n navigate?: Navigate\n children?: ReactNode\n}\n\n/** Renders no DOM; surfaces create their own styling roots. */\nexport function BillingUiProvider({\n appearance,\n messages,\n t,\n locale,\n navigate,\n children,\n}: BillingUiProviderProps) {\n const translator = useMemo(\n () => createTranslator(resolveMessages(messages), t, locale),\n [messages, t, locale]\n )\n const ui = useMemo(\n () => ({ appearance, locale, navigate }),\n [appearance, locale, navigate]\n )\n return (\n <UiContext.Provider value={ui}>\n <MessagesContext.Provider value={translator}>\n {children}\n </MessagesContext.Provider>\n </UiContext.Provider>\n )\n}\n","import type { ComponentProps } from \"react\"\n\nimport type { CheckoutAppearance } from \"./appearance\"\nimport { cn } from \"cn\"\nimport { useScopeProps } from \"./scope-context\"\n\n/** Styling root for in-page billing surfaces. */\nexport function BillingUiRoot({\n appearance,\n className,\n style,\n ...props\n}: ComponentProps<\"div\"> & { appearance?: CheckoutAppearance }) {\n const scope = useScopeProps(appearance)\n return (\n <div\n data-orck-theme={scope[\"data-orck-theme\"]}\n className={cn(scope.className, className)}\n style={{ ...scope.style, ...style }}\n {...props}\n />\n )\n}\n","import { Button as ButtonPrimitive } from \"@base-ui/react/button\"\nimport { cva, type VariantProps } from \"class-variance-authority\"\nimport { cn } from \"cn\"\n\nconst buttonVariants = cva(\n \"group/button inline-flex shrink-0 items-center justify-center rounded-md border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4\",\n {\n variants: {\n variant: {\n default: \"bg-primary text-primary-foreground hover:bg-primary/80\",\n outline:\n \"border-border bg-background shadow-xs hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50\",\n secondary:\n \"bg-secondary text-secondary-foreground hover:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)] aria-expanded:bg-secondary aria-expanded:text-secondary-foreground\",\n ghost:\n \"hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50\",\n destructive:\n \"bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40\",\n link: \"text-primary underline-offset-4 hover:underline\",\n },\n size: {\n default:\n \"h-9 gap-1.5 px-2.5 in-data-[slot=button-group]:rounded-md has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2\",\n xs: \"h-6 gap-1 rounded-[min(var(--radius-md),8px)] px-2 text-xs in-data-[slot=button-group]:rounded-md has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3\",\n sm: \"h-8 gap-1 rounded-[min(var(--radius-md),10px)] px-2.5 in-data-[slot=button-group]:rounded-md has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5\",\n lg: \"h-10 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2\",\n icon: \"size-9\",\n \"icon-xs\":\n \"size-6 rounded-[min(var(--radius-md),8px)] in-data-[slot=button-group]:rounded-md [&_svg:not([class*='size-'])]:size-3\",\n \"icon-sm\":\n \"size-8 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-md\",\n \"icon-lg\": \"size-10\",\n },\n },\n defaultVariants: {\n variant: \"default\",\n size: \"default\",\n },\n }\n)\n\nfunction Button({\n className,\n variant = \"default\",\n size = \"default\",\n ...props\n}: ButtonPrimitive.Props & VariantProps<typeof buttonVariants>) {\n return (\n <ButtonPrimitive\n data-slot=\"button\"\n className={cn(buttonVariants({ variant, size, className }))}\n {...props}\n />\n )\n}\n\nexport { Button, buttonVariants }\n","import type { Translator } from \"../i18n/messages\"\n\n// OpenRails durations are exact hours (720h is 30 days, never \"a month\"), so\n// labels name only units that divide the window exactly.\nexport type PeriodUnit = \"hour\" | \"day\" | \"week\"\n\nexport interface Period {\n unit: PeriodUnit\n count: number\n}\n\nexport function periodOf(hours: number | null | undefined): Period | null {\n if (!hours || !Number.isSafeInteger(hours) || hours <= 0) return null\n if (hours % 168 === 0) return { unit: \"week\", count: hours / 168 }\n if (hours % 24 === 0) return { unit: \"day\", count: hours / 24 }\n return { unit: \"hour\", count: hours }\n}\n\n/** Hours from an OpenRails interval (`\"720h\"`, `\"720h0m0s\"`). */\nexport function intervalHours(interval: string | null | undefined) {\n const match = /^(\\d+)h(?:0m(?:0s)?)?$/.exec(interval?.trim() ?? \"\")\n return match ? Number(match[1]) : null\n}\n\n/** \"every 30 days\" */\nexport function everyLabel(hours: number | null | undefined, m: Translator) {\n const p = periodOf(hours)\n return p ? m.plural(`interval.every.${p.unit}`, p.count) : null\n}\n\n/** \"/ 30 days\" */\nexport function perLabel(hours: number | null | undefined, m: Translator) {\n const p = periodOf(hours)\n return p ? m.plural(`interval.per.${p.unit}`, p.count) : null\n}\n\n/** \"30 days of access\", for a window that does not renew. */\nexport function accessLabel(hours: number | null | undefined, m: Translator) {\n const p = periodOf(hours)\n return p ? m.plural(`interval.access.${p.unit}`, p.count) : null\n}\n","import type {\n CardSummary,\n CurrencyScales,\n Payment,\n Subscription,\n SubscriptionPrice,\n} from \"../client/types\"\nimport type { Translator } from \"../i18n/messages\"\nimport { formatAmount } from \"../lib/money\"\nimport { accessLabel, everyLabel, intervalHours } from \"../lib/period\"\n\nexport function formatDate(\n value: string | null | undefined,\n locale?: string\n): string | null {\n if (!value) return null\n const date = new Date(value)\n if (Number.isNaN(date.getTime())) return null\n try {\n return new Intl.DateTimeFormat(locale, { dateStyle: \"medium\" }).format(date)\n } catch {\n return date.toISOString().slice(0, 10)\n }\n}\n\n/** Exact money, or null while the currency's scale is unknown. */\nexport function formatMoney(\n amount: string | null | undefined,\n currency: string,\n scales: CurrencyScales,\n locale?: string\n): string | null {\n if (!amount) return null\n const decimals = scales[currency.toUpperCase()]\n if (decimals === undefined) return null\n return formatAmount(amount, currency, decimals, locale)\n}\n\n/** \"every 30 days\", \"30 days of access\" or \"one-time\". */\nexport function intervalLabel(\n price: SubscriptionPrice | null | undefined,\n m: Translator\n): string | null {\n if (!price) return null\n const hours = price.access_duration_hours\n if (price.auto_renew === false)\n return accessLabel(hours, m) ?? m.t(\"interval.once\")\n return everyLabel(hours, m)\n}\n\nexport function subscriptionName(s: Subscription, { t }: Translator): string {\n return (\n s.product?.display_name?.trim() ||\n s.price?.key?.trim() ||\n t(\"subscriptions.fallbackName\")\n )\n}\n\n/** What a payment bought: the product's name, else its kind, plus its cadence. */\nexport function paymentItem(\n p: Payment,\n m: Translator\n): { name: string; detail: string | null } {\n const hours = intervalHours(p.price?.recurring?.interval)\n const recurring =\n p.price?.type === \"recurring\" || hours !== null || !!p.subscription_id\n const name =\n p.product?.display_name?.trim() ||\n m.t(recurring ? \"history.subscription\" : \"history.purchase\")\n return { name, detail: recurring ? everyLabel(hours, m) : null }\n}\n\nexport function brandName(brand: string | null | undefined, fallback: string) {\n const value = brand?.trim()\n if (!value) return fallback\n return value[0].toUpperCase() + value.slice(1).toLowerCase()\n}\n\n/** \"Visa •••• 4242 · 12/30\"; the brand alone when no digits are known. */\nexport function cardText(\n card: CardSummary | null | undefined,\n m: Translator\n): string {\n const brand = brandName(card?.brand, m.t(\"paymentMethods.fallbackBrand\"))\n if (!card?.last4) return brand\n const label = m.t(\"paymentMethods.cardLabel\", { brand, last4: card.last4 })\n const expires = expiry(card)\n return expires ? `${label} · ${expires}` : label\n}\n\nexport function expiry(card: CardSummary | null | undefined): string | null {\n if (!card?.exp_month || !card.exp_year) return null\n return `${String(card.exp_month).padStart(2, \"0\")}/${String(card.exp_year).slice(-2)}`\n}\n\nexport const LIVE_STATUSES = new Set([\n \"active\",\n \"pending\",\n \"past_due\",\n \"awaiting_method\",\n \"unverified\",\n])\n\nconst future = (at: string | null | undefined) =>\n !!at && new Date(at).getTime() > Date.now()\n\n/** Still grants access: live, or cancelled with the paid period running. */\nexport const isLive = (s: Subscription) =>\n LIVE_STATUSES.has(s.status) ||\n (s.status === \"cancelled\" &&\n (!!s.cancel_scheduled || !!s.resumable) &&\n future(s.current_period_ends_at))\n\n/** Access ends at period end and nothing renews it. */\nexport const isEnding = (s: Subscription) =>\n isLive(s) && (!!s.cancel_scheduled || s.status === \"cancelled\")\n\nexport type StatusTone = \"success\" | \"warning\" | \"destructive\" | \"neutral\"\n\nconst TONE: Record<string, StatusTone> = {\n active: \"success\",\n succeeded: \"success\",\n paid: \"success\",\n default: \"neutral\",\n pending: \"warning\",\n past_due: \"warning\",\n awaiting_method: \"warning\",\n cancel_scheduled: \"warning\",\n expiring_soon: \"warning\",\n needs_attention: \"warning\",\n partially_refunded: \"neutral\",\n failed: \"destructive\",\n expired: \"destructive\",\n cancelled: \"neutral\",\n canceled: \"neutral\",\n refunded: \"neutral\",\n}\n\nexport const statusTone = (status: string): StatusTone =>\n TONE[status] ?? \"neutral\"\n\n// The package ships no preflight, so account surfaces zero UA text margins.\nexport const RESET =\n \"[&_h2]:m-0 [&_p]:m-0 [&_ul]:m-0 [&_ul]:list-none [&_ul]:p-0 [&_table]:border-spacing-0\"\n","import * as React from \"react\"\nimport { cn } from \"cn\"\n\nfunction Card({\n className,\n size = \"default\",\n ...props\n}: React.ComponentProps<\"div\"> & { size?: \"default\" | \"sm\" }) {\n return (\n <div\n data-slot=\"card\"\n data-size={size}\n className={cn(\n \"group/card flex flex-col gap-(--card-spacing) overflow-hidden rounded-xl bg-card py-(--card-spacing) text-sm text-card-foreground shadow-xs ring-1 ring-foreground/10 [--card-spacing:--spacing(6)] has-[>img:first-child]:pt-0 data-[size=sm]:[--card-spacing:--spacing(4)] *:[img:first-child]:rounded-t-xl *:[img:last-child]:rounded-b-xl\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction CardHeader({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-header\"\n className={cn(\n \"group/card-header @container/card-header grid auto-rows-min items-start gap-1 rounded-t-xl px-(--card-spacing) has-data-[slot=card-action]:grid-cols-[1fr_auto] has-data-[slot=card-description]:grid-rows-[auto_auto] [.border-b]:pb-(--card-spacing)\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction CardTitle({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-title\"\n className={cn(\n \"text-base leading-normal font-medium group-data-[size=sm]/card:text-sm\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction CardDescription({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-description\"\n className={cn(\"text-sm text-muted-foreground\", className)}\n {...props}\n />\n )\n}\n\nfunction CardAction({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-action\"\n className={cn(\n \"col-start-2 row-span-2 row-start-1 self-start justify-self-end\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction CardContent({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-content\"\n className={cn(\"flex flex-col gap-3 px-(--card-spacing)\", className)}\n {...props}\n />\n )\n}\n\nfunction CardFooter({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-footer\"\n className={cn(\n \"flex items-center rounded-b-xl px-(--card-spacing) [.border-t]:pt-(--card-spacing)\",\n className\n )}\n {...props}\n />\n )\n}\n\nexport {\n Card,\n CardHeader,\n CardFooter,\n CardTitle,\n CardAction,\n CardDescription,\n CardContent,\n}\n","import { cn } from \"cn\"\n\nfunction Skeleton({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"skeleton\"\n className={cn(\"animate-pulse rounded-md bg-muted\", className)}\n {...props}\n />\n )\n}\n\nexport { Skeleton }\n","import * as React from \"react\"\nimport { cn } from \"cn\"\n\nimport type { CheckoutAppearance } from \"#orck/appearance\"\nimport type { BillingError } from \"#orck/client/errors\"\nimport { Button } from \"#orck/components/ui/button\"\nimport {\n Card,\n CardAction,\n CardContent,\n CardDescription,\n CardHeader,\n CardTitle,\n} from \"#orck/components/ui/card\"\nimport { Skeleton } from \"#orck/components/ui/skeleton\"\nimport { useMessages } from \"#orck/i18n/context\"\nimport { useScopeProps } from \"#orck/scope-context\"\nimport { RESET } from \"./format\"\n\nexport interface SectionProps {\n title: string\n description?: string\n action?: React.ReactNode\n appearance?: CheckoutAppearance\n className?: string\n children?: React.ReactNode\n \"data-testid\"?: string\n}\n\n// Styling root plus card. Each panel is usable alone, so each is a root.\nexport function Section({\n title,\n description,\n action,\n appearance,\n className,\n children,\n ...rest\n}: SectionProps) {\n const scope = useScopeProps(appearance)\n const id = React.useId()\n return (\n <section\n aria-labelledby={id}\n className={cn(scope.className, RESET, \"block\", className)}\n data-orck-theme={scope[\"data-orck-theme\"]}\n style={scope.style}\n data-testid={rest[\"data-testid\"]}\n >\n <Card className=\"gap-4 bg-card text-card-foreground\">\n <CardHeader>\n <CardTitle id={id} role=\"heading\" aria-level={2}>\n {title}\n </CardTitle>\n {description ? (\n <CardDescription>{description}</CardDescription>\n ) : null}\n {action ? <CardAction>{action}</CardAction> : null}\n </CardHeader>\n <CardContent className=\"gap-0\">{children}</CardContent>\n </Card>\n </section>\n )\n}\n\nexport function ListSkeleton({ rows = 2 }: { rows?: number }) {\n return (\n <div className=\"grid gap-4 py-2\" aria-hidden>\n {Array.from({ length: rows }, (_, i) => (\n <div key={i} className=\"flex items-center gap-3\">\n <Skeleton className=\"h-7 w-11 rounded-md\" />\n <div className=\"grid flex-1 gap-2\">\n <Skeleton className=\"h-3.5 w-40\" />\n <Skeleton className=\"h-3 w-28\" />\n </div>\n <Skeleton className=\"h-3.5 w-14\" />\n </div>\n ))}\n </div>\n )\n}\n\nexport function EmptyState({\n title,\n description,\n action,\n}: {\n title: string\n description?: string\n action?: React.ReactNode\n}) {\n return (\n <div className=\"grid justify-items-center gap-1 rounded-lg border border-dashed px-4 py-8 text-center\">\n <p className=\"text-sm font-medium\">{title}</p>\n {description ? (\n <p className=\"text-sm text-muted-foreground\">{description}</p>\n ) : null}\n {action ? <div className=\"mt-3\">{action}</div> : null}\n </div>\n )\n}\n\nexport function ErrorState({\n error,\n onRetry,\n}: {\n error: BillingError\n onRetry: () => void\n}) {\n const m = useMessages()\n return (\n <div\n role=\"alert\"\n className=\"flex flex-wrap items-center justify-between gap-3 rounded-lg bg-destructive/5 px-4 py-3\"\n >\n <p className=\"text-sm text-destructive\">{m.error(error)}</p>\n <Button variant=\"outline\" size=\"sm\" onClick={onRetry}>\n {m.t(\"common.retry\")}\n </Button>\n </div>\n )\n}\n","import { mergeProps } from \"@base-ui/react/merge-props\"\nimport { useRender } from \"@base-ui/react/use-render\"\nimport { cva, type VariantProps } from \"class-variance-authority\"\nimport { cn } from \"cn\"\n\nconst badgeVariants = cva(\n \"group/badge inline-flex h-5 w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-4xl border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-all focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3!\",\n {\n variants: {\n variant: {\n default: \"bg-primary text-primary-foreground [a]:hover:bg-primary/80\",\n secondary:\n \"bg-secondary text-secondary-foreground [a]:hover:bg-secondary/80\",\n destructive:\n \"bg-destructive/10 text-destructive focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:focus-visible:ring-destructive/40 [a]:hover:bg-destructive/20\",\n outline:\n \"border-border text-foreground [a]:hover:bg-muted [a]:hover:text-muted-foreground\",\n ghost:\n \"hover:bg-muted hover:text-muted-foreground dark:hover:bg-muted/50\",\n link: \"text-primary underline-offset-4 hover:underline\",\n },\n },\n defaultVariants: {\n variant: \"default\",\n },\n }\n)\n\nfunction Badge({\n className,\n variant = \"default\",\n render,\n ...props\n}: useRender.ComponentProps<\"span\"> & VariantProps<typeof badgeVariants>) {\n return useRender({\n defaultTagName: \"span\",\n props: mergeProps<\"span\">(\n {\n className: cn(badgeVariants({ variant }), className),\n },\n props\n ),\n render,\n state: {\n slot: \"badge\",\n variant,\n },\n })\n}\n\nexport { Badge, badgeVariants }\n","import { cn } from \"cn\"\n\nimport { Badge } from \"#orck/components/ui/badge\"\nimport { useMessages } from \"#orck/i18n/context\"\nimport type { MessageKey } from \"#orck/i18n/messages\"\nimport { statusTone, type StatusTone } from \"./format\"\n\nconst TONE_CLASS: Record<StatusTone, string> = {\n success: \"bg-[color:var(--orck-success)]/12 text-[color:var(--orck-success)]\",\n warning: \"bg-[color:var(--orck-warning)]/14 text-[color:var(--orck-warning)]\",\n destructive: \"bg-destructive/10 text-destructive\",\n neutral: \"bg-muted text-muted-foreground\",\n}\n\nexport interface BillingStatusBadgeProps {\n /** Subscription, payment or card-health status. */\n status: string\n /** Overrides the translated label. */\n label?: string\n className?: string\n}\n\nexport function BillingStatusBadge({\n status,\n label,\n className,\n}: BillingStatusBadgeProps) {\n const { t, messages } = useMessages()\n const key = status === \"canceled\" ? \"cancelled\" : status\n const text =\n label ??\n (key in messages.status\n ? t(`status.${key}` as MessageKey)\n : status.replace(/_/g, \" \"))\n return (\n <Badge\n data-status={status}\n className={cn(TONE_CLASS[statusTone(status)], \"font-medium\", className)}\n >\n {text}\n </Badge>\n )\n}\n","import * as React from \"react\"\nimport { cn } from \"cn\"\n\nimport type { CheckoutAppearance } from \"#orck/appearance\"\nimport type { Payment } from \"#orck/client/types\"\nimport { Button } from \"#orck/components/ui/button\"\nimport { useMessages } from \"#orck/i18n/context\"\nimport type { MessageKey, Translator } from \"#orck/i18n/messages\"\nimport { usePayments, type PaymentsOptions } from \"#orck/react/hooks\"\nimport { useBillingClient } from \"#orck/react/context\"\nimport { useUiSettings } from \"#orck/scope-context\"\nimport { cardText, formatDate, formatMoney, paymentItem } from \"./format\"\nimport { EmptyState, ErrorState, ListSkeleton, Section } from \"./section\"\nimport { BillingStatusBadge } from \"./status-badge\"\n\nexport interface PaymentHistoryProps extends PaymentsOptions {\n appearance?: CheckoutAppearance\n className?: string\n}\n\nfunction methodText(p: Payment, m: Translator): string {\n if (p.card?.last4) return cardText(p.card, m)\n const rail = p.rail ?? \"\"\n return rail in m.messages.history.rail\n ? m.t(`history.rail.${rail}` as MessageKey)\n : rail || m.t(\"common.notAvailable\")\n}\n\nexport function PaymentHistory({\n appearance,\n className,\n ...options\n}: PaymentHistoryProps) {\n const m = useMessages()\n const { t } = m\n const { locale } = useUiSettings()\n const state = usePayments(options)\n const scales = useBillingClient().currencies\n\n let body: React.ReactNode\n const payments = state.payments\n if (payments === null && state.error) {\n body = <ErrorState error={state.error} onRetry={state.refetch} />\n } else if (payments === null) {\n body = <ListSkeleton rows={3} />\n } else if (payments.length === 0 && state.page === 0) {\n body = (\n <EmptyState\n title={t(\"history.empty\")}\n description={t(\"history.emptyDescription\")}\n />\n )\n } else {\n body = (\n <div className=\"-mx-1 overflow-x-auto px-1\">\n <table\n className={cn(\n \"w-full border-collapse text-sm\",\n state.loading && \"opacity-60 transition-opacity\"\n )}\n aria-busy={state.loading || undefined}\n >\n <thead>\n <tr className=\"border-b text-left text-xs text-muted-foreground\">\n <th\n scope=\"col\"\n className=\"hidden py-2 pr-3 font-medium @md:table-cell\"\n >\n {t(\"history.date\")}\n </th>\n <th scope=\"col\" className=\"py-2 pr-3 font-medium\">\n {t(\"history.item\")}\n </th>\n <th\n scope=\"col\"\n className=\"hidden py-2 pr-3 font-medium @md:table-cell\"\n >\n {t(\"history.method\")}\n </th>\n <th scope=\"col\" className=\"py-2 pr-3 font-medium\">\n {t(\"history.status\")}\n </th>\n <th scope=\"col\" className=\"py-2 text-right font-medium\">\n {t(\"history.amount\")}\n </th>\n </tr>\n </thead>\n <tbody className=\"divide-y divide-border\">\n {payments.map((p) => {\n const refund = p.object === \"refund\"\n const status = p.status || (refund ? \"refunded\" : \"unknown\")\n const amount = formatMoney(p.amount, p.currency, scales, locale)\n const refunded =\n !refund && p.amount_refunded && p.amount_refunded !== \"0\"\n ? formatMoney(p.amount_refunded, p.currency, scales, locale)\n : null\n const date =\n formatDate(p.created_at, locale) ?? t(\"common.notAvailable\")\n const item = paymentItem(p, m)\n return (\n <tr key={p.id} data-testid=\"payment-row\" data-payment-id={p.id}>\n <td className=\"hidden py-3 pr-3 align-top whitespace-nowrap tabular-nums @md:table-cell\">\n {date}\n </td>\n <td className=\"py-3 pr-3 align-top\">\n <div data-testid=\"payment-item\" className=\"font-medium\">\n {item.name}\n </div>\n {p.status === \"failed\" && p.failure?.message ? (\n <div\n data-testid=\"payment-failure\"\n className=\"text-xs text-destructive\"\n >\n {p.failure.message}\n </div>\n ) : null}\n {item.detail ? (\n <div\n data-testid=\"payment-period\"\n className=\"text-xs text-muted-foreground\"\n >\n {item.detail}\n </div>\n ) : null}\n <div className=\"text-xs text-muted-foreground tabular-nums @md:hidden\">\n {date} · {methodText(p, m)}\n </div>\n </td>\n <td className=\"hidden py-3 pr-3 align-top text-muted-foreground tabular-nums @md:table-cell\">\n {methodText(p, m)}\n </td>\n <td className=\"py-3 pr-3 align-top\">\n <BillingStatusBadge\n status={status}\n label={refund ? t(\"history.refund\") : undefined}\n />\n </td>\n <td className=\"py-3 text-right align-top font-medium whitespace-nowrap tabular-nums\">\n {amount ?? t(\"common.notAvailable\")}\n {refunded ? (\n <div className=\"text-xs font-normal text-muted-foreground\">\n {t(\"history.refundedAmount\", { amount: refunded })}\n </div>\n ) : null}\n </td>\n </tr>\n )\n })}\n </tbody>\n </table>\n </div>\n )\n }\n\n const paged = state.page > 0 || state.hasMore\n return (\n <Section\n title={t(\"history.title\")}\n description={t(\"history.description\")}\n appearance={appearance}\n className={className}\n data-testid=\"payment-history\"\n >\n {body}\n {payments !== null && state.error ? (\n <div className=\"pt-3\">\n <ErrorState error={state.error} onRetry={state.refetch} />\n </div>\n ) : null}\n {paged ? (\n <nav\n aria-label={t(\"history.title\")}\n className=\"flex items-center justify-between gap-3 pt-4\"\n >\n <span className=\"text-xs text-muted-foreground tabular-nums\">\n {t(\"history.page\", { page: state.page + 1 })}\n </span>\n <div className=\"flex gap-2\">\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={state.page === 0 || state.loading}\n onClick={state.previous}\n >\n {t(\"common.previous\")}\n </Button>\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={!state.hasMore || state.loading}\n onClick={state.next}\n >\n {t(\"common.next\")}\n </Button>\n </div>\n </nav>\n ) : null}\n </Section>\n )\n}\n","// Card-network identity: which marks we ship and how a rail's spelling maps\n// onto them.\nexport type CardBrand = \"visa\" | \"mastercard\" | \"amex\"\n\nconst BRAND_ALIASES: Record<string, CardBrand> = {\n visa: \"visa\",\n mastercard: \"mastercard\",\n mc: \"mastercard\",\n master: \"mastercard\",\n amex: \"amex\",\n americanexpress: \"amex\",\n \"american express\": \"amex\",\n}\n\n// Resolves the rail's spelling of a brand (\"Visa\", \"MASTERCARD\", \"amex\") onto\n// the marks we ship; anything unknown falls back to a text plate.\nexport function resolveCardBrand(brand?: string): CardBrand | undefined {\n const key = brand\n ?.trim()\n .toLowerCase()\n .replace(/[^a-z ]/g, \"\")\n return key ? BRAND_ALIASES[key] : undefined\n}\n","// Card network marks, inlined rather than fetched: this package is meant to\n// run inside someone else's app, where an asset URL of ours would 404. Artwork\n// is each network's own published symbol, unmodified in shape and color.\nimport * as React from \"react\"\n\nimport { resolveCardBrand } from \"#orck/lib/card-brands\"\nimport { cn } from \"cn\"\n\nfunction VisaMark() {\n return (\n <svg viewBox=\"0 0 1000 324.68\" className=\"h-2.5 w-auto\" role=\"presentation\">\n <path\n fill=\"#1434cb\"\n d=\"m651.19.5c-70.93,0-134.32,36.77-134.32,104.69,0,77.9,112.42,83.28,112.42,122.42,0,16.48-18.88,31.23-51.14,31.23-45.77,0-79.98-20.61-79.98-20.61l-14.64,68.55s39.41,17.41,91.73,17.41c77.55,0,138.58-38.57,138.58-107.66,0-82.32-112.89-87.54-112.89-123.86,0-12.91,15.5-27.05,47.66-27.05,36.29,0,65.89,14.99,65.89,14.99l14.33-66.2S696.61.5,651.18.5h0ZM2.22,5.5L.5,15.49s29.84,5.46,56.72,16.36c34.61,12.49,37.07,19.77,42.9,42.35l63.51,244.83h85.14L379.93,5.5h-84.94l-84.28,213.17-34.39-180.7c-3.15-20.68-19.13-32.48-38.68-32.48,0,0-135.41,0-135.41,0Zm411.87,0l-66.63,313.53h81L494.85,5.5h-80.76Zm451.76,0c-19.53,0-29.88,10.46-37.47,28.73l-118.67,284.8h84.94l16.43-47.47h103.48l9.99,47.47h74.95L934.12,5.5h-68.27Zm11.05,84.71l25.18,117.65h-67.45l42.28-117.65h0Z\"\n />\n </svg>\n )\n}\n\nfunction MastercardMark() {\n return (\n <svg viewBox=\"0 0 152.4 108\" className=\"h-4 w-auto\" role=\"presentation\">\n <g>\n <rect y=\"0\" fill=\"none\" width=\"152.4\" height=\"108\" />\n <g>\n <rect x=\"60.4\" y=\"25.7\" fill=\"#FF5F00\" width=\"31.5\" height=\"56.6\" />\n <path\n fill=\"#EB001B\"\n d=\"M62.4,54c0-11,5.1-21.5,13.7-28.3c-15.6-12.3-38.3-9.6-50.6,6.1C13.3,47.4,16,70,31.7,82.3\n\t\t\tc13.1,10.3,31.4,10.3,44.5,0C67.5,75.5,62.4,65,62.4,54z\"\n />\n <path\n fill=\"#F79E1B\"\n d=\"M134.4,54c0,19.9-16.1,36-36,36c-8.1,0-15.9-2.7-22.2-7.7c15.6-12.3,18.3-34.9,6-50.6c-1.8-2.2-3.8-4.3-6-6\n\t\t\tc15.6-12.3,38.3-9.6,50.5,6.1C131.7,38.1,134.4,45.9,134.4,54z\"\n />\n </g>\n </g>\n </svg>\n )\n}\n\nfunction AmexMark() {\n const gradientId = `orck-amex-${React.useId().replace(/[^a-zA-Z0-9-]/g, \"\")}`\n return (\n <svg viewBox=\"0 0 300 300\" className=\"h-full w-auto\" role=\"presentation\">\n <radialGradient\n id={gradientId}\n cx=\"57.3882\"\n cy=\"57.021\"\n r=\"264.5797\"\n gradientUnits=\"userSpaceOnUse\"\n >\n <stop offset=\"0\" stopColor=\"#9DD5F6\" />\n <stop offset=\"0.0711\" stopColor=\"#98D3F5\" />\n <stop offset=\"0.1575\" stopColor=\"#89CEF3\" />\n <stop offset=\"0.2516\" stopColor=\"#70C6EF\" />\n <stop offset=\"0.3514\" stopColor=\"#4EBBEA\" />\n <stop offset=\"0.4546\" stopColor=\"#23ADE3\" />\n <stop offset=\"0.5\" stopColor=\"#0DA6E0\" />\n <stop offset=\"1\" stopColor=\"#2E77BC\" />\n </radialGradient>\n <path\n fill={`url(#${gradientId})`}\n d=\"M289.584,7.598H7.639v282.966h281.945v-93.386c1.12-1.619,1.673-3.69,1.673-6.222\n\tc0-2.898-0.553-4.693-1.673-6.205\"\n />\n <g></g>\n <path\n fill=\"#FFFFFF\"\n d=\"M33.053,130.042l-5.424-13.217l-5.393,13.217 M152.543,124.779c-1.089,0.661-2.377,0.683-3.92,0.683h-9.627\n\tv-7.364h9.758c1.381,0,2.822,0.062,3.758,0.598c1.028,0.483,1.664,1.511,1.664,2.931\n\tC154.176,123.076,153.571,124.242,152.543,124.779z M221.221,130.042l-5.484-13.217l-5.454,13.217H221.221z M93.201,144.348h-8.124\n\tl-0.03-25.966l-11.491,25.966h-6.958l-11.521-25.989v25.989H38.959l-3.045-7.395h-16.5l-3.076,7.395H7.731l14.191-33.154h11.774\n\tl13.478,31.39v-31.39h12.934l10.371,22.491l9.527-22.491h13.194V144.348z M125.58,144.348H99.107v-33.154h26.473v6.904h-18.548\n\tv5.976h18.103v6.796h-18.103v6.621h18.548V144.348z M162.906,120.123c0,5.286-3.528,8.017-5.584,8.837\n\tc1.734,0.66,3.215,1.826,3.92,2.792c1.119,1.649,1.312,3.122,1.312,6.083v6.513h-7.993l-0.03-4.181c0-1.995,0.191-4.864-1.251-6.459\n\tc-1.158-1.166-2.923-1.419-5.776-1.419h-8.507v12.059h-7.924v-33.154h18.227c4.05,0,7.034,0.107,9.596,1.588\n\tC161.403,114.263,162.906,116.425,162.906,120.123z M175.588,144.348h-8.086v-33.154h8.086V144.348z M269.396,144.348h-11.23\n\tl-15.021-24.884v24.884h-16.139l-3.084-7.395H207.46l-2.992,7.395h-9.273c-3.852,0-8.729-0.852-11.491-3.667\n\tc-2.785-2.815-4.234-6.628-4.234-12.657c0-4.917,0.866-9.412,4.272-12.964c2.562-2.646,6.574-3.866,12.035-3.866h7.672v7.104h-7.511\n\tc-2.892,0-4.525,0.43-6.098,1.964c-1.351,1.396-2.278,4.035-2.278,7.51c0,3.552,0.706,6.113,2.179,7.786\n\tc1.22,1.312,3.437,1.71,5.523,1.71h3.559l11.169-26.073h11.874l13.417,31.359v-31.359h12.066l13.93,23.09v-23.09h8.117V144.348z\n\t M7.639,150.86h13.54l3.053-7.364h6.835l3.045,7.364h26.641v-5.63l2.378,5.654h13.83l2.378-5.738v5.714h66.208l-0.031-12.088h1.281\n\tc0.897,0.031,1.159,0.114,1.159,1.595v10.493h34.243v-2.814c2.762,1.48,7.058,2.814,12.711,2.814h14.406l3.083-7.364h6.835\n\tl3.015,7.364h27.761v-6.995l4.204,6.995h22.246v-46.24h-22.016v5.461l-3.083-5.461H228.77v5.461l-2.831-5.461h-30.515\n\tc-5.108,0-9.598,0.713-13.225,2.7v-2.7h-21.058v2.7c-2.308-2.048-5.453-2.7-8.95-2.7H75.258l-5.162,11.943l-5.301-11.943H40.563\n\tv5.461l-2.662-5.461H17.235l-9.597,21.985V150.86z\"\n />\n <path\n fill=\"#FFFFFF\"\n d=\"M289.584,175.315h-14.443c-1.442,0-2.4,0.054-3.207,0.599c-0.836,0.537-1.158,1.334-1.158,2.386\n\tc0,1.251,0.706,2.102,1.733,2.47c0.836,0.291,1.734,0.376,3.054,0.376l4.295,0.115c4.334,0.107,7.227,0.852,8.991,2.669\n\tc0.321,0.253,0.514,0.537,0.735,0.821 M289.584,197.178c-1.925,2.815-5.676,4.242-10.754,4.242h-15.304v-7.111h15.242\n\tc1.512,0,2.57-0.199,3.207-0.821c0.552-0.513,0.937-1.258,0.937-2.163c0-0.966-0.385-1.733-0.968-2.193\n\tc-0.575-0.506-1.412-0.736-2.792-0.736c-7.441-0.253-16.724,0.23-16.724-10.264c0-4.81,3.054-9.873,11.37-9.873h15.785v-6.598\n\th-14.666c-4.426,0-7.641,1.06-9.918,2.708v-2.708h-21.693c-3.469,0-7.541,0.86-9.467,2.708v-2.708h-38.738v2.708\n\tc-3.083-2.224-8.285-2.708-10.686-2.708h-25.552v2.708c-2.439-2.362-7.863-2.708-11.169-2.708h-28.597l-6.544,7.082l-6.129-7.082\n\tH63.706v46.272h41.914l6.743-7.194l6.352,7.194l25.836,0.023v-10.885h2.54c3.428,0.053,7.471-0.085,11.038-1.627v12.488h21.31\n\tv-12.06h1.028c1.312,0,1.441,0.054,1.441,1.365v10.694h64.736c4.11,0,8.406-1.052,10.785-2.961v2.961h20.534\n\tc4.273,0,8.446-0.599,11.621-2.133V197.178z M257.973,183.93c1.543,1.597,2.37,3.613,2.37,7.026c0,7.134-4.457,10.464-12.449,10.464\n\th-15.435v-7.111h15.373c1.503,0,2.569-0.199,3.237-0.821c0.545-0.513,0.936-1.258,0.936-2.163c0-0.966-0.423-1.733-0.967-2.193\n\tc-0.606-0.506-1.442-0.736-2.822-0.736c-7.411-0.253-16.692,0.23-16.692-10.264c0-4.81,3.022-9.873,11.33-9.873h15.887v7.058\n\th-14.537c-1.441,0-2.378,0.054-3.175,0.599c-0.868,0.537-1.19,1.334-1.19,2.386c0,1.251,0.737,2.102,1.734,2.47\n\tc0.836,0.291,1.734,0.376,3.084,0.376l4.266,0.115C253.225,181.368,256.178,182.112,257.973,183.93z M186.465,181.882\n\tc-1.06,0.629-2.371,0.683-3.913,0.683h-9.627v-7.448h9.758c1.411,0,2.823,0.03,3.782,0.599c1.027,0.537,1.641,1.564,1.641,2.983\n\tS187.492,181.261,186.465,181.882z M191.251,186.009c1.764,0.651,3.206,1.818,3.882,2.784c1.119,1.619,1.281,3.13,1.313,6.053v6.574\n\th-7.956v-4.149c0-1.995,0.192-4.949-1.281-6.491c-1.158-1.188-2.923-1.472-5.814-1.472h-8.469v12.112h-7.963v-33.162h18.296\n\tc4.012,0,6.934,0.177,9.535,1.565c2.501,1.511,4.074,3.581,4.074,7.364C196.867,182.48,193.337,185.181,191.251,186.009z\n\t M201.262,168.258h26.449v6.858h-18.557v6.029h18.104v6.766h-18.104v6.598l18.557,0.03v6.881h-26.449V168.258z M147.795,183.562\n\th-10.241v-8.445h10.333c2.861,0,4.847,1.166,4.847,4.066C152.734,182.051,150.84,183.562,147.795,183.562z M129.661,198.404\n\tl-12.167-13.508l12.167-13.079V198.404z M98.24,194.509H78.756v-6.598h17.398v-6.766H78.756v-6.029h19.868l8.668,9.664\n\tL98.24,194.509z M161.242,179.183c0,9.212-6.873,11.114-13.8,11.114h-9.888v11.123h-15.403l-9.758-10.978l-10.141,10.978h-31.39\n\tv-33.162h31.873l9.75,10.87l10.08-10.87h25.322C154.176,168.258,161.242,169.999,161.242,179.183z\"\n />\n </svg>\n )\n}\n\n// A fixed plate keeps every row's leading edge aligned whatever the mark's\n// aspect ratio.\nexport function CardBrandPlate({\n brand,\n fallback,\n className,\n}: {\n brand?: string\n fallback: string\n className?: string\n}) {\n const resolved = resolveCardBrand(brand)\n return (\n <span\n aria-hidden\n className={cn(\n \"grid h-7 w-11 shrink-0 place-items-center overflow-hidden rounded-md\",\n // White ground only because the marks are drawn for light surfaces —\n // on a light page it simply disappears and the mark stands alone.\n resolved\n ? \"bg-white\"\n : \"bg-muted text-[10px] font-semibold tracking-wide text-muted-foreground uppercase\",\n className\n )}\n >\n {resolved === \"visa\" ? (\n <VisaMark />\n ) : resolved === \"mastercard\" ? (\n <MastercardMark />\n ) : resolved === \"amex\" ? (\n <AmexMark />\n ) : (\n fallback\n )}\n </span>\n )\n}\n","\"use client\"\n\nimport * as React from \"react\"\nimport { AlertDialog as AlertDialogPrimitive } from \"@base-ui/react/alert-dialog\"\nimport { cn } from \"cn\"\n\nimport { Button } from \"#orck/components/ui/button\"\n\nfunction AlertDialog({ ...props }: AlertDialogPrimitive.Root.Props) {\n return <AlertDialogPrimitive.Root data-slot=\"alert-dialog\" {...props} />\n}\n\nfunction AlertDialogTrigger({ ...props }: AlertDialogPrimitive.Trigger.Props) {\n return (\n <AlertDialogPrimitive.Trigger data-slot=\"alert-dialog-trigger\" {...props} />\n )\n}\n\nfunction AlertDialogPortal({ ...props }: AlertDialogPrimitive.Portal.Props) {\n return (\n <AlertDialogPrimitive.Portal data-slot=\"alert-dialog-portal\" {...props} />\n )\n}\n\nfunction AlertDialogOverlay({\n className,\n ...props\n}: AlertDialogPrimitive.Backdrop.Props) {\n return (\n <AlertDialogPrimitive.Backdrop\n data-slot=\"alert-dialog-overlay\"\n className={cn(\n \"fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction AlertDialogContent({\n className,\n size = \"default\",\n ...props\n}: AlertDialogPrimitive.Popup.Props & {\n size?: \"default\" | \"sm\"\n}) {\n return (\n <AlertDialogPortal>\n <AlertDialogOverlay />\n <AlertDialogPrimitive.Popup\n data-slot=\"alert-dialog-content\"\n data-size={size}\n className={cn(\n \"group/alert-dialog-content fixed top-1/2 left-1/2 z-50 grid w-full -translate-x-1/2 -translate-y-1/2 gap-6 rounded-xl bg-popover p-6 text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none data-[size=default]:max-w-xs data-[size=sm]:max-w-xs data-[size=default]:sm:max-w-lg data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95\",\n className\n )}\n {...props}\n />\n </AlertDialogPortal>\n )\n}\n\nfunction AlertDialogHeader({\n className,\n ...props\n}: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"alert-dialog-header\"\n className={cn(\n \"grid grid-rows-[auto_1fr] place-items-center gap-1.5 text-center has-data-[slot=alert-dialog-media]:grid-rows-[auto_auto_1fr] has-data-[slot=alert-dialog-media]:gap-x-6 sm:group-data-[size=default]/alert-dialog-content:place-items-start sm:group-data-[size=default]/alert-dialog-content:text-left sm:group-data-[size=default]/alert-dialog-content:has-data-[slot=alert-dialog-media]:grid-rows-[auto_1fr]\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction AlertDialogFooter({\n className,\n ...props\n}: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"alert-dialog-footer\"\n className={cn(\n \"flex flex-col-reverse gap-2 group-data-[size=sm]/alert-dialog-content:grid group-data-[size=sm]/alert-dialog-content:grid-cols-2 sm:flex-row sm:justify-end\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction AlertDialogMedia({\n className,\n ...props\n}: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"alert-dialog-media\"\n className={cn(\n \"mb-2 inline-flex size-16 items-center justify-center rounded-md bg-muted sm:group-data-[size=default]/alert-dialog-content:row-span-2 *:[svg:not([class*='size-'])]:size-8\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction AlertDialogTitle({\n className,\n ...props\n}: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {\n return (\n <AlertDialogPrimitive.Title\n data-slot=\"alert-dialog-title\"\n className={cn(\n \"text-lg font-medium sm:group-data-[size=default]/alert-dialog-content:group-has-data-[slot=alert-dialog-media]/alert-dialog-content:col-start-2\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction AlertDialogDescription({\n className,\n ...props\n}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {\n return (\n <AlertDialogPrimitive.Description\n data-slot=\"alert-dialog-description\"\n className={cn(\n \"text-sm text-balance text-muted-foreground md:text-pretty *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction AlertDialogAction({\n className,\n ...props\n}: React.ComponentProps<typeof Button>) {\n return (\n <Button\n data-slot=\"alert-dialog-action\"\n className={cn(className)}\n {...props}\n />\n )\n}\n\nfunction AlertDialogCancel({\n className,\n variant = \"outline\",\n size = \"default\",\n ...props\n}: AlertDialogPrimitive.Close.Props &\n Pick<React.ComponentProps<typeof Button>, \"variant\" | \"size\">) {\n return (\n <AlertDialogPrimitive.Close\n data-slot=\"alert-dialog-cancel\"\n className={cn(className)}\n render={<Button variant={variant} size={size} />}\n {...props}\n />\n )\n}\n\nexport {\n AlertDialog,\n AlertDialogAction,\n AlertDialogCancel,\n AlertDialogContent,\n AlertDialogDescription,\n AlertDialogFooter,\n AlertDialogHeader,\n AlertDialogMedia,\n AlertDialogOverlay,\n AlertDialogPortal,\n AlertDialogTitle,\n AlertDialogTrigger,\n}\n","import * as React from \"react\"\nimport { Dialog as DialogPrimitive } from \"@base-ui/react/dialog\"\nimport { cn } from \"cn\"\n\nimport { Button } from \"#orck/components/ui/button\"\nimport { HugeiconsIcon } from \"@hugeicons/react\"\nimport { Cancel01Icon } from \"@hugeicons/core-free-icons\"\n\nfunction Dialog({ ...props }: DialogPrimitive.Root.Props) {\n return <DialogPrimitive.Root data-slot=\"dialog\" {...props} />\n}\n\nfunction DialogTrigger({ ...props }: DialogPrimitive.Trigger.Props) {\n return <DialogPrimitive.Trigger data-slot=\"dialog-trigger\" {...props} />\n}\n\nfunction DialogPortal({ ...props }: DialogPrimitive.Portal.Props) {\n return <DialogPrimitive.Portal data-slot=\"dialog-portal\" {...props} />\n}\n\nfunction DialogClose({ ...props }: DialogPrimitive.Close.Props) {\n return <DialogPrimitive.Close data-slot=\"dialog-close\" {...props} />\n}\n\nfunction DialogOverlay({\n className,\n ...props\n}: DialogPrimitive.Backdrop.Props) {\n return (\n <DialogPrimitive.Backdrop\n data-slot=\"dialog-overlay\"\n className={cn(\n \"fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction DialogContent({\n className,\n children,\n showCloseButton = true,\n ...props\n}: DialogPrimitive.Popup.Props & {\n showCloseButton?: boolean\n}) {\n return (\n <DialogPortal>\n <DialogOverlay />\n <DialogPrimitive.Popup\n data-slot=\"dialog-content\"\n className={cn(\n \"fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-6 rounded-xl bg-popover p-6 text-sm text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none sm:max-w-md data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95\",\n className\n )}\n {...props}\n >\n {children}\n {showCloseButton && (\n <DialogPrimitive.Close\n data-slot=\"dialog-close\"\n render={\n <Button\n variant=\"ghost\"\n className=\"absolute top-4 right-4\"\n size=\"icon-sm\"\n />\n }\n >\n <HugeiconsIcon icon={Cancel01Icon} strokeWidth={2} />\n <span className=\"sr-only\">Close</span>\n </DialogPrimitive.Close>\n )}\n </DialogPrimitive.Popup>\n </DialogPortal>\n )\n}\n\nfunction DialogHeader({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"dialog-header\"\n className={cn(\"flex flex-col gap-2\", className)}\n {...props}\n />\n )\n}\n\nfunction DialogFooter({\n className,\n showCloseButton = false,\n children,\n ...props\n}: React.ComponentProps<\"div\"> & {\n showCloseButton?: boolean\n}) {\n return (\n <div\n data-slot=\"dialog-footer\"\n className={cn(\n \"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end\",\n className\n )}\n {...props}\n >\n {children}\n {showCloseButton && (\n <DialogPrimitive.Close render={<Button variant=\"outline\" />}>\n Close\n </DialogPrimitive.Close>\n )}\n </div>\n )\n}\n\nfunction DialogTitle({ className, ...props }: DialogPrimitive.Title.Props) {\n return (\n <DialogPrimitive.Title\n data-slot=\"dialog-title\"\n className={cn(\"leading-none font-medium\", className)}\n {...props}\n />\n )\n}\n\nfunction DialogDescription({\n className,\n ...props\n}: DialogPrimitive.Description.Props) {\n return (\n <DialogPrimitive.Description\n data-slot=\"dialog-description\"\n className={cn(\n \"text-sm text-muted-foreground *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground\",\n className\n )}\n {...props}\n />\n )\n}\n\nexport {\n Dialog,\n DialogClose,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogOverlay,\n DialogPortal,\n DialogTitle,\n DialogTrigger,\n}\n","import { cn } from \"cn\"\nimport { HugeiconsIcon } from \"@hugeicons/react\"\nimport { Loading03Icon } from \"@hugeicons/core-free-icons\"\n\nimport { useMessages } from \"#orck/i18n/context\"\n\n// Local: HugeiconsIcon props, since its strokeWidth rejects the svg string type.\nfunction Spinner({\n className,\n ...props\n}: Omit<React.ComponentProps<typeof HugeiconsIcon>, \"icon\">) {\n const { t } = useMessages() // Local: i18n \"Loading\" label.\n return (\n <HugeiconsIcon\n icon={Loading03Icon}\n strokeWidth={2}\n data-slot=\"spinner\"\n role=\"status\"\n aria-label={t(\"common.loading\")}\n className={cn(\"size-4 animate-spin\", className)}\n {...props}\n />\n )\n}\n\nexport { Spinner }\n","// OpenRails's browser-safe PSP projection (GET /checkout-config, or the host's\n// copy of it). Hosts pass it through unchanged; which browser flow a PSP needs\n// is decided here, never by the host.\nimport { z } from \"zod\"\n\nimport type { PaymentMethod } from \"./client/types\"\nimport type { PaymentRailOption, SavedPaymentMethod } from \"./types\"\n\nexport const pspConfigSchema = z.object({\n psp_id: z.string().min(1),\n /** Checkout's `payment.rail` selector. */\n key: z.string().min(1),\n rail: z.string(),\n /** Who holds the card: \"psp\" or a third-party custodian. */\n custodian: z.string(),\n display_name: z.string(),\n /** `tokenize | card | elements | redirect | wallet` */\n flow: z.string(),\n config: z.record(z.string(), z.string()).nullish(),\n /**\n * New purchases and new cards use this PSP (the operator's checkout PSP).\n * Other PSPs stay listed so existing cards and subscriptions keep working.\n */\n checkout: z.boolean().nullish(),\n})\nexport type PspConfig = z.infer<typeof pspConfigSchema>\n\n/**\n * One way OpenRails can sell a price now (`ListCheckoutRailOptions`): the PSP\n * is armed and its rail supports the sale. OpenRails decides the browser\n * `driver` and `public_config`; an offer without a driver cannot run here.\n */\nexport interface CheckoutRailOffer {\n selector: string\n psp_id: string\n rail: string\n mode: string\n driver?: string | null\n public_config?: Record<string, string> | null\n}\n\nconst drivers = new Set<string>([\n \"collect_js\",\n \"card\",\n \"stripe_elements\",\n \"redirect\",\n \"solana_pay\",\n])\n\n/** The rails this UI can drive, exactly as OpenRails advertised them. */\nexport function checkoutRails(\n offers: readonly CheckoutRailOffer[]\n): PaymentRailOption[] {\n return offers.flatMap((offer) => {\n if (!offer.driver || !drivers.has(offer.driver)) return []\n return [\n {\n id: offer.psp_id,\n rail: offer.rail,\n mode: offer.mode === \"subscription\" ? \"subscription\" : \"one_off\",\n driver: offer.driver as PaymentRailOption[\"driver\"],\n psp_key: offer.selector,\n ...(offer.public_config ? { public_config: offer.public_config } : {}),\n },\n ]\n })\n}\n\nconst cardDrivers = new Set<PaymentRailOption[\"driver\"]>([\n \"collect_js\",\n \"card\",\n \"stripe_elements\",\n])\n\n/** Whether a rail takes a card in the page (saved or new). */\nexport const isCardRail = (rail: PaymentRailOption): boolean =>\n cardDrivers.has(rail.driver)\n\n/** PSPs that take new purchases and new cards. */\nexport const checkoutPsps = (psps: readonly PspConfig[]): PspConfig[] =>\n psps.filter((psp) => psp.checkout !== false)\n\n/**\n * Saved cards the checkout can charge in place, for the given rails: the\n * default first, then most recent.\n */\nexport function savedMethodsFor(\n methods: readonly PaymentMethod[],\n rails: readonly PaymentRailOption[]\n): SavedPaymentMethod[] {\n const recent = [...methods].sort(\n (a, b) =>\n Number(!!b.default) - Number(!!a.default) ||\n (b.created_at ?? \"\").localeCompare(a.created_at ?? \"\")\n )\n return recent.flatMap((method) => {\n const rail = rails.find(\n (item) => item.id === method.psp_id && isCardRail(item)\n )\n if (!rail || method.health?.active === false) return []\n return [\n {\n id: method.id,\n option_id: rail.id,\n rail: rail.rail,\n brand: method.card?.brand ?? undefined,\n last_four: method.card?.last4 ?? undefined,\n exp_month: method.card?.exp_month ?? undefined,\n exp_year: method.card?.exp_year ?? undefined,\n default: method.default ?? undefined,\n },\n ]\n })\n}\n\nexport type CardSetupDriver = \"collect_js\" | \"card\" | \"stripe_elements\"\n\nconst usable = (value?: string) => !!value && !value.startsWith(\"preview_\")\n\nconst stripeKey = (psp: PspConfig) =>\n psp.rail === \"stripe\" && !!psp.config?.publishable_key?.startsWith(\"pk_\")\n\n/** How a card is saved with this PSP in the page, or null when it cannot be. */\nexport function cardSetupDriver(psp: PspConfig): CardSetupDriver | null {\n if (psp.custodian !== \"psp\") return null\n // The PSP takes cards on OpenRails itself (card_entry: server).\n if (psp.flow === \"card\" && psp.rail === \"nmi\") return \"card\"\n if (\n psp.flow === \"tokenize\" &&\n usable(psp.config?.tokenization_key) &&\n !!psp.config?.tokenization_url\n )\n return \"collect_js\"\n if (stripeKey(psp)) return \"stripe_elements\"\n return null\n}\n\nexport const canSavePaymentMethod = (psp: PspConfig): boolean =>\n cardSetupDriver(psp) !== null\n\n/** Whether a pending payment on this PSP can be authenticated in the page. */\nexport const canAuthenticatePayment = (psp: PspConfig): boolean =>\n cardSetupDriver(psp) === \"stripe_elements\"\n\n/** The PSP config behind a checkout rail, for card setup and authentication. */\nexport function railPsp(rail: PaymentRailOption): PspConfig {\n return {\n psp_id: rail.id,\n key: rail.psp_key ?? rail.rail,\n rail: rail.rail,\n custodian: \"psp\",\n display_name: \"\",\n flow:\n rail.driver === \"stripe_elements\"\n ? \"elements\"\n : rail.driver === \"card\"\n ? \"card\"\n : \"tokenize\",\n config: rail.public_config ?? null,\n }\n}\n","import * as React from \"react\"\nimport { Input as InputPrimitive } from \"@base-ui/react/input\"\nimport { cn } from \"cn\"\n\nfunction Input({ className, type, ...props }: React.ComponentProps<\"input\">) {\n return (\n <InputPrimitive\n type={type}\n data-slot=\"input\"\n className={cn(\n \"h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-2.5 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40\",\n className\n )}\n {...props}\n />\n )\n}\n\nexport { Input }\n","import * as React from \"react\"\nimport { cn } from \"cn\"\n\nfunction Label({ className, ...props }: React.ComponentProps<\"label\">) {\n return (\n <label\n data-slot=\"label\"\n className={cn(\n \"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50\",\n className\n )}\n {...props}\n />\n )\n}\n\nexport { Label }\n","import { z } from \"zod\"\n\nconst ISO_COUNTRY_CODES =\n \"AD AE AF AG AI AL AM AO AQ AR AS AT AU AW AX AZ BA BB BD BE BF BG BH BI BJ BL BM BN BO BQ BR BS BT BV BW BY BZ CA CC CD CF CG CH CI CK CL CM CN CO CR CU CV CW CX CY CZ DE DJ DK DM DO DZ EC EE EG EH ER ES ET FI FJ FK FM FO FR GA GB GD GE GF GG GH GI GL GM GN GP GQ GR GS GT GU GW GY HK HM HN HR HT HU ID IE IL IM IN IO IQ IR IS IT JE JM JO JP KE KG KH KI KM KN KP KR KW KY KZ LA LB LC LI LK LR LS LT LU LV LY MA MC MD ME MF MG MH MK ML MM MN MO MP MQ MR MS MT MU MV MW MX MY MZ NA NC NE NF NG NI NL NO NP NR NU NZ OM PA PE PF PG PH PK PL PM PN PR PS PT PW PY QA RE RO RS RU RW SA SB SC SD SE SG SH SI SJ SK SL SM SN SO SR SS ST SV SX SY SZ TC TD TF TG TH TJ TK TL TM TN TO TR TT TV TW TZ UA UG UM US UY UZ VA VC VE VG VI VN VU WF WS YE YT ZA ZM ZW\".split(\n \" \"\n )\n\n// ISO-3166 alpha-2 projection of the UPU's \"List of countries which do not\n// require postal codes\" (Universal DataBase, September 2025). Keep a postal\n// code when a customer supplies one, but do not block tokenization when the\n// destination does not require it.\n// https://www.upu.int/UPU/media/upu/documents/PostCode/General-Addressing-Issues.pdf\nconst POSTAL_OPTIONAL_COUNTRIES = new Set([\n \"AE\",\n \"AG\",\n \"AO\",\n \"AQ\",\n \"AW\",\n \"BF\",\n \"BI\",\n \"BJ\",\n \"BO\",\n \"BQ\",\n \"BS\",\n \"BV\",\n \"BW\",\n \"BZ\",\n \"CF\",\n \"CG\",\n \"CI\",\n \"CK\",\n \"CM\",\n \"CW\",\n \"DM\",\n \"ER\",\n \"FJ\",\n \"GA\",\n \"GD\",\n \"GM\",\n \"GQ\",\n \"JM\",\n \"KM\",\n \"KP\",\n \"LY\",\n \"ML\",\n \"MR\",\n \"QA\",\n \"RW\",\n \"SB\",\n \"SC\",\n \"SL\",\n \"SO\",\n \"SR\",\n \"SS\",\n \"ST\",\n \"SX\",\n \"SY\",\n \"TD\",\n \"TG\",\n \"TK\",\n \"TO\",\n \"TV\",\n \"UM\",\n \"VU\",\n \"YE\",\n \"ZW\",\n])\n\nconst POSTAL_PLACEHOLDERS: Record<string, string> = {\n AR: \"C1000\",\n BR: \"01000-000\",\n CA: \"A1A 1A1\",\n CL: \"8320000\",\n CN: \"100000\",\n CO: \"110111\",\n DE: \"10115\",\n ES: \"28001\",\n JP: \"100-0001\",\n KR: \"04524\",\n MX: \"01000\",\n PE: \"15001\",\n US: \"12345\",\n}\n\nconst displayNames = new Intl.DisplayNames([\"en\"], { type: \"region\" })\n\nexport const COUNTRY_OPTIONS = ISO_COUNTRY_CODES.map((code) => ({\n code,\n name: displayNames.of(code) ?? code,\n})).sort((left, right) => left.name.localeCompare(right.name))\n\nexport const nameOnCardSchema = z\n .string()\n .trim()\n .min(1, \"Name on card is required\")\n .max(200, \"Name on card is too long\")\n\nexport const countryCodeSchema = z\n .string()\n .trim()\n .regex(/^[A-Za-z]{2}$/, \"Select a country\")\n .transform((value) => value.toUpperCase())\n\nexport function isPostalRequired(country: string): boolean {\n const code = country.trim().toUpperCase()\n return code === \"\" || !POSTAL_OPTIONAL_COUNTRIES.has(code)\n}\n\nexport function postalField(\n country: string,\n required: boolean\n): {\n label: string\n placeholder: string\n inputMode: \"numeric\" | \"text\"\n pattern?: string\n} {\n const code = country.trim().toUpperCase()\n const baseLabel =\n code === \"US\"\n ? \"ZIP code\"\n : code === \"GB\" || code === \"AU\" || code === \"NZ\"\n ? \"Postcode\"\n : \"Postal code\"\n return {\n label: required ? baseLabel : `${baseLabel} (optional)`,\n placeholder: POSTAL_PLACEHOLDERS[code] ?? baseLabel,\n inputMode: code === \"US\" ? \"numeric\" : \"text\",\n pattern: code === \"US\" ? \"[0-9]{5}(?:-[0-9]{4})?\" : undefined,\n }\n}\n\nexport const nmiBillingSchema = z\n .object({\n name_on_card: nameOnCardSchema,\n country: countryCodeSchema,\n zip: z.string().trim().max(32, \"Postal code is too long\"),\n })\n .superRefine((value, context) => {\n if (isPostalRequired(value.country) && !value.zip) {\n context.addIssue({\n code: \"custom\",\n message: `${postalField(value.country, true).label} is required`,\n path: [\"zip\"],\n })\n }\n if (\n value.country === \"US\" &&\n value.zip &&\n !/^\\d{5}(?:-\\d{4})?$/.test(value.zip)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"Enter a valid ZIP code\",\n path: [\"zip\"],\n })\n }\n })\n\nexport type NMIBilling = z.infer<typeof nmiBillingSchema>\n\nexport const emptyNMIBilling: NMIBilling = {\n name_on_card: \"\",\n country: \"\",\n zip: \"\",\n}\n\n/** The buyer's likely billing country from the browser locale, or \"\". */\nexport function browserCountry(): string {\n try {\n if (typeof navigator === \"undefined\" || !navigator.language) return \"\"\n const region = new Intl.Locale(navigator.language).maximize().region\n return region && /^[A-Z]{2}$/.test(region) ? region : \"\"\n } catch {\n return \"\"\n }\n}\n\n/** The host's country when it is a known code, else the browser's region. */\nexport function initialCountry(hostCountry?: string): string {\n const code = hostCountry?.trim().toUpperCase() ?? \"\"\n if (COUNTRY_OPTIONS.some((option) => option.code === code)) return code\n const region = browserCountry()\n return COUNTRY_OPTIONS.some((option) => option.code === region) ? region : \"\"\n}\n","import type * as React from \"react\"\n\nimport { Input } from \"#orck/components/ui/input\"\nimport { Label } from \"#orck/components/ui/label\"\nimport {\n COUNTRY_OPTIONS,\n isPostalRequired,\n postalField,\n type NMIBilling,\n} from \"#orck/lib/billing\"\n\nconst LABEL = \"text-[13px] font-medium text-foreground\"\nconst CONTROL =\n \"h-[38px] rounded-[9px] border border-input bg-card text-sm text-foreground\"\nconst INPUT = `${CONTROL} px-2.5`\n\nexport function BillingTextField({\n id,\n name,\n label,\n value,\n onChange,\n autoComplete,\n placeholder,\n disabled,\n maxLength,\n required,\n type,\n inputMode,\n pattern,\n}: {\n id: string\n name: string\n label: string\n value: string\n onChange: (value: string) => void\n autoComplete: string\n placeholder?: string\n disabled?: boolean\n maxLength?: number\n required?: boolean\n type?: React.HTMLInputTypeAttribute\n inputMode?: React.HTMLAttributes<HTMLInputElement>[\"inputMode\"]\n pattern?: string\n}) {\n return (\n <div className=\"grid gap-1.5\">\n <Label htmlFor={id} className={LABEL}>\n {label}\n </Label>\n <Input\n id={id}\n name={name}\n type={type}\n className={INPUT}\n value={value}\n autoComplete={autoComplete}\n placeholder={placeholder}\n disabled={disabled}\n maxLength={maxLength}\n required={required}\n inputMode={inputMode}\n pattern={pattern}\n onChange={(event) => onChange(event.target.value)}\n />\n </div>\n )\n}\n\nexport function CountryField({\n id,\n value,\n onChange,\n disabled,\n}: {\n id: string\n value: string\n onChange: (value: string) => void\n disabled?: boolean\n}) {\n return (\n <div className=\"grid gap-1.5\">\n <Label htmlFor={id} className={LABEL}>\n Country\n </Label>\n <select\n id={id}\n name=\"country\"\n className={`${CONTROL} w-full px-2.5`}\n value={value}\n autoComplete=\"billing country\"\n disabled={disabled}\n required\n onChange={(event) => onChange(event.target.value)}\n >\n <option value=\"\">Select country</option>\n {COUNTRY_OPTIONS.map((country) => (\n <option key={country.code} value={country.code}>\n {country.name}\n </option>\n ))}\n </select>\n </div>\n )\n}\n\nexport function PostalField({\n id,\n value,\n country,\n onChange,\n disabled,\n required,\n error,\n}: {\n id: string\n value: string\n country: string\n onChange: (value: string) => void\n disabled?: boolean\n required: boolean\n error?: string\n}) {\n const field = postalField(country, required)\n return (\n <div className=\"grid gap-1.5\">\n <BillingTextField\n id={id}\n name=\"zip\"\n label={field.label}\n value={value}\n onChange={onChange}\n autoComplete=\"billing postal-code\"\n placeholder={field.placeholder}\n disabled={disabled}\n maxLength={32}\n required={required}\n inputMode={field.inputMode}\n pattern={field.pattern}\n />\n {error ? (\n <p className=\"text-[12.5px] text-destructive\" role=\"alert\">\n {error}\n </p>\n ) : null}\n </div>\n )\n}\n\nexport function CardBillingFields({\n idPrefix,\n value,\n onChange,\n disabled,\n postalError,\n}: {\n idPrefix: string\n value: NMIBilling\n onChange: (next: NMIBilling) => void\n disabled?: boolean\n postalError?: string\n}) {\n const set = (key: keyof NMIBilling) => (next: string) =>\n onChange({ ...value, [key]: next })\n const postalRequired = isPostalRequired(value.country)\n return (\n <div className=\"grid gap-3\">\n <BillingTextField\n id={`${idPrefix}-name-on-card`}\n name=\"name_on_card\"\n label=\"Name on card\"\n value={value.name_on_card}\n onChange={set(\"name_on_card\")}\n autoComplete=\"cc-name\"\n placeholder=\"Name as shown on card\"\n disabled={disabled}\n maxLength={200}\n required\n />\n <div className=\"grid grid-cols-2 gap-3\">\n <CountryField\n id={`${idPrefix}-country`}\n value={value.country}\n onChange={set(\"country\")}\n disabled={disabled}\n />\n <PostalField\n id={`${idPrefix}-postal-code`}\n value={value.zip}\n country={value.country}\n onChange={set(\"zip\")}\n disabled={disabled}\n required={postalRequired}\n error={postalError}\n />\n </div>\n </div>\n )\n}\n","// Card entry for the NMI rail. Live mode mounts Collect.js hosted iframes\n// into these containers (card data never touches our code); preview mode\n// (fixture tokenization keys) renders inert placeholders with the same\n// geometry so every state is designable without a gateway. A PSP that takes\n// cards on OpenRails itself gets NativeCardFields instead.\nimport type * as React from \"react\"\n\nimport { Label } from \"#orck/components/ui/label\"\nimport type { CardEntryState } from \"#orck/lib/card-entry\"\nimport type { CollectFieldErrors } from \"#orck/lib/collect\"\nimport { cn } from \"cn\"\n\nfunction FieldError({ id, message }: { id: string; message?: string }) {\n return message ? (\n <p id={id} className=\"text-[12.5px] text-destructive\" role=\"alert\">\n {message}\n </p>\n ) : null\n}\n\nconst FIELD =\n \"orck-collect-field h-[38px] overflow-hidden rounded-[9px] border border-[color:var(--border)] bg-card px-[3px]\"\nconst PREVIEW_FIELD =\n \"flex h-[38px] items-center rounded-[9px] border border-[color:var(--border)] bg-card px-[11px] text-sm text-[color:var(--orck-faint)] tabular-nums\"\n\nexport interface CardFieldIds {\n number: string\n expiry: string\n cvv: string\n}\n\nexport function CardFields({\n ids,\n preview,\n error,\n fieldErrors = {},\n hidden,\n}: {\n ids: CardFieldIds\n preview: boolean\n error?: string\n /** Inline per-field errors (gateway validation or a decline). */\n fieldErrors?: CollectFieldErrors\n // Kept mounted while hidden: the Collect.js iframes cannot be recreated\n // cheaply, so switching to a stored card must not unmount them.\n hidden?: boolean\n}) {\n return (\n <div\n className={cn(\"grid gap-3\", hidden && \"hidden\")}\n aria-hidden={hidden || undefined}\n >\n <div className=\"grid gap-1.5\">\n <Label\n htmlFor={ids.number}\n className=\"text-[13px] font-medium text-foreground\"\n >\n Card number\n </Label>\n {preview ? (\n <div id={ids.number} className={PREVIEW_FIELD}>\n 1234 1234 1234 1234\n </div>\n ) : (\n <div\n id={ids.number}\n className={cn(FIELD, fieldErrors.number && \"border-destructive\")}\n />\n )}\n <FieldError id={`${ids.number}-error`} message={fieldErrors.number} />\n </div>\n <div className=\"grid grid-cols-2 gap-3\">\n <div className=\"grid gap-1.5\">\n <Label\n htmlFor={ids.expiry}\n className=\"text-[13px] font-medium text-foreground\"\n >\n Expiry\n </Label>\n {preview ? (\n <div id={ids.expiry} className={PREVIEW_FIELD}>\n MM / YY\n </div>\n ) : (\n <div\n id={ids.expiry}\n className={cn(FIELD, fieldErrors.expiry && \"border-destructive\")}\n />\n )}\n <FieldError id={`${ids.expiry}-error`} message={fieldErrors.expiry} />\n </div>\n <div className=\"grid gap-1.5\">\n <Label\n htmlFor={ids.cvv}\n className=\"text-[13px] font-medium text-foreground\"\n >\n CVC\n </Label>\n {preview ? (\n <div id={ids.cvv} className={PREVIEW_FIELD}>\n CVC\n </div>\n ) : (\n <div\n id={ids.cvv}\n className={cn(FIELD, fieldErrors.cvv && \"border-destructive\")}\n />\n )}\n <FieldError id={`${ids.cvv}-error`} message={fieldErrors.cvv} />\n </div>\n </div>\n {error ? (\n <p className={cn(\"text-[13px] text-destructive\")} role=\"alert\">\n {error}\n </p>\n ) : null}\n </div>\n )\n}\n\nconst NATIVE_FIELD =\n \"h-[38px] w-full min-w-0 rounded-[9px] border border-[color:var(--border)] bg-card px-[11px] text-sm text-foreground tabular-nums outline-none placeholder:text-[color:var(--orck-faint)] focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:opacity-50\"\n\n/**\n * Card entry for a PSP that takes cards on OpenRails itself (driver \"card\"):\n * plain inputs in the same layout as the Collect.js containers. The card is\n * posted to OpenRails; no gateway script is loaded.\n */\nexport function NativeCardFields({\n ids,\n card,\n fieldErrors = {},\n disabled,\n hidden,\n}: {\n ids: CardFieldIds\n card: CardEntryState\n /** Inline errors beyond the form's own (a decline naming a field). */\n fieldErrors?: CollectFieldErrors\n disabled?: boolean\n hidden?: boolean\n}) {\n const errors = { ...card.fieldErrors, ...fieldErrors }\n const field = (\n id: string,\n name: \"number\" | \"expiry\" | \"cvc\",\n error: string | undefined,\n props: React.ComponentProps<\"input\">\n ) => (\n <>\n <input\n id={id}\n name={`card-${name}`}\n className={cn(NATIVE_FIELD, error && \"border-destructive\")}\n value={card.input[name]}\n onChange={(event) => card.change(name, event.target.value)}\n onBlur={() => card.leave(name)}\n inputMode=\"numeric\"\n spellCheck={false}\n disabled={disabled}\n required\n aria-invalid={error ? true : undefined}\n aria-describedby={error ? `${id}-error` : undefined}\n {...props}\n />\n <FieldError id={`${id}-error`} message={error} />\n </>\n )\n return (\n <div\n className={cn(\"grid gap-3\", hidden && \"hidden\")}\n aria-hidden={hidden || undefined}\n >\n <div className=\"grid gap-1.5\">\n <Label\n htmlFor={ids.number}\n className=\"text-[13px] font-medium text-foreground\"\n >\n Card number\n </Label>\n {field(ids.number, \"number\", errors.number, {\n autoComplete: \"cc-number\",\n placeholder: \"1234 1234 1234 1234\",\n maxLength: 23,\n })}\n </div>\n <div className=\"grid grid-cols-2 gap-3\">\n <div className=\"grid gap-1.5\">\n <Label\n htmlFor={ids.expiry}\n className=\"text-[13px] font-medium text-foreground\"\n >\n Expiry\n </Label>\n {field(ids.expiry, \"expiry\", errors.expiry, {\n autoComplete: \"cc-exp\",\n placeholder: \"MM / YY\",\n maxLength: 7,\n })}\n </div>\n <div className=\"grid gap-1.5\">\n <Label\n htmlFor={ids.cvv}\n className=\"text-[13px] font-medium text-foreground\"\n >\n CVC\n </Label>\n {field(ids.cvv, \"cvc\", errors.cvv, {\n autoComplete: \"cc-csc\",\n placeholder: \"CVC\",\n maxLength: 4,\n })}\n </div>\n </div>\n </div>\n )\n}\n","// The one bold element on the surface: the ink button carrying the amount.\n// Redirect rails relabel it; Solana has no button at all.\nimport { Button } from \"#orck/components/ui/button\"\nimport { cn } from \"cn\"\n\nexport function PayButton({\n label,\n processing,\n disabled,\n}: {\n label: string\n processing: boolean\n disabled?: boolean\n}) {\n return (\n <Button\n type=\"submit\"\n className={cn(\n \"h-[42px] w-full rounded-[10px] text-sm font-semibold tabular-nums\",\n processing && \"opacity-75\"\n )}\n disabled={disabled || processing}\n >\n {processing ? (\n <>\n <span\n aria-hidden\n className=\"size-3.5 animate-spin rounded-full border-2 border-[color:var(--primary-foreground)]/35 border-t-[color:var(--primary-foreground)] motion-reduce:animate-none\"\n />\n Processing…\n </>\n ) : (\n label\n )}\n </Button>\n )\n}\n\nexport function TrustLine() {\n return (\n <div className=\"-mt-1 flex items-center justify-center gap-1.5 text-xs text-[color:var(--orck-faint)]\">\n <svg\n viewBox=\"0 0 16 16\"\n fill=\"currentColor\"\n aria-hidden\n className=\"size-[11px]\"\n >\n <path d=\"M8 1a3.5 3.5 0 0 0-3.5 3.5V6H4a1.5 1.5 0 0 0-1.5 1.5v5A1.5 1.5 0 0 0 4 14h8a1.5 1.5 0 0 0 1.5-1.5v-5A1.5 1.5 0 0 0 12 6h-.5V4.5A3.5 3.5 0 0 0 8 1Zm2 5H6V4.5a2 2 0 1 1 4 0V6Z\" />\n </svg>\n Secured by OpenRails\n </div>\n )\n}\n","// Stripe.js for in-page card setup and payment authentication. Loaded on first\n// use, so hosts without a Stripe PSP never fetch it.\nimport type { Stripe } from \"@stripe/stripe-js\"\n\nconst loaded = new Map<string, Promise<Stripe>>()\n\nexport function loadStripeFor(publishableKey: string): Promise<Stripe> {\n let stripe = loaded.get(publishableKey)\n if (!stripe) {\n stripe = import(\"@stripe/stripe-js\")\n .then(({ loadStripe }) => loadStripe(publishableKey))\n .then((value) => {\n if (!value) throw new Error(\"Stripe could not be loaded.\")\n return value\n })\n stripe.catch(() => loaded.delete(publishableKey))\n loaded.set(publishableKey, stripe)\n }\n return stripe\n}\n","// Collect.js (NMI browser tokenization). The gateway script mounts hosted\n// iframes into our field containers, so card data never touches this code —\n// we receive a one-time token plus display metadata. Collect.js has no\n// teardown API: the script and configuration persist for the page lifetime;\n// reconfiguring re-mounts fields.\nimport * as React from \"react\"\n\nexport interface CollectCard {\n number?: string\n type?: string\n exp?: string\n}\n\nexport interface CollectResponse {\n token: string\n card?: CollectCard\n}\n\ndeclare global {\n interface Window {\n CollectJS?: {\n configure: (config: Record<string, unknown>) => void\n startPaymentRequest: () => void\n }\n }\n}\n\nconst SCRIPT_ID = \"openrails-collectjs\"\nconst TIMEOUT_MS = 30_000\nconst collectScriptStates = new WeakMap<\n HTMLScriptElement,\n \"loading\" | \"loaded\" | \"failed\"\n>()\n\nfunction safeCollectScriptURL(raw: string): string | undefined {\n try {\n const parsed = new URL(raw)\n if (\n parsed.protocol !== \"https:\" ||\n parsed.username ||\n parsed.password ||\n parsed.hash\n ) {\n return undefined\n }\n return parsed.toString()\n } catch {\n return undefined\n }\n}\n\n// toPlainColor normalizes a CSS color into rgb()/rgba() form, the least\n// common denominator the gateway's CSS sanitizer accepts. Chrome serializes\n// the theme tokens in their authored oklch space (canvas fillStyle keeps it\n// too), so oklch is converted numerically; everything else round-trips\n// through a canvas fillStyle. Unparseable input returns \"\".\nexport function toPlainColor(value: string | undefined): string {\n if (!value) return \"\"\n const oklch = oklchToRGB(value)\n if (oklch) return oklch\n try {\n const context = document.createElement(\"canvas\").getContext(\"2d\")\n if (!context) return \"\"\n context.fillStyle = \"#010203\"\n context.fillStyle = value\n const normalized = context.fillStyle\n if (normalized === \"#010203\" && value !== \"#010203\") return \"\"\n return normalized.startsWith(\"oklch\") ? \"\" : normalized\n } catch {\n return \"\"\n }\n}\n\n// oklchToRGB converts \"oklch(L C H)\" / \"oklch(L C H / A)\" (L as 0..1 or %)\n// to an rgb()/rgba() string via OKLab → linear sRGB (Ottosson's matrices).\nfunction oklchToRGB(value: string): string {\n const match =\n /^oklch\\(\\s*([\\d.]+%?)\\s+([\\d.]+)\\s+([\\d.]+)(?:deg)?\\s*(?:\\/\\s*([\\d.]+%?)\\s*)?\\)$/i.exec(\n value.trim()\n )\n if (!match) return \"\"\n const number = (raw: string) =>\n raw.endsWith(\"%\") ? parseFloat(raw) / 100 : parseFloat(raw)\n const L = number(match[1])\n const C = parseFloat(match[2])\n const H = (parseFloat(match[3]) * Math.PI) / 180\n const alpha = match[4] === undefined ? 1 : number(match[4])\n const a = C * Math.cos(H)\n const b = C * Math.sin(H)\n const l = (L + 0.3963377774 * a + 0.2158037573 * b) ** 3\n const m = (L - 0.1055613458 * a - 0.0638541728 * b) ** 3\n const s = (L - 0.0894841775 * a - 1.291485548 * b) ** 3\n const channel = (linear: number) => {\n const gamma =\n linear <= 0.0031308\n ? 12.92 * linear\n : 1.055 * Math.max(linear, 0) ** (1 / 2.4) - 0.055\n return Math.round(Math.min(1, Math.max(0, gamma)) * 255)\n }\n const red = channel(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s)\n const green = channel(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s)\n const blue = channel(-0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s)\n return alpha >= 1\n ? `rgb(${red}, ${green}, ${blue})`\n : `rgba(${red}, ${green}, ${blue}, ${alpha})`\n}\n\n// Preview keys skip the live script entirely so fixture-driven previews can\n// render the card fields without a real gateway.\nexport function isPreviewTokenizationKey(key: string): boolean {\n return key.startsWith(\"preview_\")\n}\n\n/** Inline field errors, keyed by our field names. */\nexport interface CollectFieldErrors {\n number?: string\n expiry?: string\n cvv?: string\n}\n\nconst FIELD_NAMES: Record<string, keyof CollectFieldErrors> = {\n ccnumber: \"number\",\n ccexp: \"expiry\",\n cvv: \"cvv\",\n}\n\nconst FIELD_MESSAGES: Record<keyof CollectFieldErrors, string> = {\n number: \"Enter a valid card number\",\n expiry: \"Enter a valid expiry date\",\n cvv: \"Enter a valid security code\",\n}\n\nexport interface CollectFieldSelectors {\n number: string\n expiry: string\n cvv: string\n}\n\nexport function useCollectJS(config: {\n enabled: boolean\n active: boolean\n tokenizationKey: string\n scriptURL: string\n selectors: CollectFieldSelectors\n}): {\n ready: boolean\n preview: boolean\n loadError?: string\n /** Every field reported valid by the gateway. */\n valid: boolean\n fieldErrors: CollectFieldErrors\n tokenize: () => Promise<CollectResponse>\n} {\n const preview =\n config.enabled && isPreviewTokenizationKey(config.tokenizationKey)\n const [ready, setReady] = React.useState(false)\n const [loadError, setLoadError] = React.useState<string>()\n // Validity per field as Collect.js reports it on edit and blur.\n const [validity, setValidity] = React.useState<\n Partial<\n Record<keyof CollectFieldErrors, { valid: boolean; message?: string }>\n >\n >({})\n const pending = React.useRef<\n | {\n resolve: (r: CollectResponse) => void\n reject: (e: Error) => void\n timer: number\n }\n | undefined\n >(undefined)\n const configuredFor = React.useRef<string | undefined>(undefined)\n const { number, expiry, cvv } = config.selectors\n\n React.useEffect(() => {\n if (\n !config.enabled ||\n preview ||\n !config.tokenizationKey ||\n !config.scriptURL ||\n typeof document === \"undefined\"\n ) {\n return\n }\n const scriptURL = safeCollectScriptURL(config.scriptURL)\n if (!scriptURL) {\n void Promise.resolve().then(() => {\n setReady(false)\n setLoadError(\"Card fields failed to load\")\n })\n return\n }\n const configuration = [\n config.tokenizationKey,\n scriptURL,\n number,\n expiry,\n cvv,\n ].join(\"\\u0000\")\n const configurationChanged = configuredFor.current !== configuration\n if (!configurationChanged && !config.active) return\n configuredFor.current = configuration\n\n let cancelled = false\n const settle = (fn: () => void) => {\n if (!cancelled) fn()\n }\n const configure = () => {\n if (cancelled) return\n const collect = window.CollectJS\n if (!collect) {\n settle(() => setLoadError(\"Card fields failed to load\"))\n return\n }\n settle(() => {\n // Replacing stale hosted iframes invalidates readiness until NMI\n // confirms that every new field is available.\n setReady(false)\n setLoadError(undefined)\n setValidity({})\n })\n // The hosted iframes cannot inherit the page theme; hand them the\n // container's resolved colors so dark mode reaches inside the fields.\n // Chrome serializes computed colors in their authored space (oklch),\n // which the gateway's CSS sanitizer drops — normalize through a canvas\n // fillStyle round-trip to a format it accepts. (Resolved once per\n // configure — an in-place OS theme flip re-themes on the next load.)\n const probe = document.querySelector<HTMLElement>(number)\n const probeStyle = probe ? window.getComputedStyle(probe) : undefined\n const probeBackground = toPlainColor(probeStyle?.backgroundColor)\n const fieldBackground =\n probeBackground &&\n probeBackground !== \"transparent\" &&\n probeBackground !== \"rgba(0, 0, 0, 0)\"\n ? probeBackground\n : \"#ffffff\"\n const fieldColor = toPlainColor(probeStyle?.color) || \"#18181b\"\n const placeholderColor =\n toPlainColor(\n probeStyle?.getPropertyValue(\"--muted-foreground\").trim()\n ) || fieldColor\n try {\n collect.configure({\n variant: \"inline\",\n styleSniffer: true,\n customCss: {\n height: \"38px\",\n \"line-height\": \"38px\",\n padding: \"0 8px\",\n \"font-size\": \"14px\",\n \"font-family\": probeStyle?.fontFamily || \"inherit\",\n \"background-color\": fieldBackground,\n color: fieldColor,\n },\n placeholderCss: {\n color: placeholderColor,\n },\n invalidCss: {\n color:\n toPlainColor(\n probeStyle?.getPropertyValue(\"--destructive\").trim()\n ) || \"#dc2626\",\n },\n focusCss: {\n outline: \"none\",\n },\n // Collect.js owns the cross-origin inputs and therefore controls\n // their autocomplete behavior. Titles and placeholders are the\n // accessibility/browser hints its public field API supports.\n fields: {\n ccnumber: {\n selector: number,\n title: \"Card number\",\n placeholder: \"1234 1234 1234 1234\",\n },\n ccexp: {\n selector: expiry,\n title: \"Expiration date\",\n placeholder: \"MM / YY\",\n },\n cvv: {\n selector: cvv,\n title: \"Card security code\",\n placeholder: \"CVC\",\n },\n },\n fieldsAvailableCallback: () => settle(() => setReady(true)),\n validationCallback: (\n field: string,\n status: boolean,\n message: string\n ) => {\n const name = FIELD_NAMES[field]\n if (!name) return\n settle(() =>\n setValidity((current) => ({\n ...current,\n [name]: {\n valid: status,\n message: status\n ? undefined\n : message && message !== \"Field is empty\"\n ? `${FIELD_MESSAGES[name]}.`\n : FIELD_MESSAGES[name],\n },\n }))\n )\n },\n timeoutDuration: TIMEOUT_MS,\n timeoutCallback: () => {\n const request = pending.current\n pending.current = undefined\n if (request) {\n window.clearTimeout(request.timer)\n request.reject(new Error(\"Card entry timed out\"))\n }\n },\n callback: (response: CollectResponse) => {\n const request = pending.current\n pending.current = undefined\n if (request) {\n window.clearTimeout(request.timer)\n request.resolve(response)\n }\n },\n })\n } catch {\n settle(() => setLoadError(\"Card fields failed to load\"))\n }\n }\n let existing = document.getElementById(SCRIPT_ID)\n if (\n existing instanceof HTMLScriptElement &&\n (existing.src !== scriptURL ||\n collectScriptStates.get(existing) === \"failed\")\n ) {\n // A white-label merchant may use a different Collect.js distribution.\n // Never configure one merchant's key against another merchant's script,\n // and allow a later modal open to retry a failed network load.\n existing.remove()\n if (existing.src !== scriptURL) {\n Reflect.deleteProperty(window, \"CollectJS\")\n }\n existing = null\n }\n if (existing instanceof HTMLScriptElement) {\n if (window.CollectJS) {\n configure()\n return () => {\n cancelled = true\n }\n }\n if (collectScriptStates.get(existing) === \"loaded\") {\n settle(() => setLoadError(\"Card fields failed to load\"))\n return () => {\n cancelled = true\n }\n }\n const failed = () =>\n settle(() => setLoadError(\"Card fields failed to load\"))\n existing.addEventListener(\"load\", configure)\n existing.addEventListener(\"error\", failed)\n return () => {\n cancelled = true\n existing.removeEventListener(\"load\", configure)\n existing.removeEventListener(\"error\", failed)\n }\n }\n const script = document.createElement(\"script\")\n script.id = SCRIPT_ID\n script.src = scriptURL\n script.async = true\n script.dataset.tokenizationKey = config.tokenizationKey\n collectScriptStates.set(script, \"loading\")\n script.onload = () => {\n collectScriptStates.set(script, \"loaded\")\n configure()\n }\n script.onerror = () => {\n collectScriptStates.set(script, \"failed\")\n settle(() => setLoadError(\"Card fields failed to load\"))\n }\n document.head.appendChild(script)\n return () => {\n cancelled = true\n }\n }, [\n config.enabled,\n config.active,\n preview,\n config.tokenizationKey,\n config.scriptURL,\n number,\n expiry,\n cvv,\n ])\n\n const tokenize = React.useCallback(\n () =>\n new Promise<CollectResponse>((resolve, reject) => {\n if (preview) {\n // Preview sessions demo the full flow; a real backend rejects this\n // token, fixture sources accept it.\n resolve({\n token: \"preview_payment_token\",\n card: { number: \"4242424242424242\", type: \"visa\", exp: \"1227\" },\n })\n return\n }\n const collect = window.CollectJS\n if (!collect || !ready) {\n reject(new Error(\"Card fields are not ready\"))\n return\n }\n if (pending.current) {\n reject(new Error(\"Card entry is already in progress\"))\n return\n }\n const timer = window.setTimeout(() => {\n pending.current = undefined\n reject(new Error(\"Card entry timed out\"))\n }, TIMEOUT_MS + 5_000)\n pending.current = { resolve, reject, timer }\n collect.startPaymentRequest()\n }),\n [preview, ready]\n )\n\n const fieldErrors: CollectFieldErrors = {}\n for (const name of [\"number\", \"expiry\", \"cvv\"] as const) {\n const state = validity[name]\n if (state && !state.valid) fieldErrors[name] = state.message\n }\n const valid =\n preview ||\n ([\"number\", \"expiry\", \"cvv\"] as const).every(\n (name) => validity[name]?.valid === true\n )\n return {\n ready: ready || preview,\n preview,\n loadError,\n valid,\n fieldErrors,\n tokenize,\n }\n}\n\n/** Display metadata of a tokenized card: never the PAN. */\nexport function collectCardDisplay(card?: CollectCard): {\n last_four?: string\n card_type?: string\n expiry_date?: string\n} {\n const digits = (card?.number ?? \"\").replace(/\\D/g, \"\")\n const exp = (card?.exp ?? \"\").replace(/\\D/g, \"\")\n return {\n ...(digits.length >= 4 ? { last_four: digits.slice(-4) } : {}),\n ...(card?.type ? { card_type: card.type } : {}),\n ...(exp.length === 4\n ? { expiry_date: `${exp.slice(0, 2)}/${exp.slice(2)}` }\n : {}),\n }\n}\n","// Stripe Elements appearance from the page's resolved theme tokens, so the\n// Payment Element matches our inputs (height, radius, type, colors).\nimport type { Appearance } from \"@stripe/stripe-js\"\n\nimport { toPlainColor } from \"#orck/lib/collect\"\n\nexport function stripeAppearance(host: HTMLElement): Appearance {\n const style = window.getComputedStyle(host)\n const token = (name: string) =>\n toPlainColor(style.getPropertyValue(name).trim()) || undefined\n const dark = !!host.closest(\".dark\")\n return {\n theme: dark ? \"night\" : \"stripe\",\n variables: {\n colorPrimary: token(\"--primary\"),\n colorBackground: token(\"--card\"),\n colorText: token(\"--foreground\"),\n colorTextSecondary: token(\"--muted-foreground\"),\n colorDanger: token(\"--destructive\"),\n fontFamily: style.fontFamily || undefined,\n fontSizeBase: \"14px\",\n borderRadius: \"9px\",\n spacingUnit: \"3px\",\n },\n rules: {\n \".Input\": {\n padding: \"9px 10px\",\n boxShadow: \"none\",\n borderColor: token(\"--border\") ?? \"\",\n },\n \".Input:focus\": {\n borderColor: token(\"--ring\") ?? \"\",\n boxShadow: \"none\",\n },\n \".Label\": { fontSize: \"13px\", fontWeight: \"500\", marginBottom: \"6px\" },\n \".Error\": { fontSize: \"12.5px\" },\n },\n }\n}\n","// Stripe Payment Element on an OpenRails card setup (SetupIntent). The card\n// lives only in Stripe's frames; save() confirms the setup in the page (3-D\n// Secure included) and returns the saved OpenRails payment method id.\nimport * as React from \"react\"\nimport type {\n Stripe,\n StripeElements,\n StripePaymentElementChangeEvent,\n} from \"@stripe/stripe-js\"\n\nimport type { BillingClient } from \"#orck/client/client\"\nimport type { CardSetup } from \"#orck/client/types\"\nimport { loadStripeFor } from \"#orck/lib/stripe\"\nimport { stripeAppearance } from \"#orck/lib/stripe-appearance\"\nimport type { PspConfig } from \"#orck/psp\"\n\nexport interface StripeCardHandle {\n /** Confirms the setup and returns the saved payment method id. */\n save(): Promise<string>\n}\n\nconst defaultReturnURL = (setupId: string) => {\n const url = new URL(window.location.href)\n url.searchParams.set(\"setup_id\", setupId)\n return url.href\n}\n\nexport const StripeCardEntry = React.forwardRef<\n StripeCardHandle,\n {\n psp: PspConfig\n client: BillingClient\n returnURL?: (setupId: string) => string\n defaultCountry?: string\n /** Completeness of the entered card, from the element's change events. */\n onCompleteChange?: (complete: boolean) => void\n unavailableMessage: string\n verificationPendingMessage: string\n }\n>(function StripeCardEntry(\n {\n psp,\n client,\n returnURL = defaultReturnURL,\n defaultCountry,\n onCompleteChange,\n unavailableMessage,\n verificationPendingMessage,\n },\n ref\n) {\n const [idempotencyKey] = React.useState(() => crypto.randomUUID())\n const [setup, setSetup] = React.useState<CardSetup>()\n const [error, setError] = React.useState<string>()\n const host = React.useRef<HTMLDivElement>(null)\n const mounted = React.useRef<{ stripe: Stripe; elements: StripeElements }>(\n null\n )\n const completeRef = React.useRef(onCompleteChange)\n React.useEffect(() => {\n completeRef.current = onCompleteChange\n })\n\n React.useEffect(() => {\n let cancelled = false\n client\n .createCardSetup({ pspId: psp.psp_id, idempotencyKey })\n .then((created) => {\n if (cancelled) return\n if (!created.client_secret && !created.payment_method_id)\n throw new Error(unavailableMessage)\n setSetup(created)\n if (created.payment_method_id) completeRef.current?.(true)\n })\n .catch((cause: unknown) => {\n if (!cancelled)\n setError(cause instanceof Error ? cause.message : unavailableMessage)\n })\n return () => {\n cancelled = true\n }\n }, [client, psp.psp_id, idempotencyKey, unavailableMessage])\n\n const secret = setup?.client_secret\n const publishable = psp.config?.publishable_key\n React.useEffect(() => {\n if (!secret || !publishable || !host.current) return\n let cancelled = false\n let unmount: (() => void) | undefined\n void loadStripeFor(publishable).then(\n (stripe) => {\n if (cancelled || !host.current) return\n const elements = stripe.elements({\n clientSecret: secret,\n appearance: stripeAppearance(host.current),\n })\n // Cards only: the panel saves a card, so no Link bank or wallets.\n const element = elements.create(\"payment\", {\n wallets: { link: \"never\", applePay: \"never\", googlePay: \"never\" },\n ...(defaultCountry\n ? {\n defaultValues: {\n billingDetails: { address: { country: defaultCountry } },\n },\n }\n : {}),\n })\n element.on(\"change\", (event: StripePaymentElementChangeEvent) => {\n completeRef.current?.(event.complete)\n })\n element.mount(host.current)\n mounted.current = { stripe, elements }\n unmount = () => element.destroy()\n },\n (cause: unknown) => {\n if (!cancelled)\n setError(cause instanceof Error ? cause.message : unavailableMessage)\n }\n )\n return () => {\n cancelled = true\n mounted.current = null\n unmount?.()\n }\n }, [secret, publishable, defaultCountry, unavailableMessage])\n\n React.useImperativeHandle(\n ref,\n () => ({\n async save() {\n if (setup?.payment_method_id) return setup.payment_method_id\n const current = mounted.current\n if (!setup || !current) throw new Error(unavailableMessage)\n setError(undefined)\n const validation = await current.elements.submit()\n if (validation.error)\n throw new Error(validation.error.message ?? unavailableMessage)\n const result = await current.stripe.confirmSetup({\n elements: current.elements,\n confirmParams: { return_url: returnURL(setup.id) },\n redirect: \"if_required\",\n })\n if (result.error)\n throw new Error(result.error.message ?? unavailableMessage)\n const verified = await client.confirmCardSetup(setup.id)\n if (!verified.payment_method_id)\n throw new Error(verificationPendingMessage)\n return verified.payment_method_id\n },\n }),\n [setup, client, returnURL, unavailableMessage, verificationPendingMessage]\n )\n\n return (\n <div className=\"grid gap-2\">\n <div ref={host} data-testid=\"stripe-card-entry\" />\n {error ? (\n <p role=\"alert\" className=\"text-[13px] text-destructive\">\n {error}\n </p>\n ) : null}\n </div>\n )\n})\n","// Native card entry (driver \"card\"): the PSP declares card_entry: server, so\n// the page posts the card to OpenRails, which vaults it at the gateway. No\n// gateway script is loaded. The card lives in component state only until it\n// is submitted.\nimport * as React from \"react\"\n\nimport type { CollectFieldErrors } from \"#orck/lib/collect\"\n\n/** A card as OpenRails' `card` field takes it. */\nexport interface CardEntry {\n number: string\n exp_month: number\n exp_year: number\n cvc: string\n}\n\n/** What the buyer typed, as typed. */\nexport interface CardEntryInput {\n number: string\n expiry: string\n cvc: string\n}\n\nexport const FIELD_MESSAGES: Required<CollectFieldErrors> = {\n number: \"Enter a valid card number\",\n expiry: \"Enter a valid expiry date\",\n cvv: \"Enter a valid security code\",\n}\n\nconst digitsOf = (value: string) => value.replace(/\\D/g, \"\")\n\nfunction luhn(digits: string): boolean {\n let sum = 0\n for (let i = 0; i < digits.length; i++) {\n let d = digits.charCodeAt(digits.length - 1 - i) - 48\n if (i % 2 === 1) {\n d *= 2\n if (d > 9) d -= 9\n }\n sum += d\n }\n return sum % 10 === 0\n}\n\n/** The card network a number's leading digits name (\"\" when none). */\nexport function cardBrandOf(number: string): string {\n const d = digitsOf(number)\n const p = (n: number) => (d.length >= n ? Number(d.slice(0, n)) : -1)\n if (p(1) === 4) return \"visa\"\n if (p(2) === 34 || p(2) === 37) return \"amex\"\n if ((p(2) >= 51 && p(2) <= 55) || (p(4) >= 2221 && p(4) <= 2720))\n return \"mastercard\"\n if (p(4) === 6011 || p(2) === 65 || (p(3) >= 644 && p(3) <= 649))\n return \"discover\"\n if (p(2) === 35) return \"jcb\"\n if (p(2) === 36 || p(2) === 38 || (p(3) >= 300 && p(3) <= 305))\n return \"diners\"\n return \"\"\n}\n\n/** Groups a number as it is printed: 4-6-5 for Amex, fours otherwise. */\nexport function formatCardNumber(value: string): string {\n const d = digitsOf(value).slice(0, 19)\n if (cardBrandOf(d) === \"amex\")\n return [d.slice(0, 4), d.slice(4, 10), d.slice(10, 15)]\n .filter(Boolean)\n .join(\" \")\n return d.replace(/(\\d{4})(?=\\d)/g, \"$1 \")\n}\n\n/** MM / YY as it is typed. */\nexport function formatExpiry(value: string): string {\n const d = digitsOf(value).slice(0, 4)\n return d.length > 2 ? `${d.slice(0, 2)} / ${d.slice(2)}` : d\n}\n\nfunction parseExpiry(value: string, now: Date) {\n const d = digitsOf(value)\n if (d.length !== 4 && d.length !== 6) return null\n const month = Number(d.slice(0, 2))\n const year = d.length === 4 ? 2000 + Number(d.slice(2)) : Number(d.slice(2))\n if (month < 1 || month > 12) return null\n const lapsed =\n year < now.getFullYear() ||\n (year === now.getFullYear() && month < now.getMonth() + 1)\n return lapsed ? null : { month, year }\n}\n\n/** Every field's error; an empty object means the card is complete. */\nexport function cardEntryErrors(\n input: CardEntryInput,\n now = new Date()\n): CollectFieldErrors {\n const errors: CollectFieldErrors = {}\n const number = digitsOf(input.number)\n if (number.length < 12 || number.length > 19 || !luhn(number))\n errors.number = FIELD_MESSAGES.number\n if (!parseExpiry(input.expiry, now)) errors.expiry = FIELD_MESSAGES.expiry\n const cvc = digitsOf(input.cvc)\n const want = cardBrandOf(number) === \"amex\" ? 4 : 3\n if (cvc !== input.cvc.trim() || (cvc.length !== want && cvc.length !== 4))\n errors.cvv = FIELD_MESSAGES.cvv\n return errors\n}\n\n/** The card OpenRails takes, or null while any field is invalid. */\nexport function parseCardEntry(\n input: CardEntryInput,\n now = new Date()\n): CardEntry | null {\n if (Object.keys(cardEntryErrors(input, now)).length > 0) return null\n const expiry = parseExpiry(input.expiry, now)!\n return {\n number: digitsOf(input.number),\n exp_month: expiry.month,\n exp_year: expiry.year,\n cvc: digitsOf(input.cvc),\n }\n}\n\n/** A card's display facts, the ones a saved card is labelled with. */\nexport function cardEntryDisplay(card: CardEntry): {\n last_four: string\n card_type?: string\n expiry_date: string\n} {\n const brand = cardBrandOf(card.number)\n return {\n last_four: card.number.slice(-4),\n ...(brand ? { card_type: brand } : {}),\n expiry_date: `${String(card.exp_month).padStart(2, \"0\")}/${String(card.exp_year % 100).padStart(2, \"0\")}`,\n }\n}\n\nconst empty: CardEntryInput = { number: \"\", expiry: \"\", cvc: \"\" }\n\n/**\n * The state of one native card form. Errors show once a field was left;\n * `take` hands the card over and clears the form, so the page keeps it no\n * longer than the request that sends it.\n */\nexport function useCardEntry() {\n const [input, setInput] = React.useState<CardEntryInput>(empty)\n const [touched, setTouched] = React.useState<\n Partial<Record<keyof CardEntryInput, boolean>>\n >({})\n const errors = cardEntryErrors(input)\n const shown: CollectFieldErrors = {}\n if (touched.number && errors.number) shown.number = errors.number\n if (touched.expiry && errors.expiry) shown.expiry = errors.expiry\n if (touched.cvc && errors.cvv) shown.cvv = errors.cvv\n const clear = React.useCallback(() => {\n setInput(empty)\n setTouched({})\n }, [])\n return {\n input,\n fieldErrors: shown,\n valid: Object.keys(errors).length === 0,\n change: (field: keyof CardEntryInput, value: string) =>\n setInput((current) => ({\n ...current,\n [field]:\n field === \"number\"\n ? formatCardNumber(value)\n : field === \"expiry\"\n ? formatExpiry(value)\n : digitsOf(value).slice(0, 4),\n })),\n leave: (field: keyof CardEntryInput) =>\n setTouched((current) => ({ ...current, [field]: true })),\n take: (): CardEntry | null => {\n const card = parseCardEntry(input)\n if (!card) {\n setTouched({ number: true, expiry: true, cvc: true })\n return null\n }\n clear()\n return card\n },\n clear,\n }\n}\n\nexport type CardEntryState = ReturnType<typeof useCardEntry>\n","import * as React from \"react\"\nimport {\n appearanceStyle,\n appearanceTheme,\n type CheckoutAppearance,\n} from \"./appearance\"\nimport { CardBillingFields } from \"./components/billing-fields\"\nimport { CardFields } from \"./components/card-fields\"\nimport { PayButton, TrustLine } from \"./components/pay-button\"\nimport {\n emptyNMIBilling,\n initialCountry,\n nmiBillingSchema,\n} from \"./lib/billing\"\nimport { collectCardDisplay, useCollectJS } from \"./lib/collect\"\nimport { cn } from \"cn\"\n\n// Only tokenized billing details cross the iframe boundary. PAN/CVC are never\n// accepted by this component or handed to the host callback.\nexport interface TokenizedCardData {\n payment_token: string\n name_on_card: string\n country: string\n zip?: string\n /** Display metadata from the gateway: last four, brand, MM/YY. */\n last_four?: string\n card_type?: string\n expiry_date?: string\n}\nexport interface TokenizedCardFormProps {\n tokenizationKey: string\n tokenizationURL: string\n onTokenized: (card: TokenizedCardData) => Promise<void>\n submitLabel?: string\n disabled?: boolean\n /** Billing country to preselect; default: the browser locale's region. */\n defaultCountry?: string\n appearance?: CheckoutAppearance\n className?: string\n}\n\n// The host supplies consent and performs its authorized save-card operation.\n// This component neither creates a checkout nor implies payment success.\nexport function TokenizedCardForm({\n tokenizationKey,\n tokenizationURL,\n onTokenized,\n submitLabel = \"Save card\",\n disabled = false,\n defaultCountry,\n appearance,\n className,\n}: TokenizedCardFormProps) {\n const uid = React.useId().replace(/[^a-zA-Z0-9-]/g, \"\")\n const ids = React.useMemo(\n () => ({\n number: `orck-save-${uid}-number`,\n expiry: `orck-save-${uid}-expiry`,\n cvv: `orck-save-${uid}-cvv`,\n }),\n [uid]\n )\n const [billing, setBilling] = React.useState(() => ({\n ...emptyNMIBilling,\n country: initialCountry(defaultCountry),\n }))\n const [busy, setBusy] = React.useState(false)\n const [submitted, setSubmitted] = React.useState(false)\n const [error, setError] = React.useState<string>()\n const authorization = React.useRef({ generation: 0, disabled })\n React.useLayoutEffect(() => {\n authorization.current = {\n generation: authorization.current.generation + 1,\n disabled,\n }\n }, [tokenizationKey, tokenizationURL, disabled])\n const mounted = React.useRef(true)\n React.useEffect(() => {\n mounted.current = true\n return () => {\n mounted.current = false\n }\n }, [])\n const collect = useCollectJS({\n enabled: true,\n active: true,\n tokenizationKey,\n scriptURL: tokenizationURL,\n selectors: {\n number: `#${ids.number}`,\n expiry: `#${ids.expiry}`,\n cvv: `#${ids.cvv}`,\n },\n })\n const submit = async (event: React.FormEvent) => {\n event.preventDefault()\n if (disabled || busy || submitted) return\n const parsed = nmiBillingSchema.safeParse(billing)\n if (!parsed.success) {\n setError(parsed.error.issues[0]?.message ?? \"Check the billing details\")\n return\n }\n setBusy(true)\n setError(undefined)\n const generation = authorization.current.generation\n let sent = false\n try {\n const token = await collect.tokenize()\n if (\n !mounted.current ||\n authorization.current.generation !== generation ||\n authorization.current.disabled\n )\n return\n sent = true\n setSubmitted(true)\n await onTokenized({\n payment_token: token.token,\n ...parsed.data,\n ...collectCardDisplay(token.card),\n })\n } catch (cause) {\n if (mounted.current)\n setError(\n sent\n ? \"The card-save result is not confirmed. Check your saved cards before starting another attempt.\"\n : cause instanceof Error\n ? cause.message\n : \"Card entry could not be completed.\"\n )\n } finally {\n if (mounted.current) setBusy(false)\n }\n }\n return (\n <div\n className={cn(\"orck\", className)}\n data-orck-theme={appearanceTheme(appearance)}\n style={appearanceStyle(appearance)}\n >\n <form\n aria-label=\"Secure card setup\"\n autoComplete=\"on\"\n className=\"grid gap-4\"\n onSubmit={(event) => void submit(event)}\n >\n <CardBillingFields\n idPrefix={`orck-save-${uid}`}\n value={billing}\n onChange={setBilling}\n disabled={disabled || busy || submitted}\n />\n <CardFields\n ids={ids}\n preview={collect.preview}\n error={collect.loadError}\n fieldErrors={collect.fieldErrors}\n />\n {error ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {error}\n </p>\n ) : null}\n <PayButton\n label={submitLabel}\n processing={busy}\n disabled={\n disabled ||\n submitted ||\n !collect.ready ||\n !collect.valid ||\n Boolean(collect.loadError)\n }\n />\n <TrustLine />\n </form>\n </div>\n )\n}\n","import * as React from \"react\"\n\nimport {\n appearanceStyle,\n appearanceTheme,\n type CheckoutAppearance,\n} from \"./appearance\"\nimport { isBillingError } from \"./client/errors\"\nimport { CardBillingFields } from \"./components/billing-fields\"\nimport { NativeCardFields } from \"./components/card-fields\"\nimport { PayButton, TrustLine } from \"./components/pay-button\"\nimport {\n StripeCardEntry,\n type StripeCardHandle,\n} from \"./components/stripe-card\"\nimport { useMessages } from \"./i18n/context\"\nimport {\n emptyNMIBilling,\n initialCountry,\n nmiBillingSchema,\n} from \"./lib/billing\"\nimport { useCardEntry } from \"./lib/card-entry\"\nimport { cardSetupDriver, type PspConfig } from \"./psp\"\nimport { useBillingContext } from \"./react/context\"\nimport {\n TokenizedCardForm,\n type TokenizedCardData,\n} from \"./tokenized-card-form\"\nimport { cn } from \"cn\"\n\nexport interface SavePaymentMethodProps {\n /** The PSP to save the card with, from OpenRails's checkout config. */\n psp: PspConfig\n onSaved: (paymentMethodId: string) => void\n /**\n * Where the provider returns after an off-page verification (3-D Secure),\n * given the setup id to confirm with `client.confirmCardSetup`. Default:\n * the current page with `?setup_id=`.\n */\n returnURL?: (setupId: string) => string\n /** Billing country to preselect; default: the browser locale's region. */\n defaultCountry?: string\n submitLabel?: string\n appearance?: CheckoutAppearance\n className?: string\n}\n\n/**\n * Saves a card to the customer's account with any PSP OpenRails serves, in\n * the page. The PSP's configuration picks the flow: card data enters the\n * provider's own frames, or, for a PSP whose card_entry is server, is posted\n * to OpenRails. Requires `BillingProvider`.\n */\nexport function SavePaymentMethod(props: SavePaymentMethodProps) {\n const { t } = useMessages()\n const driver = cardSetupDriver(props.psp)\n if (!driver)\n return (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {t(\"paymentMethods.unavailable\")}\n </p>\n )\n return (\n <div\n className={cn(\"orck grid gap-4\", props.className)}\n data-orck-theme={appearanceTheme(props.appearance)}\n style={appearanceStyle(props.appearance)}\n >\n <p className=\"text-sm text-muted-foreground\">\n {t(\"paymentMethods.saveNotice\")}\n </p>\n {driver === \"collect_js\" ? (\n <TokenizedSetup {...props} />\n ) : driver === \"card\" ? (\n <NativeCardSetup {...props} />\n ) : (\n <ElementsSetup {...props} />\n )}\n </div>\n )\n}\n\n// Provider SDK errors carry customer-facing text (\"Your card was declined.\").\nconst describe = (m: ReturnType<typeof useMessages>, cause: unknown) =>\n !isBillingError(cause) && cause instanceof Error && cause.message\n ? cause.message\n : m.error(cause)\n\nfunction TokenizedSetup({\n psp,\n onSaved,\n submitLabel,\n appearance,\n defaultCountry,\n}: SavePaymentMethodProps) {\n const m = useMessages()\n const { client, notify } = useBillingContext()\n const [formKey, setFormKey] = React.useState(0)\n const [error, setError] = React.useState<string>()\n const save = async (card: TokenizedCardData) => {\n setError(undefined)\n let method\n try {\n method = await client.addPaymentMethod({ ...card, provider: psp.key })\n } catch (cause) {\n setError(describe(m, cause))\n setFormKey((key) => key + 1)\n return\n }\n notify({ type: \"payment_method.added\", paymentMethodId: method.id })\n onSaved(method.id)\n }\n return (\n <>\n {error ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {error}\n </p>\n ) : null}\n <TokenizedCardForm\n key={formKey}\n tokenizationKey={psp.config!.tokenization_key!}\n tokenizationURL={psp.config!.tokenization_url!}\n onTokenized={save}\n defaultCountry={defaultCountry}\n submitLabel={submitLabel ?? m.t(\"paymentMethods.save\")}\n appearance={appearance}\n />\n </>\n )\n}\n\nfunction NativeCardSetup({\n psp,\n onSaved,\n submitLabel,\n defaultCountry,\n}: SavePaymentMethodProps) {\n const m = useMessages()\n const { client, notify } = useBillingContext()\n const uid = React.useId().replace(/[^a-zA-Z0-9-]/g, \"\")\n const ids = React.useMemo(\n () => ({\n number: `orck-save-${uid}-number`,\n expiry: `orck-save-${uid}-expiry`,\n cvv: `orck-save-${uid}-cvv`,\n }),\n [uid]\n )\n const card = useCardEntry()\n const [billing, setBilling] = React.useState(() => ({\n ...emptyNMIBilling,\n country: initialCountry(defaultCountry),\n }))\n const [busy, setBusy] = React.useState(false)\n const [error, setError] = React.useState<string>()\n\n const submit = async (event: React.FormEvent) => {\n event.preventDefault()\n if (busy) return\n const parsed = nmiBillingSchema.safeParse(billing)\n if (!parsed.success) {\n setError(parsed.error.issues[0]?.message ?? \"Check the billing details\")\n return\n }\n const entered = card.take()\n if (!entered) return\n setBusy(true)\n setError(undefined)\n try {\n const method = await client.addPaymentMethod({\n ...parsed.data,\n provider: psp.key,\n card: entered,\n })\n notify({ type: \"payment_method.added\", paymentMethodId: method.id })\n onSaved(method.id)\n } catch (cause) {\n setError(describe(m, cause))\n } finally {\n setBusy(false)\n }\n }\n\n return (\n <form\n aria-label=\"Secure card setup\"\n autoComplete=\"on\"\n className=\"grid gap-4\"\n noValidate\n onSubmit={(event) => void submit(event)}\n >\n <CardBillingFields\n idPrefix={`orck-save-${uid}`}\n value={billing}\n onChange={setBilling}\n disabled={busy}\n />\n <NativeCardFields ids={ids} card={card} disabled={busy} />\n {error ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {error}\n </p>\n ) : null}\n <PayButton\n label={submitLabel ?? m.t(\"paymentMethods.save\")}\n processing={busy}\n disabled={!card.valid}\n />\n <TrustLine />\n </form>\n )\n}\n\nfunction ElementsSetup({\n psp,\n onSaved,\n returnURL,\n submitLabel,\n defaultCountry,\n}: SavePaymentMethodProps) {\n const m = useMessages()\n const { t } = m\n const { client, notify } = useBillingContext()\n const card = React.useRef<StripeCardHandle>(null)\n const [complete, setComplete] = React.useState(false)\n const [busy, setBusy] = React.useState(false)\n const [error, setError] = React.useState<string>()\n const country = React.useMemo(\n () => initialCountry(defaultCountry),\n [defaultCountry]\n )\n\n const submit = async (event: React.FormEvent) => {\n event.preventDefault()\n if (!card.current || busy) return\n setBusy(true)\n setError(undefined)\n try {\n const id = await card.current.save()\n notify({ type: \"payment_method.added\", paymentMethodId: id })\n onSaved(id)\n } catch (cause) {\n setError(describe(m, cause))\n } finally {\n setBusy(false)\n }\n }\n\n return (\n <form className=\"grid gap-4\" onSubmit={(event) => void submit(event)}>\n <StripeCardEntry\n ref={card}\n psp={psp}\n client={client}\n returnURL={returnURL}\n defaultCountry={country || undefined}\n onCompleteChange={setComplete}\n unavailableMessage={t(\"paymentMethods.unavailable\")}\n verificationPendingMessage={t(\"paymentMethods.verificationPending\")}\n />\n {error ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {error}\n </p>\n ) : null}\n <PayButton\n label={submitLabel ?? t(\"paymentMethods.save\")}\n processing={busy}\n disabled={!complete}\n />\n <TrustLine />\n </form>\n )\n}\n","import * as React from \"react\"\nimport { cn } from \"cn\"\n\n/** Polite confirmation line that clears itself. */\nexport function useNotice(): [React.ReactNode, (text: string) => void] {\n const [text, setText] = React.useState<string | null>(null)\n React.useEffect(() => {\n if (!text) return\n const timer = setTimeout(() => setText(null), 6000)\n return () => clearTimeout(timer)\n }, [text])\n const node = (\n <p\n role=\"status\"\n aria-live=\"polite\"\n className={cn(\"text-sm text-muted-foreground\", text ? \"pt-3\" : \"sr-only\")}\n >\n {text}\n </p>\n )\n return [node, setText]\n}\n","import * as React from \"react\"\nimport { HugeiconsIcon } from \"@hugeicons/react\"\nimport { Add01Icon, Delete02Icon } from \"@hugeicons/core-free-icons\"\n\nimport type { CheckoutAppearance } from \"#orck/appearance\"\nimport type { BillingError } from \"#orck/client/errors\"\nimport type { PaymentMethod } from \"#orck/client/types\"\nimport { CardBrandPlate } from \"#orck/components/card-brands\"\nimport {\n AlertDialog,\n AlertDialogCancel,\n AlertDialogContent,\n AlertDialogDescription,\n AlertDialogFooter,\n AlertDialogHeader,\n AlertDialogTitle,\n} from \"#orck/components/ui/alert-dialog\"\nimport { Button } from \"#orck/components/ui/button\"\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogHeader,\n DialogTitle,\n} from \"#orck/components/ui/dialog\"\nimport { Spinner } from \"#orck/components/ui/spinner\"\nimport { useMessages } from \"#orck/i18n/context\"\nimport type { Translator } from \"#orck/i18n/messages\"\nimport { usePaymentMethods } from \"#orck/react/hooks\"\nimport { useScopeProps } from \"#orck/scope-context\"\nimport { canSavePaymentMethod, checkoutPsps, type PspConfig } from \"#orck/psp\"\nimport { SavePaymentMethod } from \"#orck/save-payment-method\"\nimport { cardText, RESET } from \"./format\"\nimport { EmptyState, ErrorState, ListSkeleton, Section } from \"./section\"\nimport { useNotice } from \"./notice\"\nimport { BillingStatusBadge } from \"./status-badge\"\n\nexport interface PaymentMethodsPanelProps {\n /**\n * OpenRails's browser PSP configs (checkout config). \"Add card\" offers\n * each one a card can be saved with in the page.\n */\n psps?: readonly PspConfig[]\n /** Return target after off-page card verification; see `SavePaymentMethod`. */\n cardSetupReturnURL?: (setupId: string) => string\n /** Enables \"Make default\" for this currency's invoice collection. */\n defaultCurrency?: string\n /** Billing country to preselect when adding a card. */\n defaultCountry?: string\n appearance?: CheckoutAppearance\n className?: string\n}\n\nfunction methodLabel(method: PaymentMethod, m: Translator): string {\n return cardText(method.card, m)\n}\n\nfunction removeMessage(error: BillingError, m: Translator): string {\n if (error.status === 409 && error.code === \"resource_conflict\")\n return m.t(\"paymentMethods.inUse\")\n return m.error(error)\n}\n\nexport function PaymentMethodsPanel({\n psps,\n cardSetupReturnURL,\n defaultCurrency,\n defaultCountry,\n appearance,\n className,\n}: PaymentMethodsPanelProps) {\n const m = useMessages()\n const { t } = m\n const scope = useScopeProps(appearance)\n const state = usePaymentMethods()\n const [removing, setRemoving] = React.useState<PaymentMethod | null>(null)\n const [removeError, setRemoveError] = React.useState<string | null>(null)\n const [rowError, setRowError] = React.useState<{\n id: string\n message: string\n } | null>(null)\n const [adding, setAdding] = React.useState(false)\n const savable = checkoutPsps(psps ?? []).filter(canSavePaymentMethod)\n const [pspId, setPspId] = React.useState<string>()\n const psp = savable.find((item) => item.psp_id === pspId) ?? savable[0]\n const [notice, announce] = useNotice()\n const currency = defaultCurrency?.toUpperCase()\n\n const confirmRemove = async () => {\n if (!removing) return\n setRemoveError(null)\n const error = await state.remove(removing.id)\n if (error) {\n setRemoveError(removeMessage(error, m))\n return\n }\n setRemoving(null)\n announce(t(\"paymentMethods.removed\"))\n }\n\n const makeDefault = async (method: PaymentMethod) => {\n if (!currency) return\n setRowError(null)\n const error = await state.setDefault(method.id, currency)\n if (error) setRowError({ id: method.id, message: m.error(error) })\n else announce(t(\"paymentMethods.madeDefault\"))\n }\n\n let body: React.ReactNode\n const methods = state.methods\n if (methods === null && state.error) {\n body = <ErrorState error={state.error} onRetry={state.refetch} />\n } else if (methods === null) {\n body = <ListSkeleton />\n } else if (methods.length === 0) {\n body = (\n <EmptyState\n title={t(\"paymentMethods.empty\")}\n description={t(\"paymentMethods.emptyDescription\")}\n />\n )\n } else {\n body = (\n <ul className=\"-my-1 divide-y divide-border\">\n {methods.map((method) => {\n const label = methodLabel(method, m)\n const users = (method.subscriptions ?? [])\n .map((s) => s.display_name)\n .filter(Boolean)\n const health = method.health?.expiry_status\n const defaults = method.collection_default_currencies ?? []\n const pending = state.pending[method.id]\n const meta = [\n users.length > 0 &&\n t(\"paymentMethods.usedBy\", { names: users.join(\", \") }),\n ].filter(Boolean)\n return (\n <li\n key={method.id}\n data-testid=\"payment-method-row\"\n data-payment-method-id={method.id}\n className=\"flex flex-wrap items-center gap-x-3 gap-y-2 py-3.5\"\n >\n <CardBrandPlate\n brand={method.card?.brand ?? undefined}\n fallback={(method.card?.brand ?? \"card\").slice(0, 4)}\n />\n <div className=\"grid min-w-40 flex-1 gap-0.5\">\n <div className=\"flex flex-wrap items-center gap-x-2 gap-y-1\">\n <span className=\"text-sm font-medium tabular-nums\">\n {label}\n </span>\n {health === \"expired\" || health === \"expiring_soon\" ? (\n <BillingStatusBadge status={health} />\n ) : method.health?.active === false ? (\n <BillingStatusBadge status=\"needs_attention\" />\n ) : null}\n {defaults.length > 0 ? (\n <BillingStatusBadge\n status=\"default\"\n label={t(\"paymentMethods.defaultFor\", {\n currencies: defaults.join(\", \"),\n })}\n />\n ) : null}\n </div>\n {meta.length > 0 ? (\n <p className=\"text-sm text-muted-foreground tabular-nums\">\n {meta.join(\" · \")}\n </p>\n ) : null}\n {rowError?.id === method.id ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {rowError.message}\n </p>\n ) : null}\n </div>\n <div className=\"ml-auto flex items-center gap-1\">\n {currency && !defaults.includes(currency) ? (\n <Button\n variant=\"ghost\"\n size=\"sm\"\n className=\"text-muted-foreground\"\n disabled={!!pending}\n onClick={() => void makeDefault(method)}\n >\n {pending === \"default\" ? <Spinner /> : null}\n {t(\"paymentMethods.makeDefault\")}\n </Button>\n ) : null}\n <Button\n variant=\"ghost\"\n size=\"icon-sm\"\n className=\"text-muted-foreground hover:text-destructive\"\n aria-label={t(\"paymentMethods.removeLabel\", { label })}\n title={t(\"paymentMethods.remove\")}\n disabled={!!pending}\n onClick={() => {\n setRemoveError(null)\n setRemoving(method)\n }}\n >\n {pending === \"remove\" ? (\n <Spinner />\n ) : (\n <HugeiconsIcon icon={Delete02Icon} aria-hidden />\n )}\n </Button>\n </div>\n </li>\n )\n })}\n </ul>\n )\n }\n\n const removingBusy = removing\n ? state.pending[removing.id] === \"remove\"\n : false\n const removingLabel = removing ? methodLabel(removing, m) : \"\"\n\n return (\n <Section\n title={t(\"paymentMethods.title\")}\n description={t(\"paymentMethods.description\")}\n appearance={appearance}\n className={className}\n data-testid=\"payment-methods-panel\"\n action={\n psp ? (\n <Button variant=\"outline\" size=\"sm\" onClick={() => setAdding(true)}>\n <HugeiconsIcon\n icon={Add01Icon}\n aria-hidden\n data-icon=\"inline-start\"\n />\n {t(\"paymentMethods.add\")}\n </Button>\n ) : null\n }\n >\n {body}\n {methods !== null && state.error ? (\n <div className=\"pt-3\">\n <ErrorState error={state.error} onRetry={state.refetch} />\n </div>\n ) : null}\n {notice}\n\n <AlertDialog\n open={removing !== null}\n onOpenChange={(open) => {\n if (!open && !removingBusy) setRemoving(null)\n }}\n >\n <AlertDialogContent\n className={`${scope.className} ${RESET} bg-popover text-popover-foreground`}\n data-orck-theme={scope[\"data-orck-theme\"]}\n style={scope.style}\n >\n <AlertDialogHeader>\n <AlertDialogTitle>\n {t(\"paymentMethods.removeTitle\", { label: removingLabel })}\n </AlertDialogTitle>\n <AlertDialogDescription>\n {t(\"paymentMethods.removeDescription\")}\n </AlertDialogDescription>\n </AlertDialogHeader>\n {removeError ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {removeError}\n </p>\n ) : null}\n <AlertDialogFooter>\n <AlertDialogCancel disabled={removingBusy}>\n {t(\"common.cancel\")}\n </AlertDialogCancel>\n <Button\n variant=\"destructive\"\n disabled={removingBusy}\n onClick={() => void confirmRemove()}\n >\n {removingBusy ? <Spinner /> : null}\n {t(\"paymentMethods.removeConfirm\")}\n </Button>\n </AlertDialogFooter>\n </AlertDialogContent>\n </AlertDialog>\n\n {psp ? (\n <Dialog open={adding} onOpenChange={setAdding}>\n <DialogContent\n className={`${scope.className} ${RESET} max-h-[calc(100dvh-2rem)] overflow-y-auto bg-popover text-popover-foreground`}\n data-orck-theme={scope[\"data-orck-theme\"]}\n style={scope.style}\n >\n <DialogHeader>\n <DialogTitle>{t(\"paymentMethods.addTitle\")}</DialogTitle>\n <DialogDescription>\n {t(\"paymentMethods.addDescription\")}\n </DialogDescription>\n </DialogHeader>\n {savable.length > 1 ? (\n <label className=\"grid gap-1.5 text-sm\">\n {t(\"paymentMethods.provider\")}\n <select\n className=\"h-9 rounded-md border border-input bg-transparent px-2\"\n value={psp.psp_id}\n onChange={(event) => setPspId(event.target.value)}\n >\n {savable.map((item) => (\n <option key={item.psp_id} value={item.psp_id}>\n {item.display_name}\n </option>\n ))}\n </select>\n </label>\n ) : null}\n <SavePaymentMethod\n key={psp.psp_id}\n psp={psp}\n returnURL={cardSetupReturnURL}\n defaultCountry={defaultCountry}\n appearance={appearance}\n onSaved={() => {\n setAdding(false)\n announce(t(\"paymentMethods.added\"))\n }}\n />\n </DialogContent>\n </Dialog>\n ) : null}\n </Section>\n )\n}\n","import * as React from \"react\"\nimport { cn } from \"cn\"\n\nfunction Textarea({ className, ...props }: React.ComponentProps<\"textarea\">) {\n return (\n <textarea\n data-slot=\"textarea\"\n className={cn(\n \"flex field-sizing-content min-h-16 w-full rounded-md border border-input bg-transparent px-2.5 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40\",\n className\n )}\n {...props}\n />\n )\n}\n\nexport { Textarea }\n","import * as React from \"react\"\n\nimport type { CheckoutAppearance } from \"#orck/appearance\"\n\nimport {\n CANCEL_FEEDBACK_MAX,\n CANCEL_FEEDBACK_MIN,\n isWalletRejection,\n} from \"#orck/client/client\"\nimport type { BillingError } from \"#orck/client/errors\"\nimport {\n AlertDialog,\n AlertDialogCancel,\n AlertDialogContent,\n AlertDialogDescription,\n AlertDialogFooter,\n AlertDialogHeader,\n AlertDialogTitle,\n} from \"#orck/components/ui/alert-dialog\"\nimport { Button } from \"#orck/components/ui/button\"\nimport { Label } from \"#orck/components/ui/label\"\nimport { Spinner } from \"#orck/components/ui/spinner\"\nimport { Textarea } from \"#orck/components/ui/textarea\"\nimport { useMessages } from \"#orck/i18n/context\"\nimport type { SubscriptionAction } from \"#orck/react/hooks\"\nimport { useScopeProps } from \"#orck/scope-context\"\nimport { RESET } from \"./format\"\n\n// Key it per subscription so each opening starts blank.\nexport interface CancelSubscriptionDialogProps {\n open: boolean\n onOpenChange: (open: boolean) => void\n /** Subscription display name. */\n name: string\n /** On-chain (Solana) cancel: no feedback, the wallet signs. */\n onChain?: boolean\n /** In-flight stage, when cancelling. */\n pending?: SubscriptionAction\n /** Resolves null on success; the dialog then closes. */\n onConfirm: (feedback: string) => Promise<BillingError | null>\n appearance?: CheckoutAppearance\n}\n\nexport function CancelSubscriptionDialog({\n open,\n onOpenChange,\n name,\n onChain = false,\n pending,\n onConfirm,\n appearance,\n}: CancelSubscriptionDialogProps) {\n const m = useMessages()\n const { t } = m\n const scope = useScopeProps(appearance)\n const reasonId = React.useId()\n const hintId = React.useId()\n const [feedback, setFeedback] = React.useState(\"\")\n const [touched, setTouched] = React.useState(false)\n const [error, setError] = React.useState<BillingError | null>(null)\n const busy = pending !== undefined\n\n const length = feedback.trim().length\n const tooShort = !onChain && length < CANCEL_FEEDBACK_MIN\n const confirm = async () => {\n setTouched(true)\n if (tooShort || busy) return\n setError(null)\n const result = await onConfirm(feedback)\n if (!result) onOpenChange(false)\n else if (!isWalletRejection(result)) setError(result)\n }\n\n const stageLabel =\n pending === \"preparing\"\n ? t(\"cancel.preparing\")\n : pending === \"signing\"\n ? t(\"cancel.signing\")\n : pending === \"confirming\"\n ? t(\"cancel.confirming\")\n : busy\n ? t(\"cancel.working\")\n : onChain\n ? t(\"cancel.confirmWallet\")\n : t(\"cancel.confirm\")\n\n return (\n <AlertDialog\n open={open}\n onOpenChange={(next) => {\n if (!next && busy) return\n onOpenChange(next)\n }}\n >\n <AlertDialogContent\n className={`${scope.className} ${RESET} bg-popover text-popover-foreground`}\n data-orck-theme={scope[\"data-orck-theme\"]}\n style={scope.style}\n >\n <form\n className=\"grid gap-5\"\n noValidate\n onSubmit={(event) => {\n event.preventDefault()\n void confirm()\n }}\n >\n <AlertDialogHeader>\n <AlertDialogTitle>{t(\"cancel.title\", { name })}</AlertDialogTitle>\n <AlertDialogDescription>\n {onChain\n ? t(\"cancel.solanaDescription\")\n : t(\"cancel.description\")}\n </AlertDialogDescription>\n </AlertDialogHeader>\n {onChain ? null : (\n <div className=\"grid gap-2\">\n <Label htmlFor={reasonId}>{t(\"cancel.reasonLabel\")}</Label>\n <Textarea\n id={reasonId}\n value={feedback}\n maxLength={CANCEL_FEEDBACK_MAX}\n placeholder={t(\"cancel.reasonPlaceholder\")}\n aria-describedby={hintId}\n aria-invalid={touched && tooShort ? true : undefined}\n disabled={busy}\n required\n rows={3}\n className=\"[font:inherit]\"\n onChange={(event) => setFeedback(event.target.value)}\n onBlur={() => length > 0 && setTouched(true)}\n />\n <div\n id={hintId}\n className=\"flex justify-between gap-3 text-xs text-muted-foreground\"\n >\n <span className={touched && tooShort ? \"text-destructive\" : \"\"}>\n {touched && tooShort\n ? t(\"cancel.reasonTooShort\", { min: CANCEL_FEEDBACK_MIN })\n : \"\"}\n </span>\n <span className=\"tabular-nums\">\n {t(\"cancel.reasonHint\", {\n count: feedback.length,\n max: CANCEL_FEEDBACK_MAX,\n })}\n </span>\n </div>\n </div>\n )}\n {error ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {m.error(error)}\n </p>\n ) : null}\n <AlertDialogFooter>\n <AlertDialogCancel disabled={busy}>\n {t(\"cancel.keep\")}\n </AlertDialogCancel>\n <Button type=\"submit\" variant=\"destructive\" disabled={busy}>\n {busy ? <Spinner /> : null}\n {stageLabel}\n </Button>\n </AlertDialogFooter>\n </form>\n </AlertDialogContent>\n </AlertDialog>\n )\n}\n","\"use client\"\n\nimport { Radio as RadioPrimitive } from \"@base-ui/react/radio\"\nimport { RadioGroup as RadioGroupPrimitive } from \"@base-ui/react/radio-group\"\nimport { cn } from \"cn\"\n\nfunction RadioGroup({ className, ...props }: RadioGroupPrimitive.Props) {\n return (\n <RadioGroupPrimitive\n data-slot=\"radio-group\"\n className={cn(\"grid w-full gap-3\", className)}\n {...props}\n />\n )\n}\n\nfunction RadioGroupItem({ className, ...props }: RadioPrimitive.Root.Props) {\n return (\n <RadioPrimitive.Root\n data-slot=\"radio-group-item\"\n className={cn(\n \"group/radio-group-item peer relative flex aspect-square size-4 shrink-0 rounded-full border border-input outline-none group-has-[:focus-visible]/field-label:ring-0 group-has-[:focus-visible]/field-label:not-data-checked:border-input after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 aria-invalid:aria-checked:border-primary dark:bg-input/30 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:border-primary data-checked:bg-primary data-checked:text-primary-foreground group-has-[:focus-visible]/field-label:data-checked:border-primary dark:data-checked:bg-primary\",\n className\n )}\n {...props}\n >\n <RadioPrimitive.Indicator\n data-slot=\"radio-group-indicator\"\n className=\"flex size-4 items-center justify-center\"\n >\n <span className=\"absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2 rounded-full bg-primary-foreground\" />\n </RadioPrimitive.Indicator>\n </RadioPrimitive.Root>\n )\n}\n\nexport { RadioGroup, RadioGroupItem }\n","import * as React from \"react\"\n\nimport type { CheckoutAppearance } from \"#orck/appearance\"\nimport { cn } from \"cn\"\n\nimport type { BillingError } from \"#orck/client/errors\"\nimport type { PaymentMethod, Subscription } from \"#orck/client/types\"\nimport { CardBrandPlate } from \"#orck/components/card-brands\"\nimport { Button } from \"#orck/components/ui/button\"\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n} from \"#orck/components/ui/dialog\"\nimport { Label } from \"#orck/components/ui/label\"\nimport { RadioGroup, RadioGroupItem } from \"#orck/components/ui/radio-group\"\nimport { Spinner } from \"#orck/components/ui/spinner\"\nimport { useMessages } from \"#orck/i18n/context\"\nimport { usePaymentMethods } from \"#orck/react/hooks\"\nimport { useScopeProps } from \"#orck/scope-context\"\nimport { cardText, RESET } from \"./format\"\nimport { ErrorState, ListSkeleton } from \"./section\"\n\n/** Cards the subscription's PSP can charge; expired cards are left out. */\nfunction eligibleCards(\n s: Subscription,\n methods: readonly PaymentMethod[]\n): PaymentMethod[] {\n return methods.filter(\n (m) =>\n m.health?.expiry_status !== \"expired\" &&\n (!s.psp_id || !m.psp_id || m.psp_id === s.psp_id) &&\n (!s.rail || !m.rail || m.rail === s.rail)\n )\n}\n\nexport interface ChangeCardDialogProps {\n subscription: Subscription | null\n name: string\n onOpenChange: (open: boolean) => void\n pending: boolean\n /** Resolves null on success; the dialog then closes. */\n onConfirm: (paymentMethodId: string) => Promise<BillingError | null>\n appearance?: CheckoutAppearance\n}\n\nexport function ChangeCardDialog({\n subscription,\n name,\n onOpenChange,\n pending,\n onConfirm,\n appearance,\n}: ChangeCardDialogProps) {\n const scope = useScopeProps(appearance)\n return (\n <Dialog\n open={subscription !== null}\n onOpenChange={(next) => {\n if (!next && pending) return\n onOpenChange(next)\n }}\n >\n <DialogContent\n showCloseButton={false}\n className={`${scope.className} ${RESET} bg-popover text-popover-foreground`}\n data-orck-theme={scope[\"data-orck-theme\"]}\n style={scope.style}\n >\n {subscription ? (\n <ChangeCardForm\n subscription={subscription}\n name={name}\n pending={pending}\n onCancel={() => onOpenChange(false)}\n onConfirm={onConfirm}\n />\n ) : null}\n </DialogContent>\n </Dialog>\n )\n}\n\n// Mounted only while open, so the card list loads on demand.\nfunction ChangeCardForm({\n subscription,\n name,\n pending,\n onCancel,\n onConfirm,\n}: {\n subscription: Subscription\n name: string\n pending: boolean\n onCancel: () => void\n onConfirm: (paymentMethodId: string) => Promise<BillingError | null>\n}) {\n const m = useMessages()\n const { t } = m\n const idPrefix = React.useId()\n const methods = usePaymentMethods()\n const current = subscription.payment_method_id ?? \"\"\n const [selected, setSelected] = React.useState(current)\n const [error, setError] = React.useState<BillingError | null>(null)\n const cards = methods.methods\n ? eligibleCards(subscription, methods.methods)\n : null\n const canSwitch = !!cards && cards.some((c) => c.id !== current)\n\n const confirm = async () => {\n if (!selected || selected === current || pending) return\n setError(null)\n const result = await onConfirm(selected)\n if (result) setError(result)\n }\n\n let list: React.ReactNode\n if (cards === null && methods.error) {\n list = <ErrorState error={methods.error} onRetry={methods.refetch} />\n } else if (cards === null) {\n list = <ListSkeleton rows={2} />\n } else {\n list = (\n <RadioGroup\n value={selected}\n onValueChange={(next) => {\n if (typeof next === \"string\" && next) setSelected(next)\n }}\n disabled={pending}\n aria-label={t(\"changeCard.title\", { name })}\n className=\"grid gap-0\"\n >\n {cards.map((card) => {\n const id = `${idPrefix}-${card.id}`\n return (\n <Label\n key={card.id}\n htmlFor={id}\n data-testid=\"change-card-option\"\n className={cn(\n \"flex cursor-pointer items-center gap-3 py-1.5 select-none\",\n pending && \"cursor-default\"\n )}\n >\n <RadioGroupItem id={id} value={card.id} />\n <CardBrandPlate\n brand={card.card?.brand ?? undefined}\n fallback={(card.card?.brand ?? \"card\").slice(0, 4)}\n />\n <span className=\"min-w-0 flex-1 truncate text-sm font-medium tabular-nums\">\n {cardText(card.card, m)}\n </span>\n {card.id === current ? (\n <span className=\"shrink-0 text-xs text-muted-foreground\">\n {t(\"changeCard.current\")}\n </span>\n ) : null}\n </Label>\n )\n })}\n </RadioGroup>\n )\n }\n\n return (\n <form\n className=\"grid gap-5\"\n noValidate\n onSubmit={(event) => {\n event.preventDefault()\n void confirm()\n }}\n >\n <DialogHeader>\n <DialogTitle>{t(\"changeCard.title\", { name })}</DialogTitle>\n <DialogDescription>\n {cards !== null && !canSwitch\n ? t(\"changeCard.none\")\n : t(\"changeCard.description\")}\n </DialogDescription>\n </DialogHeader>\n {list}\n {error ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {m.error(error)}\n </p>\n ) : null}\n <DialogFooter>\n <Button\n type=\"button\"\n variant=\"outline\"\n disabled={pending}\n onClick={onCancel}\n >\n {t(\"common.cancel\")}\n </Button>\n <Button\n type=\"submit\"\n disabled={pending || !selected || selected === current}\n >\n {pending ? <Spinner /> : null}\n {t(\"changeCard.confirm\")}\n </Button>\n </DialogFooter>\n </form>\n )\n}\n","import * as React from \"react\"\nimport { HugeiconsIcon } from \"@hugeicons/react\"\nimport { ArrowUpRight01Icon } from \"@hugeicons/core-free-icons\"\nimport { cn } from \"cn\"\n\nimport type { CheckoutAppearance } from \"#orck/appearance\"\nimport type { SendSolanaTransaction } from \"#orck/client/client\"\nimport type { Subscription } from \"#orck/client/types\"\nimport { Button, buttonVariants } from \"#orck/components/ui/button\"\nimport { Spinner } from \"#orck/components/ui/spinner\"\nimport { useMessages } from \"#orck/i18n/context\"\nimport { useSubscriptions, type SubscriptionsOptions } from \"#orck/react/hooks\"\nimport { useBillingClient } from \"#orck/react/context\"\nimport { useUiSettings } from \"#orck/scope-context\"\nimport { CancelSubscriptionDialog } from \"./cancel-dialog\"\nimport { ChangeCardDialog } from \"./change-card-dialog\"\nimport {\n brandName,\n formatDate,\n formatMoney,\n intervalLabel,\n isEnding,\n isLive,\n LIVE_STATUSES,\n subscriptionName,\n} from \"./format\"\nimport { EmptyState, ErrorState, ListSkeleton, Section } from \"./section\"\nimport { useNotice } from \"./notice\"\nimport { BillingStatusBadge } from \"./status-badge\"\n\nexport interface SubscriptionsPanelProps extends SubscriptionsOptions {\n /**\n * Wallet for Solana-rail subscriptions. Without it their cancel action is\n * hidden.\n */\n sendSolanaTransaction?: SendSolanaTransaction\n /** Empty-state link to the host's plans page (uses `navigate` if set). */\n plansHref?: string\n /** Host content under a row, e.g. a plan-change control. */\n renderSubscriptionFooter?: (subscription: Subscription) => React.ReactNode\n appearance?: CheckoutAppearance\n className?: string\n}\n\nexport function SubscriptionsPanel({\n sendSolanaTransaction,\n plansHref,\n renderSubscriptionFooter,\n appearance,\n className,\n ...options\n}: SubscriptionsPanelProps) {\n const m = useMessages()\n const { t } = m\n const { locale, navigate } = useUiSettings()\n const state = useSubscriptions(options)\n const scales = useBillingClient().currencies\n const [cancelling, setCancelling] = React.useState<Subscription | null>(null)\n const [changingCard, setChangingCard] = React.useState<Subscription | null>(\n null\n )\n const [rowError, setRowError] = React.useState<{\n id: string\n message: string\n } | null>(null)\n const [notice, announce] = useNotice()\n\n const rows = React.useMemo(() => {\n const list = state.subscriptions ?? []\n return [...list.filter(isLive), ...list.filter((s) => !isLive(s))]\n }, [state.subscriptions])\n\n const resume = async (s: Subscription) => {\n setRowError(null)\n const error = await state.resume(s.id)\n if (error) setRowError({ id: s.id, message: m.error(error) })\n else announce(t(\"subscriptions.resumed\"))\n }\n\n const onChain = cancelling?.rail === \"solana\"\n\n let body: React.ReactNode\n if (state.subscriptions === null && state.error) {\n body = <ErrorState error={state.error} onRetry={state.refetch} />\n } else if (state.subscriptions === null) {\n body = <ListSkeleton />\n } else if (rows.length === 0) {\n body = (\n <EmptyState\n title={t(\"subscriptions.empty\")}\n description={t(\"subscriptions.emptyDescription\")}\n action={\n plansHref ? (\n <a\n href={plansHref}\n className={buttonVariants({ variant: \"outline\", size: \"sm\" })}\n onClick={(event) => {\n if (!navigate) return\n event.preventDefault()\n navigate(plansHref)\n }}\n >\n {t(\"subscriptions.browsePlans\")}\n </a>\n ) : null\n }\n />\n )\n } else {\n body = (\n <ul className=\"-my-1 divide-y divide-border\">\n {rows.map((s) => {\n const live = isLive(s)\n const pending = state.pending[s.id]\n const name = subscriptionName(s, m)\n const price = s.price\n ? formatMoney(s.price.unit_amount, s.price.currency, scales, locale)\n : null\n const interval = intervalLabel(s.price, m)\n const periodEnd = formatDate(s.current_period_ends_at, locale)\n const endedAt = formatDate(\n s.ended_at ?? s.cancelled_at ?? s.current_period_ends_at,\n locale\n )\n const scheduled = isEnding(s)\n const renews = live && !scheduled && s.price?.auto_renew !== false\n const when = !live\n ? endedAt && t(\"subscriptions.endedOn\", { date: endedAt })\n : periodEnd &&\n (renews\n ? t(\"subscriptions.renews\", { date: periodEnd })\n : t(\"subscriptions.endsOn\", { date: periodEnd }))\n const paidWith =\n s.rail === \"solana\"\n ? t(\"subscriptions.wallet\")\n : s.card?.last4\n ? t(\"subscriptions.paidWith\", {\n brand: brandName(\n s.card.brand,\n t(\"paymentMethods.fallbackBrand\")\n ),\n last4: s.card.last4,\n })\n : null\n const portal = live && !scheduled ? s.cancel_portal_url : null\n const canCancel =\n LIVE_STATUSES.has(s.status) &&\n !scheduled &&\n !portal &&\n (s.rail !== \"solana\" || !!sendSolanaTransaction)\n const canChangeCard =\n (s.status === \"active\" ||\n s.status === \"past_due\" ||\n s.status === \"awaiting_method\" ||\n s.status === \"unverified\") &&\n !scheduled &&\n !portal &&\n s.rail !== \"solana\" &&\n !!s.payment_method_id\n const status = scheduled ? \"cancel_scheduled\" : s.status\n const footer = renderSubscriptionFooter?.(s)\n return (\n <li\n key={s.id}\n data-testid=\"subscription-row\"\n data-subscription-id={s.id}\n className=\"grid gap-3 py-4 @md:grid-cols-[1fr_auto] @md:items-center\"\n >\n <div className=\"grid min-w-0 gap-1\">\n <div className=\"flex flex-wrap items-center gap-x-2 gap-y-1\">\n <span\n className={cn(\n \"truncate text-sm font-semibold\",\n !live && \"text-muted-foreground\"\n )}\n >\n {name}\n </span>\n <BillingStatusBadge status={status} />\n </div>\n <p className=\"text-sm text-muted-foreground tabular-nums\">\n {[when, paidWith].filter(Boolean).join(\" · \") ||\n t(\"common.notAvailable\")}\n </p>\n {price ? (\n <p\n className={cn(\n \"text-sm tabular-nums\",\n !live && \"text-muted-foreground\"\n )}\n >\n <span className=\"font-medium\">{price}</span>\n {interval ? (\n <span className=\"text-muted-foreground\"> {interval}</span>\n ) : null}\n </p>\n ) : null}\n {s.status === \"past_due\" || s.status === \"awaiting_method\" ? (\n <p className=\"text-sm text-destructive\">\n {t(\"subscriptions.pastDue\")}\n </p>\n ) : null}\n {rowError?.id === s.id ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {rowError.message}\n </p>\n ) : null}\n </div>\n <div className=\"flex flex-wrap gap-2 @md:justify-end\">\n {s.resumable ? (\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={!!pending}\n onClick={() => void resume(s)}\n >\n {pending === \"resume\" ? <Spinner /> : null}\n {pending === \"resume\"\n ? t(\"subscriptions.updating\")\n : t(\"subscriptions.resume\")}\n </Button>\n ) : null}\n {portal ? (\n <a\n href={portal}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n className={buttonVariants({\n variant: \"outline\",\n size: \"sm\",\n })}\n >\n {t(\"subscriptions.manageAtProvider\")}\n <HugeiconsIcon icon={ArrowUpRight01Icon} aria-hidden />\n </a>\n ) : null}\n {canChangeCard ? (\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={!!pending}\n aria-label={t(\"subscriptions.changeCardLabel\", { name })}\n onClick={() => {\n setRowError(null)\n setChangingCard(s)\n }}\n >\n {pending === \"payment_method\" ? <Spinner /> : null}\n {t(\"subscriptions.changeCard\")}\n </Button>\n ) : null}\n {canCancel ? (\n <Button\n variant=\"ghost\"\n size=\"sm\"\n className=\"text-muted-foreground hover:text-destructive\"\n disabled={!!pending}\n aria-label={t(\"subscriptions.cancelLabel\", { name })}\n onClick={() => {\n setRowError(null)\n setCancelling(s)\n }}\n >\n {pending &&\n pending !== \"resume\" &&\n pending !== \"payment_method\" &&\n pending !== \"change_tier\" ? (\n <Spinner />\n ) : null}\n {t(\"subscriptions.cancel\")}\n </Button>\n ) : null}\n </div>\n {footer ? (\n <div\n data-testid=\"subscription-footer\"\n className=\"border-t border-border/60 pt-3 @md:col-span-2\"\n >\n {footer}\n </div>\n ) : null}\n </li>\n )\n })}\n </ul>\n )\n }\n\n return (\n <Section\n title={t(\"subscriptions.title\")}\n description={t(\"subscriptions.description\")}\n appearance={appearance}\n className={className}\n data-testid=\"subscriptions-panel\"\n >\n {body}\n {state.subscriptions !== null && state.error ? (\n <div className=\"pt-3\">\n <ErrorState error={state.error} onRetry={state.refetch} />\n </div>\n ) : null}\n {notice}\n <ChangeCardDialog\n key={`card-${changingCard?.id ?? \"closed\"}`}\n subscription={changingCard}\n name={changingCard ? subscriptionName(changingCard, m) : \"\"}\n onOpenChange={(open) => !open && setChangingCard(null)}\n appearance={appearance}\n pending={\n !!changingCard && state.pending[changingCard.id] === \"payment_method\"\n }\n onConfirm={async (paymentMethodId) => {\n if (!changingCard) return null\n const error = await state.setPaymentMethod(\n changingCard.id,\n paymentMethodId\n )\n if (!error) {\n setChangingCard(null)\n announce(t(\"changeCard.done\"))\n }\n return error\n }}\n />\n <CancelSubscriptionDialog\n key={cancelling?.id ?? \"closed\"}\n open={cancelling !== null}\n onOpenChange={(open) => !open && setCancelling(null)}\n name={cancelling ? subscriptionName(cancelling, m) : \"\"}\n onChain={onChain}\n appearance={appearance}\n pending={cancelling ? state.pending[cancelling.id] : undefined}\n onConfirm={async (feedback) => {\n if (!cancelling) return null\n const error =\n onChain && sendSolanaTransaction\n ? await state.cancelOnChain(cancelling.id, sendSolanaTransaction)\n : await state.cancel(cancelling.id, feedback)\n if (!error) announce(t(\"cancel.done\"))\n return error\n }}\n />\n </Section>\n )\n}\n","import { cn } from \"cn\"\n\nimport type { CheckoutAppearance } from \"#orck/appearance\"\nimport type { SendSolanaTransaction } from \"#orck/client/client\"\nimport { BillingUiRoot } from \"#orck/scope\"\nimport { PaymentHistory } from \"./payment-history\"\nimport {\n PaymentMethodsPanel,\n type PaymentMethodsPanelProps,\n} from \"./payment-methods-panel\"\nimport {\n SubscriptionsPanel,\n type SubscriptionsPanelProps,\n} from \"./subscriptions-panel\"\n\nexport interface AccountBillingProps {\n psps?: PaymentMethodsPanelProps[\"psps\"]\n cardSetupReturnURL?: PaymentMethodsPanelProps[\"cardSetupReturnURL\"]\n defaultCurrency?: string\n /** Billing country to preselect when adding a card. */\n defaultCountry?: string\n sendSolanaTransaction?: SendSolanaTransaction\n plansHref?: string\n renderSubscriptionFooter?: SubscriptionsPanelProps[\"renderSubscriptionFooter\"]\n historyPageSize?: number\n appearance?: CheckoutAppearance\n className?: string\n}\n\n/** Subscriptions, payment methods and history in one column. */\nexport function AccountBilling({\n psps,\n cardSetupReturnURL,\n defaultCurrency,\n defaultCountry,\n sendSolanaTransaction,\n plansHref,\n renderSubscriptionFooter,\n historyPageSize,\n appearance,\n className,\n}: AccountBillingProps) {\n return (\n <BillingUiRoot\n appearance={appearance}\n className={cn(\"grid gap-6\", className)}\n data-testid=\"account-billing\"\n >\n <SubscriptionsPanel\n sendSolanaTransaction={sendSolanaTransaction}\n plansHref={plansHref}\n renderSubscriptionFooter={renderSubscriptionFooter}\n appearance={appearance}\n />\n <PaymentMethodsPanel\n psps={psps}\n cardSetupReturnURL={cardSetupReturnURL}\n defaultCurrency={defaultCurrency}\n defaultCountry={defaultCountry}\n appearance={appearance}\n />\n <PaymentHistory pageSize={historyPageSize} appearance={appearance} />\n </BillingUiRoot>\n )\n}\n","import type { BillingClient } from \"./client/client\"\nimport { loadStripeFor } from \"./lib/stripe\"\nimport { canAuthenticatePayment, type PspConfig } from \"./psp\"\n\n/**\n * Completes the provider challenge (3-D Secure) a pending payment operation\n * waits on. \"not_required\" when the provider has none outstanding; the\n * operation's own status remains the result.\n */\nexport async function authenticatePayment(\n client: BillingClient,\n operationId: string,\n psp: PspConfig\n): Promise<\"authenticated\" | \"not_required\"> {\n if (!canAuthenticatePayment(psp)) return \"not_required\"\n const { client_secret: secret } =\n await client.getPaymentAuthentication(operationId)\n if (!secret) return \"not_required\"\n const stripe = await loadStripeFor(psp.config!.publishable_key!)\n const result = await stripe.confirmCardPayment(secret)\n if (result.error)\n throw new Error(result.error.message ?? \"Authentication failed.\")\n await client.confirmPaymentAuthentication(operationId)\n return \"authenticated\"\n}\n","// CCBill credit-card hand-off uses the compact billing identity below. Name\n// stays canonical; the server binds verified email/IP and projects the provider.\nimport {\n BillingTextField,\n CountryField,\n PostalField,\n} from \"#orck/components/billing-fields\"\nimport type { CCBillBilling } from \"#orck/lib/ccbill\"\n\nexport function CCBillFields({\n idPrefix,\n value,\n onChange,\n disabled,\n error,\n}: {\n idPrefix: string\n value: CCBillBilling\n onChange: (next: CCBillBilling) => void\n disabled?: boolean\n error?: string\n}) {\n const set = (key: keyof CCBillBilling) => (next: string) =>\n onChange({ ...value, [key]: next })\n return (\n <>\n <BillingTextField\n id={`${idPrefix}-name-on-card`}\n name=\"name_on_card\"\n label=\"Name on card\"\n value={value.name_on_card}\n onChange={set(\"name_on_card\")}\n autoComplete=\"cc-name\"\n placeholder=\"Name as shown on card\"\n disabled={disabled}\n maxLength={200}\n required\n />\n <div className=\"grid grid-cols-2 gap-3\">\n <CountryField\n id={`${idPrefix}-country`}\n value={value.country}\n onChange={set(\"country\")}\n disabled={disabled}\n />\n <PostalField\n id={`${idPrefix}-zip`}\n value={value.zip}\n country={value.country}\n onChange={set(\"zip\")}\n disabled={disabled}\n required\n />\n </div>\n {error ? (\n <p className=\"text-[13px] text-destructive\" role=\"alert\">\n {error}\n </p>\n ) : null}\n </>\n )\n}\n","// CCBill credit-card identity. Verified account email and customer IP remain\n// server-owned; configurable street/city/state fields are not collected here.\nimport { z } from \"zod\"\n\nimport { countryCodeSchema, nameOnCardSchema } from \"#orck/lib/billing\"\n\nexport const ccbillBillingSchema = z.object({\n name_on_card: nameOnCardSchema,\n zip: z.string().trim().min(1, \"ZIP is required\"),\n country: countryCodeSchema,\n})\n\nexport type CCBillBilling = z.infer<typeof ccbillBillingSchema>\n\nexport const emptyCCBillBilling: CCBillBilling = {\n name_on_card: \"\",\n zip: \"\",\n country: \"\",\n}\n","// Customer-facing rail vocabulary. Unknown rails are not rendered — a rail\n// the UI cannot execute must not be offered.\nimport type { PaymentRailOption } from \"#orck/types\"\n\nexport interface RailMeta {\n label: string\n hint?: string\n}\n\n// A card taken in the page reads \"Card\" whichever PSP charges it.\nexport function railMeta(option: PaymentRailOption): RailMeta {\n if (\n option.driver === \"collect_js\" ||\n option.driver === \"card\" ||\n option.driver === \"stripe_elements\"\n )\n return { label: \"Card\" }\n return RAIL_META[option.rail]\n}\n\nexport const RAIL_META: Record<string, RailMeta> = {\n nmi: { label: \"Card\" },\n stripe: { label: \"Stripe\", hint: \"Opens Stripe\" },\n ccbill: { label: \"CCBill\", hint: \"Opens CCBill\" },\n // The Solana hint is not static: it names the token the host bound to the\n // option (see solanaToken), so the buyer sees the mint they will actually pay\n // with, on the network the host is actually on.\n solana: { label: \"Crypto\" },\n}\n\n// The Solana token the host bound to an option, read from its public_config:\n// - token_symbol — required; the SPL mint the price is bound to (USDC, USD1…).\n// - token_name — optional buyer-facing name (\"USD Coin\").\n// - network — optional Solana cluster (\"mainnet-beta\", \"devnet\",\n// \"testnet\"); anything but mainnet-beta is named in the UI so a\n// test-network payment is never mistaken for a real one.\n// The package never assumes a token: an option without token_symbol is not\n// offered (supportedOptions) — a rail the UI cannot execute must not be shown.\nexport interface SolanaToken {\n symbol: string\n name?: string\n network?: string\n}\n\nexport function solanaToken(\n option: PaymentRailOption\n): SolanaToken | undefined {\n const symbol = option.public_config?.token_symbol?.trim().toUpperCase()\n if (!symbol) return undefined\n const name = option.public_config?.token_name?.trim()\n const network = option.public_config?.network?.trim().toLowerCase()\n return {\n symbol,\n name: name || undefined,\n network: network || undefined,\n }\n}\n\nexport function solanaHint(token: SolanaToken): string {\n const label =\n token.name && token.name.toUpperCase() !== token.symbol\n ? `${token.name} (${token.symbol})`\n : token.symbol\n const chain =\n token.network && token.network !== \"mainnet-beta\"\n ? `Solana ${token.network}`\n : \"Solana\"\n return `${label} on ${chain}`\n}\n\nexport function supportedOptions(\n options: PaymentRailOption[]\n): PaymentRailOption[] {\n return options.filter((option) => {\n if (RAIL_META[option.rail] === undefined) return false\n if (option.driver === \"collect_js\" || option.driver === \"card\")\n return option.rail === \"nmi\"\n if (option.driver === \"stripe_elements\") return option.rail === \"stripe\"\n if (option.driver === \"redirect\")\n return option.rail === \"stripe\" || option.rail === \"ccbill\"\n return (\n option.driver === \"solana_pay\" &&\n option.rail === \"solana\" &&\n solanaToken(option) !== undefined\n )\n })\n}\n","// The method list: flat hairline-separated rows on a shared radio group.\n// Selection reads through the filled radio and the row title going ink —\n// never a highlighted container (containment budget: one, owned by the\n// host). Each row expands its body in place.\nimport { cn } from \"cn\"\nimport { Label } from \"#orck/components/ui/label\"\nimport { RadioGroup, RadioGroupItem } from \"#orck/components/ui/radio-group\"\nimport { railMeta, solanaHint, solanaToken } from \"#orck/lib/rail-meta\"\nimport type { PaymentRailOption } from \"#orck/types\"\n\nexport function MethodList({\n rails,\n selected,\n onSelect,\n disabled,\n idPrefix,\n renderBody,\n}: {\n rails: PaymentRailOption[]\n selected: string\n onSelect: (optionID: string) => void\n disabled?: boolean\n idPrefix: string\n renderBody: (option: PaymentRailOption, active: boolean) => React.ReactNode\n}) {\n // One rail needs no chooser: render its body alone.\n if (rails.length === 1)\n return (\n <div className=\"[&>div]:pt-0 [&>div]:pb-0 [&>div]:pl-0\">\n {renderBody(rails[0], true)}\n </div>\n )\n return (\n <RadioGroup\n aria-label=\"Payment method\"\n className=\"grid w-full gap-0\"\n value={selected}\n onValueChange={(value) => {\n if (typeof value === \"string\" && value) onSelect(value)\n }}\n disabled={disabled}\n >\n {rails.map((option) => {\n const meta = railMeta(option)\n const token = option.rail === \"solana\" ? solanaToken(option) : undefined\n const hint = token ? solanaHint(token) : meta.hint\n const active = option.id === selected\n const controlId = `${idPrefix}-option-${option.id}`\n return (\n <div\n key={option.id}\n className=\"border-t border-[color:var(--orck-hairline)] first:border-t-0\"\n >\n <Label\n htmlFor={controlId}\n className={cn(\n \"flex cursor-pointer items-center gap-2.5 py-[13px] text-sm font-medium text-muted-foreground select-none\",\n active && \"font-semibold text-foreground\",\n disabled && \"cursor-default\"\n )}\n >\n <RadioGroupItem id={controlId} value={option.id} />\n {meta.label}\n {hint ? (\n <span className=\"ml-auto text-xs font-normal text-[color:var(--orck-faint)]\">\n {hint}\n </span>\n ) : null}\n </Label>\n {renderBody(option, active)}\n </div>\n )\n })}\n </RadioGroup>\n )\n}\n\nexport function MethodBody({\n children,\n hidden,\n}: {\n children: React.ReactNode\n hidden?: boolean\n}) {\n return (\n <div\n aria-hidden={hidden || undefined}\n className={cn(\n \"grid gap-3.5 pt-1 pb-[18px] pl-[26px]\",\n hidden && \"hidden\"\n )}\n >\n {children}\n </div>\n )\n}\n","// Solana Pay transfer request: the official SDK owns QR rendering while the\n// checkout owns lifecycle copy and the same-device wallet link.\nimport * as React from \"react\"\n\nimport { buttonVariants } from \"#orck/components/ui/button\"\nimport { cn } from \"cn\"\n\n// Keep the official renderer's full quiet zone. Cropping it makes the tile\n// denser but materially reduces scan reliability on lower-quality cameras.\nconst QR_SIZE = 208\n\nexport function SolanaBody({\n amountLabel,\n payload,\n statusLine,\n}: {\n amountLabel: string\n payload?: string\n statusLine: string\n}) {\n const qrRef = React.useRef<HTMLDivElement | null>(null)\n const [qrState, setQrState] = React.useState<\"loading\" | \"ready\" | \"failed\">(\n \"loading\"\n )\n\n React.useEffect(() => {\n const container = qrRef.current\n if (!container || !payload) return\n\n let cancelled = false\n container.replaceChildren()\n setQrState(\"loading\")\n void import(\"@solana/pay\")\n .then(({ createQR }) => {\n if (cancelled) return\n createQR(payload, QR_SIZE, \"#ffffff\", \"#18181b\").append(container)\n setQrState(\"ready\")\n })\n .catch(() => {\n if (!cancelled) setQrState(\"failed\")\n })\n return () => {\n cancelled = true\n container.replaceChildren()\n }\n }, [payload])\n\n return (\n <div className=\"grid justify-items-center gap-3 py-1\">\n <div className=\"grid place-items-center rounded-xl bg-white p-1 shadow-sm ring-1 ring-black/10\">\n {payload ? (\n <div\n role=\"img\"\n aria-label=\"Solana Pay QR code\"\n className=\"relative overflow-hidden rounded-lg\"\n style={{ width: QR_SIZE, height: QR_SIZE }}\n >\n <div ref={qrRef} className=\"absolute inset-0\" />\n {qrState === \"loading\" ? (\n <div\n aria-hidden\n className=\"absolute inset-0 animate-pulse rounded-lg bg-zinc-100\"\n />\n ) : null}\n {qrState === \"failed\" ? (\n <div className=\"absolute inset-0 grid place-items-center text-center text-xs text-zinc-600\">\n QR code unavailable\n </div>\n ) : null}\n </div>\n ) : (\n <div\n aria-hidden\n className=\"animate-pulse rounded-lg bg-zinc-100\"\n style={{ width: QR_SIZE, height: QR_SIZE }}\n />\n )}\n </div>\n <div className=\"text-[13px] font-medium text-balance\">\n Scan with a Solana wallet\n </div>\n <div\n className=\"text-center text-[12.5px] text-pretty text-muted-foreground tabular-nums\"\n aria-live=\"polite\"\n >\n {amountLabel} · {statusLine}\n </div>\n {payload ? (\n <a\n href={payload}\n className={cn(\n buttonVariants({ variant: \"secondary\" }),\n \"h-9 w-full max-w-56\"\n )}\n >\n Open in wallet\n </a>\n ) : null}\n </div>\n )\n}\n","// Reuse of a card the customer already stored with this merchant. Selecting\n// one skips gateway tokenization entirely — the pay request carries the\n// stored method's id instead of a fresh token. Rows stay surfaceless like the\n// rail list above them; the brand plate and ink shift carry selection, so the\n// containment budget still belongs to the host.\nimport { HugeiconsIcon } from \"@hugeicons/react\"\nimport { Add01Icon } from \"@hugeicons/core-free-icons\"\nimport { CardBrandPlate } from \"#orck/components/card-brands\"\n\nimport { Label } from \"#orck/components/ui/label\"\nimport { RadioGroup, RadioGroupItem } from \"#orck/components/ui/radio-group\"\nimport { cn } from \"cn\"\nimport type { SavedPaymentMethod } from \"#orck/types\"\n\nexport const NEW_CARD_VALUE = \"new\"\n\n// Brand plates carry the network's own wordmark treatment at small size:\n// recognizable at a glance without shipping licensed logo art.\nconst BRAND_PLATE: Record<string, string> = {\n visa: \"VISA\",\n mastercard: \"MC\",\n amex: \"AMEX\",\n discover: \"DISC\",\n jcb: \"JCB\",\n diners: \"DINERS\",\n}\n\nfunction brandPlate(brand?: string): string {\n const key = brand?.trim().toLowerCase() ?? \"\"\n return BRAND_PLATE[key] ?? \"CARD\"\n}\n\n// The plate is decorative; assistive tech gets the spoken brand instead.\nfunction brandName(brand?: string): string {\n const value = brand?.trim()\n if (!value) return \"Card\"\n return value[0].toUpperCase() + value.slice(1)\n}\n\nfunction expiryLabel(method: SavedPaymentMethod): string | undefined {\n if (!method.exp_month || !method.exp_year) return undefined\n const month = String(method.exp_month).padStart(2, \"0\")\n return `${month}/${String(method.exp_year).slice(-2)}`\n}\n\nexport function SavedMethods({\n methods,\n value,\n onChange,\n disabled,\n idPrefix,\n}: {\n methods: SavedPaymentMethod[]\n value: string\n onChange: (value: string) => void\n disabled?: boolean\n idPrefix: string\n}) {\n return (\n <RadioGroup\n value={value}\n onValueChange={(next) => {\n if (typeof next === \"string\" && next) onChange(next)\n }}\n disabled={disabled}\n aria-label=\"Saved cards\"\n className=\"grid gap-0\"\n >\n {methods.map((method) => {\n const id = `${idPrefix}-${method.id}`\n const active = value === method.id\n const expires = expiryLabel(method)\n return (\n <Label\n key={method.id}\n htmlFor={id}\n className={cn(\n \"flex cursor-pointer items-center gap-3 py-1.5 select-none\",\n disabled && \"cursor-default\"\n )}\n >\n <RadioGroupItem id={id} value={method.id} />\n <CardBrandPlate\n brand={method.brand}\n fallback={brandPlate(method.brand)}\n />\n <span\n className={cn(\n \"min-w-0 flex-1 truncate text-sm font-medium text-muted-foreground tabular-nums transition-colors\",\n active && \"font-semibold text-foreground\"\n )}\n >\n <span className=\"sr-only\">\n {brandName(method.brand)} card ending {method.last_four}\n {expires ? `, expires ${expires}` : \"\"}\n </span>\n <span aria-hidden>\n {brandName(method.brand)} •••• {method.last_four ?? \"····\"}\n {expires ? (\n <span className=\"font-normal text-muted-foreground\">\n {\" \"}\n · {expires}\n </span>\n ) : null}\n </span>\n </span>\n </Label>\n )\n })}\n <Label\n htmlFor={`${idPrefix}-new`}\n className={cn(\n \"flex cursor-pointer items-center gap-3 py-1.5 text-sm font-medium text-muted-foreground select-none\",\n value === NEW_CARD_VALUE && \"font-semibold text-foreground\",\n disabled && \"cursor-default\"\n )}\n >\n <RadioGroupItem id={`${idPrefix}-new`} value={NEW_CARD_VALUE} />\n <span\n aria-hidden\n className={cn(\n \"grid h-7 w-11 shrink-0 place-items-center rounded-md border border-dashed border-border text-muted-foreground transition-colors\",\n value === NEW_CARD_VALUE &&\n \"border-solid border-transparent bg-foreground text-background\"\n )}\n >\n <HugeiconsIcon icon={Add01Icon} className=\"size-3.5\" />\n </span>\n Use a new card\n </Label>\n </RadioGroup>\n )\n}\n","// Order summary: the money story. Full variant (wide containers) is the\n// receipt — line items, tax, a single emphasized rule above \"Due today\".\n// Compact variant (narrow containers) is one line: who + what left, how much\n// right.\nimport { cn } from \"cn\"\nimport { useMessages } from \"#orck/i18n/context\"\nimport type { Translator } from \"#orck/i18n/messages\"\nimport { addAmounts, formatAmount, type Amount } from \"#orck/lib/money\"\nimport { everyLabel, perLabel } from \"#orck/lib/period\"\nimport type { CheckoutLineItem, CheckoutSession } from \"#orck/types\"\n\nfunction renewsLabel(session: CheckoutSession, m: Translator) {\n const every = session.plan.automatically_renews\n ? everyLabel(session.plan.period_hours, m)\n : null\n return every ? m.t(\"checkout.renews\", { period: every }) : undefined\n}\n\nfunction lineItems(\n session: CheckoutSession,\n m: Translator\n): CheckoutLineItem[] {\n if (session.line_items && session.line_items.length > 0) {\n return session.line_items\n }\n return [\n {\n label: session.plan.display_name,\n sublabel: renewsLabel(session, m),\n amount: session.plan.unit_amount,\n },\n ]\n}\n\n// dueToday is the host's figure when it sends one; otherwise the exact sum of\n// the line items and tax. An int64 overflow (null) is refused by the\n// formatter, never rounded.\nfunction dueToday(session: CheckoutSession, m: Translator): Amount | null {\n if (session.due_today !== undefined) return session.due_today\n return addAmounts(\n ...lineItems(session, m).map((item) => item.amount),\n session.tax ?? \"0\"\n )\n}\n\nexport function Eyebrow({\n children,\n className,\n}: {\n children: React.ReactNode\n className?: string\n}) {\n return (\n <div\n className={cn(\n \"text-[11px] font-semibold tracking-[0.09em] text-muted-foreground uppercase\",\n className\n )}\n >\n {children}\n </div>\n )\n}\n\nfunction Row({\n label,\n sublabel,\n amount,\n quiet,\n}: {\n label: string\n sublabel?: string\n amount: string\n quiet?: boolean\n}) {\n return (\n <div\n className={cn(\n \"flex items-start justify-between gap-4 border-b border-[color:var(--orck-hairline)] py-[11px] text-[13.5px]\",\n quiet && \"text-muted-foreground\"\n )}\n >\n <span>\n {label}\n {sublabel ? (\n <span className=\"block text-xs text-muted-foreground\">\n {sublabel}\n </span>\n ) : null}\n </span>\n <span className=\"whitespace-nowrap tabular-nums\">{amount}</span>\n </div>\n )\n}\n\nexport function OrderSummary({ session }: { session: CheckoutSession }) {\n const m = useMessages()\n const { currency, unit_decimals: decimals } = session.plan\n const money = (amount: Amount | null) =>\n formatAmount(amount, currency, decimals)\n return (\n <div className=\"grid content-start gap-5\">\n <Eyebrow>{session.merchant.display_name}</Eyebrow>\n <div className=\"text-[38px] leading-[1.05] font-semibold tracking-[-0.02em] tabular-nums\">\n {money(session.plan.unit_amount)}\n <span className=\"ml-1 text-[15px] font-normal tracking-normal text-muted-foreground\">\n {perLabel(session.plan.period_hours, m)}\n </span>\n </div>\n <div className=\"grid\">\n {lineItems(session, m).map((item) => (\n <Row\n key={item.label}\n label={item.label}\n sublabel={item.sublabel}\n amount={money(item.amount)}\n />\n ))}\n {session.tax !== undefined ? (\n <Row label=\"Tax\" amount={money(session.tax)} quiet />\n ) : null}\n <div className=\"-mt-px flex items-start justify-between gap-4 border-t border-border pt-[13px] text-[13.5px] font-semibold\">\n <span>Due today</span>\n <span className=\"whitespace-nowrap tabular-nums\">\n {money(dueToday(session, m))}\n </span>\n </div>\n </div>\n </div>\n )\n}\n\nexport function CompactSummary({\n session,\n className,\n}: {\n session: CheckoutSession\n className?: string\n}) {\n const m = useMessages()\n const renews = renewsLabel(session, m)\n const per = perLabel(session.plan.period_hours, m)\n return (\n <div\n className={cn(\n \"flex items-baseline justify-between gap-3 border-b border-[color:var(--orck-hairline)] pb-3.5\",\n className\n )}\n >\n <div className=\"grid gap-0.5\">\n <Eyebrow>{session.merchant.display_name}</Eyebrow>\n <div className=\"text-[12.5px] text-muted-foreground\">\n {session.plan.display_name}\n {renews ? ` · ${renews}` : \"\"}\n </div>\n </div>\n <div className=\"text-[22px] font-semibold tracking-[-0.01em] whitespace-nowrap tabular-nums\">\n {formatAmount(\n session.plan.unit_amount,\n session.plan.currency,\n session.plan.unit_decimals\n )}\n {per ? (\n <span className=\"text-xs font-normal text-muted-foreground\">\n {\" \"}\n {per.replace(\"/ \", \"/\")}\n </span>\n ) : null}\n </div>\n </div>\n )\n}\n","// Terminal and transitional views. Each is quiet: one fact, one instruction,\n// no dead controls.\nimport { Skeleton } from \"#orck/components/ui/skeleton\"\nimport { Eyebrow } from \"#orck/components/summary\"\n\nexport function LoadingSkeleton() {\n return (\n <div className=\"grid gap-4\" aria-hidden>\n <Skeleton className=\"h-3 w-24\" />\n <Skeleton className=\"h-6 w-52\" />\n <Skeleton className=\"mt-1.5 h-11 w-full\" />\n <Skeleton className=\"h-28 w-full\" />\n <Skeleton className=\"h-11 w-full\" />\n <Skeleton className=\"mt-1 h-[42px] w-full\" />\n </div>\n )\n}\n\nexport function SucceededView({\n merchantName,\n embedded,\n}: {\n merchantName: string\n embedded: boolean\n}) {\n return (\n <div className=\"grid gap-4\">\n <Eyebrow>{merchantName}</Eyebrow>\n <div className=\"grid justify-items-center gap-2.5 px-2 py-7 text-center\">\n <div className=\"grid size-11 place-items-center rounded-full bg-[color:var(--orck-success)]/12 text-[color:var(--orck-success)]\">\n <svg\n width=\"20\"\n height=\"20\"\n viewBox=\"0 0 20 20\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2.2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden\n >\n <path d=\"M4 10.5l4 4 8-9\" />\n </svg>\n </div>\n <div className=\"text-[15px] font-semibold\">Payment complete</div>\n <div className=\"text-[13px] text-muted-foreground\">\n {embedded ? \"You're all set.\" : `Returning to ${merchantName}…`}\n </div>\n </div>\n </div>\n )\n}\n\nexport function TerminalView({\n merchantName,\n headline,\n sub,\n}: {\n merchantName: string\n headline: string\n sub?: string\n}) {\n return (\n <div className=\"grid gap-4\">\n <Eyebrow>{merchantName}</Eyebrow>\n <div className=\"grid justify-items-center gap-2 px-2 py-7 text-center\">\n <div className=\"text-[15px] font-semibold\">{headline}</div>\n {sub ? (\n <div className=\"text-[13px] text-muted-foreground\">{sub}</div>\n ) : null}\n </div>\n </div>\n )\n}\n","/** The https URL a redirect rail may navigate to, or null. */\nexport function safeRedirectURL(raw: string): string | null {\n try {\n const url = new URL(raw)\n if (url.protocol !== \"https:\" || url.username || url.password) return null\n return url.href\n } catch {\n return null\n }\n}\n","// Checkout — the entire flow as one self-contained component. Hosts render\n// it inline on any page; CheckoutModal wraps it in a dialog; the hosted page\n// is another thin host. Its only inputs are a CheckoutSource (data), an\n// appearance (theming), and lifecycle callbacks. The container query is the\n// mode switch: wide containers get the split layout, narrow ones the compact\n// stack.\n//\n// Cards are one panel: the saved cards for the checkout PSP, an inline new\n// card, and one button that is the payer's explicit confirmation of the\n// displayed terms. With a BillingProvider, a new card is saved to the\n// customer's account first and the payment charges it by id; a decline keeps\n// the buyer on the panel to pick another card and retry. A rail whose driver\n// is card takes the card in plain inputs and posts it to OpenRails: no\n// gateway script is loaded.\nimport * as React from \"react\"\n\nimport {\n appearanceStyle,\n appearanceTheme,\n type CheckoutAppearance,\n} from \"#orck/appearance\"\nimport { authenticatePayment } from \"#orck/authenticate\"\nimport { isBillingError, isServerError } from \"#orck/client/errors\"\nimport type { PaymentMethod } from \"#orck/client/types\"\nimport { CardBillingFields } from \"#orck/components/billing-fields\"\nimport { CardFields, NativeCardFields } from \"#orck/components/card-fields\"\nimport { CCBillFields } from \"#orck/components/ccbill-fields\"\nimport {\n ccbillBillingSchema,\n emptyCCBillBilling,\n type CCBillBilling,\n} from \"#orck/lib/ccbill\"\nimport { MethodBody, MethodList } from \"#orck/components/methods\"\nimport { solanaToken, supportedOptions } from \"#orck/lib/rail-meta\"\nimport { PayButton, TrustLine } from \"#orck/components/pay-button\"\nimport { SolanaBody } from \"#orck/components/qr\"\nimport { NEW_CARD_VALUE, SavedMethods } from \"#orck/components/saved-methods\"\nimport {\n LoadingSkeleton,\n SucceededView,\n TerminalView,\n} from \"#orck/components/states\"\nimport {\n StripeCardEntry,\n type StripeCardHandle,\n} from \"#orck/components/stripe-card\"\nimport { CompactSummary, OrderSummary } from \"#orck/components/summary\"\nimport { useMessages } from \"#orck/i18n/context\"\nimport {\n collectCardDisplay,\n useCollectJS,\n type CollectFieldErrors,\n} from \"#orck/lib/collect\"\nimport {\n emptyNMIBilling,\n initialCountry,\n nmiBillingSchema,\n type NMIBilling,\n} from \"#orck/lib/billing\"\nimport { cardEntryDisplay, useCardEntry } from \"#orck/lib/card-entry\"\nimport { amountToDecimal, formatAmount } from \"#orck/lib/money\"\nimport { safeRedirectURL } from \"#orck/lib/redirect\"\nimport { everyLabel } from \"#orck/lib/period\"\nimport { isCardRail, railPsp } from \"#orck/psp\"\nimport { useOptionalBillingContext } from \"#orck/react/context\"\nimport { cn } from \"cn\"\nimport type { CheckoutSource } from \"#orck/source\"\nimport type {\n CheckoutPhase,\n CheckoutSession,\n PaymentFailure,\n PaymentRailOption,\n PayRequest,\n PayResult,\n SavedPaymentMethod,\n} from \"#orck/types\"\n\n// Layout preference. Responsiveness always wins: the split layout only ever\n// renders when the container is genuinely wide enough for it.\n// - \"auto\": split on comfortably wide containers (≥48rem)\n// - \"wide\": prefer the split — it engages earlier (≥36rem); pairs with the\n// wide CheckoutModal\n// - \"compact\": always the stacked view, no matter how wide the container\nexport type CheckoutLayout = \"auto\" | \"wide\" | \"compact\"\n\nexport interface CheckoutProps {\n source: CheckoutSource\n appearance?: CheckoutAppearance\n layout?: CheckoutLayout\n /** Billing country to preselect; default: the browser locale's region. */\n defaultCountry?: string\n /** Return target after an off-page card verification (Stripe setup). */\n cardSetupReturnURL?: (setupId: string) => string\n // Embedded hosts get the result via callback; page hosts also redirect.\n onComplete?: (result: PayResult) => void\n /**\n * Leaves for a redirect rail's page. Default: navigate the top window,\n * which a nested frame may not do; <CheckoutPage> asks its app instead.\n */\n onRedirect?: (url: string) => void\n onPhaseChange?: (phase: CheckoutPhase) => void\n // Redirect hosts can announce the short return transition after success;\n // embedded/modal hosts stay put and use the settled confirmation copy.\n completionMode?: \"embedded\" | \"redirect\"\n className?: string\n}\n\nconst POLL_INTERVAL_MS = 3_000\nconst DECLINED = \"Your card was declined. Try another card.\"\n// A 5xx is shown at once. Hosts replay a retried payment under the same\n// idempotency identity, so trying again cannot charge twice.\nconst SERVER_FAILED =\n \"Payment service error. The payment was not confirmed. Try again in a moment.\"\nconst STATUS_UNAVAILABLE =\n \"Payment status is unavailable right now (service error). Still checking.\"\n\nfunction navigateTop(redirectURL: string): void {\n const href = safeRedirectURL(redirectURL)\n if (!href)\n throw new Error(\"The payment provider returned an invalid redirect\")\n // Cross-origin frames may navigate their top-level browsing context, but\n // cannot read methods such as Location.assign from the top window.\n const target = window.top ?? window\n target.location.href = href\n}\n\nfunction solanaAmountLabel(\n session: CheckoutSession,\n tokenSymbol: string,\n transactionURL?: string\n): string {\n if (transactionURL) {\n try {\n const amount = new URL(transactionURL).searchParams.get(\"amount\")\n if (amount && /^\\d+(?:\\.\\d+)?$/.test(amount))\n return `${amount} ${tokenSymbol}`.trim()\n } catch {\n // The wire schema already requires solana:, so retain the plan fallback.\n }\n }\n const { unit_amount, unit_decimals } = session.plan\n return `${amountToDecimal(unit_amount, unit_decimals) ?? unit_amount} ${tokenSymbol}`.trim()\n}\n\nfunction savedFrom(\n method: PaymentMethod,\n rail: PaymentRailOption\n): SavedPaymentMethod {\n return {\n id: method.id,\n option_id: rail.id,\n rail: rail.rail,\n brand: method.card?.brand ?? undefined,\n last_four: method.card?.last4 ?? undefined,\n exp_month: method.card?.exp_month ?? undefined,\n exp_year: method.card?.exp_year ?? undefined,\n }\n}\n\n// Provider SDK errors carry customer-facing text (\"Your card was declined.\").\nfunction describe(cause: unknown, fallback: string): string {\n if (isBillingError(cause)) return cause.message || fallback\n return cause instanceof Error && cause.message ? cause.message : fallback\n}\n\nconst awaitingPayment = (session: CheckoutSession | null) =>\n session?.status === \"processing\" ||\n (session?.status === \"requires_action\" && !!session.operation)\n\nexport function Checkout({\n source,\n appearance,\n layout = \"auto\",\n defaultCountry,\n cardSetupReturnURL,\n onComplete,\n onRedirect,\n onPhaseChange,\n completionMode = \"embedded\",\n className,\n}: CheckoutProps) {\n const m = useMessages()\n const billingContext = useOptionalBillingContext()\n const client = billingContext?.client\n const uid = React.useId().replace(/[^a-zA-Z0-9-]/g, \"\")\n const [phase, setPhase] = React.useState<CheckoutPhase>(\"loading\")\n const [session, setSession] = React.useState<CheckoutSession | null>(null)\n const [selected, setSelected] = React.useState<string>(\"\")\n const [payError, setPayError] = React.useState<string>()\n const [failure, setFailure] = React.useState<PaymentFailure>()\n const [billing, setBilling] =\n React.useState<CCBillBilling>(emptyCCBillBilling)\n const [cardBilling, setCardBilling] = React.useState<NMIBilling>(() => ({\n ...emptyNMIBilling,\n country: initialCountry(defaultCountry),\n }))\n const [solanaURL, setSolanaURL] = React.useState<string>()\n // Cards saved during this checkout, most recent first.\n const [addedCards, setAddedCards] = React.useState<SavedPaymentMethod[]>([])\n const [stripeComplete, setStripeComplete] = React.useState(false)\n const [stripeKey, setStripeKey] = React.useState(0)\n const [authenticating, setAuthenticating] = React.useState(false)\n const stripeCard = React.useRef<StripeCardHandle>(null)\n // Set once this component submitted a payment: a later definite decline\n // returns to the panel instead of a terminal page.\n const attempted = React.useRef(false)\n const mounted = React.useRef(true)\n const sourceRef = React.useRef(source)\n React.useEffect(() => {\n sourceRef.current = source\n }, [source])\n const phaseRef = React.useRef(phase)\n const solanaStartedFor = React.useRef<string | undefined>(undefined)\n\n // onPhaseChange rides a ref so changePhase stays referentially stable —\n // hosts pass inline callbacks (CheckoutModal does), and a changing identity\n // here would re-fire the load effect on every render.\n const onPhaseChangeRef = React.useRef(onPhaseChange)\n React.useEffect(() => {\n onPhaseChangeRef.current = onPhaseChange\n })\n const onCompleteRef = React.useRef(onComplete)\n React.useEffect(() => {\n onCompleteRef.current = onComplete\n })\n const onRedirectRef = React.useRef(onRedirect)\n React.useEffect(() => {\n onRedirectRef.current = onRedirect\n })\n const changePhase = React.useCallback((next: CheckoutPhase) => {\n phaseRef.current = next\n setPhase(next)\n onPhaseChangeRef.current?.(next)\n }, [])\n\n React.useEffect(() => {\n mounted.current = true\n return () => {\n mounted.current = false\n }\n }, [])\n\n // Card rails that save a card in the page need the customer's billing\n // client; without one (a hosted page) only token rails are offered.\n const usable = React.useCallback(\n (rails: PaymentRailOption[]) =>\n supportedOptions(rails).filter(\n (option) => option.driver !== \"stripe_elements\" || !!client\n ),\n [client]\n )\n\n // Load the session once per source; map its status straight to a phase.\n React.useEffect(() => {\n let cancelled = false\n solanaStartedFor.current = undefined\n attempted.current = false\n // eslint-disable-next-line react-hooks/set-state-in-effect -- deliberate: a new source restarts the flow from loading\n changePhase(\"loading\")\n setSolanaURL(undefined)\n source\n .getSession()\n .then((loaded) => {\n if (cancelled || !mounted.current) return\n setSession(loaded)\n setSolanaURL(loaded.transaction_url)\n const options = usable(loaded.rails)\n if (loaded.status === \"succeeded\") {\n changePhase(\"succeeded\")\n onCompleteRef.current?.({\n status: \"succeeded\",\n payment_id: loaded.payment_id,\n subscription_id: loaded.subscription_id,\n })\n return\n }\n if (loaded.status === \"expired\" || loaded.status === \"canceled\") {\n changePhase(\"expired\")\n return\n }\n if (loaded.status === \"failed\") {\n changePhase(\"failed\")\n return\n }\n if (loaded.status === \"blocked\") {\n changePhase(\"blocked\")\n return\n }\n if (awaitingPayment(loaded)) {\n const card = options.find(isCardRail)\n if (card) setSelected(card.id)\n changePhase(\"processing\")\n return\n }\n if (options.length === 0) {\n changePhase(\"unavailable\")\n return\n }\n setSelected((current) =>\n options.some((option) => option.id === current)\n ? current\n : options[0].id\n )\n changePhase(\"ready\")\n })\n .catch(() => {\n if (!cancelled && mounted.current) changePhase(\"error\")\n })\n return () => {\n cancelled = true\n }\n }, [source, changePhase, usable])\n\n // Expiry is enforced client-side too, so the page never invites a payment\n // the backend will refuse.\n React.useEffect(() => {\n if (!session?.expires_at) return\n const expiresAt = session.expires_at\n const remaining = Date.parse(expiresAt) - Date.now()\n if (Number.isNaN(remaining)) return\n // setTimeout overflows past 2^31-1ms and fires immediately, so clamp and\n // re-check the wall clock on fire instead of trusting the timer.\n const delay = Math.min(Math.max(0, remaining), 2 ** 31 - 1)\n const timer = window.setTimeout(() => {\n if (phaseRef.current !== \"ready\") return\n if (Date.parse(expiresAt) - Date.now() <= 0) {\n changePhase(\"expired\")\n }\n }, delay)\n return () => window.clearTimeout(timer)\n }, [session, changePhase])\n\n const options = React.useMemo(\n () => (session ? usable(session.rails) : []),\n [session, usable]\n )\n const active = options.find((option) => option.id === selected)\n const nmiOption = options.find((option) => option.driver === \"collect_js\")\n const savedMethods = React.useMemo(() => {\n if (!active || !isCardRail(active)) return []\n const seen = new Set<string>()\n return [...addedCards, ...(session?.saved_methods ?? [])].filter(\n (method) => {\n if (method.option_id !== active.id || seen.has(method.id)) return false\n seen.add(method.id)\n return true\n }\n )\n }, [active, addedCards, session])\n // Until the customer chooses, the default card (else the most recent)\n // stands pre-selected. Paying always sends the selected card's id; nothing\n // is implied server-side. Derived so it applies when the session arrives\n // after first render.\n const [savedChoice, setSavedChoice] = React.useState<string>()\n const savedMethodID =\n savedChoice &&\n (savedChoice === NEW_CARD_VALUE ||\n savedMethods.some((method) => method.id === savedChoice))\n ? savedChoice\n : ((savedMethods.find((method) => method.default) ?? savedMethods[0])\n ?.id ?? NEW_CARD_VALUE)\n const usingSavedMethod =\n savedMethodID !== NEW_CARD_VALUE &&\n savedMethods.some((method) => method.id === savedMethodID)\n const cardIds = React.useMemo(\n () => ({\n number: `orck-${uid}-cc-number`,\n expiry: `orck-${uid}-cc-expiry`,\n cvv: `orck-${uid}-cc-cvv`,\n }),\n [uid]\n )\n // Native card entry for a PSP that takes cards on OpenRails (driver card).\n const nativeCard = useCardEntry()\n const nativeCardRef = React.useRef(nativeCard)\n React.useEffect(() => {\n nativeCardRef.current = nativeCard\n })\n const nativeIds = React.useMemo(\n () => ({\n number: `orck-${uid}-card-number`,\n expiry: `orck-${uid}-card-expiry`,\n cvv: `orck-${uid}-card-cvc`,\n }),\n [uid]\n )\n const collect = useCollectJS({\n enabled:\n Boolean(nmiOption) &&\n (phase === \"ready\" ||\n (phase === \"processing\" && !awaitingPayment(session))),\n active: selected === nmiOption?.id,\n tokenizationKey: nmiOption?.public_config?.tokenization_key ?? \"\",\n scriptURL: nmiOption?.public_config?.tokenization_url ?? \"\",\n selectors: {\n number: `#${cardIds.number}`,\n expiry: `#${cardIds.expiry}`,\n cvv: `#${cardIds.cvv}`,\n },\n })\n\n const clearFailure = () => {\n setPayError(undefined)\n setFailure(undefined)\n }\n\n const showFailure = React.useCallback(\n (result: { failure?: PaymentFailure | null; failure_message?: string }) => {\n const next = result.failure ?? undefined\n setFailure(next)\n setPayError(next?.message || result.failure_message || DECLINED)\n },\n []\n )\n\n // Saves a newly entered card to the customer's account and selects it, so\n // a retry after a decline never enters or saves the card again.\n const saveNewCard = React.useCallback(\n async (rail: PaymentRailOption): Promise<PayRequest | null> => {\n if (rail.driver === \"stripe_elements\") {\n if (!client || !stripeCard.current) return null\n const id = await stripeCard.current.save()\n let saved: SavedPaymentMethod = {\n id,\n option_id: rail.id,\n rail: rail.rail,\n }\n try {\n const page = await client.listPaymentMethods({ limit: 100 })\n const method = page.data.find((item) => item.id === id)\n if (method) saved = savedFrom(method, rail)\n } catch {\n // The card is saved; its label arrives with the next session read.\n }\n billingContext?.notify({\n type: \"payment_method.added\",\n paymentMethodId: id,\n })\n setAddedCards((current) => [saved, ...current])\n setSavedChoice(id)\n setStripeKey((key) => key + 1)\n return { option_id: rail.id, payment_method_id: id }\n }\n const parsed = nmiBillingSchema.safeParse(cardBilling)\n if (!parsed.success) {\n setPayError(\n parsed.error.issues[0]?.message ?? \"Check the billing details\"\n )\n return null\n }\n if (rail.driver === \"card\") {\n // The card leaves the form here and goes to OpenRails only.\n const card = nativeCardRef.current.take()\n if (!card) return null\n if (!client) return { option_id: rail.id, card, ...parsed.data }\n const display = cardEntryDisplay(card)\n const method = await client.addPaymentMethod({\n provider: rail.psp_key ?? rail.rail,\n card,\n ...parsed.data,\n })\n billingContext?.notify({\n type: \"payment_method.added\",\n paymentMethodId: method.id,\n })\n const saved = savedFrom(method, rail)\n setAddedCards((current) => [\n {\n ...saved,\n brand: saved.brand ?? display.card_type,\n last_four: saved.last_four ?? display.last_four,\n },\n ...current,\n ])\n setSavedChoice(method.id)\n return { option_id: rail.id, payment_method_id: method.id }\n }\n const tokenized = await collect.tokenize()\n const display = collectCardDisplay(tokenized.card)\n if (!client) {\n return {\n option_id: rail.id,\n payment_token: tokenized.token,\n ...parsed.data,\n ...display,\n }\n }\n const method = await client.addPaymentMethod({\n provider: rail.psp_key ?? rail.rail,\n payment_token: tokenized.token,\n ...parsed.data,\n ...display,\n })\n billingContext?.notify({\n type: \"payment_method.added\",\n paymentMethodId: method.id,\n })\n const saved = savedFrom(method, rail)\n setAddedCards((current) => [\n {\n ...saved,\n brand: saved.brand ?? display.card_type,\n last_four: saved.last_four ?? display.last_four,\n },\n ...current,\n ])\n setSavedChoice(method.id)\n return { option_id: rail.id, payment_method_id: method.id }\n },\n [billingContext, cardBilling, client, collect]\n )\n\n const authenticate = React.useCallback(\n async (operationID: string) => {\n if (!client || !active) return\n setAuthenticating(true)\n setPayError(undefined)\n try {\n await authenticatePayment(client, operationID, railPsp(active))\n } catch (cause) {\n if (mounted.current)\n setPayError(describe(cause, \"Card authentication was not completed.\"))\n } finally {\n if (mounted.current) setAuthenticating(false)\n }\n },\n [active, client]\n )\n\n const pay = React.useCallback(async () => {\n if (!session || !active || phase !== \"ready\") return\n clearFailure()\n changePhase(\"processing\")\n let submitted = false\n try {\n let request: PayRequest = { option_id: active.id }\n if (active.driver === \"redirect\" && active.rail === \"ccbill\") {\n const parsed = ccbillBillingSchema.safeParse(billing)\n if (!parsed.success) {\n setPayError(\n parsed.error.issues[0]?.message ?? \"Check the billing details\"\n )\n changePhase(\"ready\")\n return\n }\n request = { option_id: active.id, ...parsed.data }\n }\n if (isCardRail(active) && usingSavedMethod) {\n request = { option_id: active.id, payment_method_id: savedMethodID }\n } else if (isCardRail(active)) {\n let saved: PayRequest | null\n try {\n saved = await saveNewCard(active)\n } catch (cause) {\n if (!mounted.current || sourceRef.current !== source) return\n setPayError(describe(cause, \"Card entry could not be completed.\"))\n changePhase(\"ready\")\n return\n }\n if (!mounted.current || sourceRef.current !== source) return\n if (!saved) {\n changePhase(\"ready\")\n return\n }\n request = saved\n }\n if (active.driver === \"solana_pay\") {\n // supportedOptions only offers Solana options with a bound token, so\n // the symbol the host bound is the one we pay with — never a default.\n request = {\n option_id: active.id,\n token_symbol: solanaToken(active)?.symbol,\n }\n }\n submitted = true\n attempted.current = true\n const result = await source.pay(request)\n if (!mounted.current || sourceRef.current !== source) return\n if (active.driver === \"redirect\" && result.redirect_url) {\n onCompleteRef.current?.(result)\n if (onRedirectRef.current) onRedirectRef.current(result.redirect_url)\n else navigateTop(result.redirect_url)\n return\n }\n if (\n active.driver === \"solana_pay\" &&\n result.status === \"requires_action\" &&\n result.transaction_url\n ) {\n setSession((current) =>\n current\n ? {\n ...current,\n status: \"requires_action\",\n transaction_url: result.transaction_url,\n }\n : current\n )\n setSolanaURL(result.transaction_url)\n changePhase(\"ready\")\n return\n }\n if (result.status === \"succeeded\") {\n changePhase(\"succeeded\")\n onCompleteRef.current?.(result)\n return\n }\n if (result.status === \"failed\") {\n showFailure(result)\n changePhase(\"ready\")\n return\n }\n if (result.status === \"blocked\") {\n setSession((current) =>\n current\n ? {\n ...current,\n status: \"blocked\",\n failure_message: result.failure_message,\n }\n : current\n )\n changePhase(\"blocked\")\n return\n }\n if (result.status === \"expired\" || result.status === \"canceled\") {\n setSession((current) =>\n current ? { ...current, status: result.status } : current\n )\n changePhase(\"expired\")\n return\n }\n if (result.status === \"requires_action\" && result.operation_id) {\n const operation = { id: result.operation_id, status: \"pending\" }\n setSession((current) =>\n current\n ? { ...current, status: \"requires_action\", operation }\n : current\n )\n changePhase(\"processing\")\n await authenticate(result.operation_id)\n return\n }\n setSession((current) =>\n current ? { ...current, status: \"processing\" } : current\n )\n changePhase(\"processing\")\n } catch (err) {\n if (!mounted.current || sourceRef.current !== source) return\n if (submitted && isServerError(err)) {\n setPayError(SERVER_FAILED)\n changePhase(\"ready\")\n } else if (submitted) {\n setPayError(\n \"The payment result is not confirmed yet. Keep this window open while we check its status.\"\n )\n setSession((current) =>\n current ? { ...current, status: \"processing\" } : current\n )\n changePhase(\"processing\")\n } else {\n setPayError(describe(err, \"Card entry could not be completed.\"))\n changePhase(\"ready\")\n }\n }\n }, [\n active,\n authenticate,\n billing,\n changePhase,\n phase,\n saveNewCard,\n savedMethodID,\n session,\n showFailure,\n source,\n usingSavedMethod,\n ])\n\n // Solana has no submit button: selecting it creates one transfer request,\n // then the QR remains stable while the server watches its unique reference.\n React.useEffect(() => {\n if (\n !session ||\n active?.driver !== \"solana_pay\" ||\n phase !== \"ready\" ||\n solanaURL ||\n solanaStartedFor.current === session.id\n ) {\n return\n }\n solanaStartedFor.current = session.id\n void pay()\n }, [active?.driver, pay, phase, session, solanaURL])\n\n React.useEffect(() => {\n if (\n !session ||\n (!(phase === \"processing\" && awaitingPayment(session)) &&\n !(active?.driver === \"solana_pay\" && phase === \"ready\" && solanaURL))\n )\n return\n\n let cancelled = false\n let timer: number | undefined\n const schedule = () => {\n timer = window.setTimeout(() => void poll(), POLL_INTERVAL_MS)\n }\n const poll = async () => {\n try {\n const loaded = await source.getSession()\n if (cancelled || !mounted.current) return\n switch (loaded.status) {\n case \"succeeded\":\n setSession(loaded)\n changePhase(\"succeeded\")\n onCompleteRef.current?.({\n status: \"succeeded\",\n payment_id: loaded.payment_id,\n subscription_id: loaded.subscription_id,\n })\n return\n case \"failed\":\n if (attempted.current) {\n // A definite decline of this panel's attempt: back to the\n // cards, with the reason, for another card and a new attempt.\n setSession({ ...loaded, status: \"created\", operation: null })\n showFailure(loaded)\n changePhase(\"ready\")\n return\n }\n setSession(loaded)\n changePhase(\"failed\")\n return\n case \"blocked\":\n setSession(loaded)\n changePhase(\"blocked\")\n return\n case \"expired\":\n case \"canceled\":\n setSession(loaded)\n changePhase(\"expired\")\n return\n case \"requires_action\":\n if (loaded.operation) {\n setSession(loaded)\n schedule()\n return\n }\n schedule()\n return\n default:\n // Ready-looking reads can race an accepted write. Keep the local\n // pending presentation and poll; never re-enable card entry.\n schedule()\n }\n } catch (err) {\n if (cancelled || !mounted.current) return\n if (isServerError(err)) setPayError(STATUS_UNAVAILABLE)\n schedule()\n }\n }\n\n schedule()\n return () => {\n cancelled = true\n if (timer !== undefined) window.clearTimeout(timer)\n }\n }, [\n active?.driver,\n changePhase,\n phase,\n session,\n showFailure,\n solanaURL,\n source,\n ])\n\n const merchantName = session?.merchant.display_name ?? \"\"\n const solanaTokenSymbol =\n active?.rail === \"solana\" ? (solanaToken(active)?.symbol ?? \"\") : \"\"\n const processing = phase === \"processing\"\n const amount = session\n ? formatAmount(\n session.plan.unit_amount,\n session.plan.currency,\n session.plan.unit_decimals\n )\n : \"\"\n const renews = session?.plan.automatically_renews\n ? everyLabel(session.plan.period_hours, m)\n : null\n const payLabel =\n active && session\n ? active.driver === \"redirect\"\n ? `Continue to ${active.rail === \"stripe\" ? \"Stripe\" : \"CCBill\"}`\n : renews\n ? `Subscribe for ${amount} ${renews}`\n : `Pay ${amount}`\n : \"\"\n\n // A decline about a specific field is shown next to it while the new card\n // entry is open; otherwise under the card choice.\n const newCardOpen = !!active && isCardRail(active) && !usingSavedMethod\n const collectErrors: CollectFieldErrors = { ...collect.fieldErrors }\n let postalError: string | undefined\n let inlineFailure = false\n if (\n failure?.field &&\n newCardOpen &&\n (active?.driver === \"collect_js\" || active?.driver === \"card\")\n ) {\n inlineFailure = true\n if (failure.field === \"number\") collectErrors.number = failure.message\n else if (failure.field === \"expiry\") collectErrors.expiry = failure.message\n else if (failure.field === \"cvc\") collectErrors.cvv = failure.message\n else if (failure.field === \"postal_code\") postalError = failure.message\n else inlineFailure = false\n }\n\n // Card errors sit with the cards; other rails keep the form-level line.\n const cardError =\n payError && active && isCardRail(active) && !inlineFailure\n ? payError\n : undefined\n const cardBody = (option: PaymentRailOption, isActive: boolean) => {\n const stripe = option.driver === \"stripe_elements\"\n const native = option.driver === \"card\"\n const entryOpen = isActive && !usingSavedMethod\n return (\n <MethodBody hidden={!isActive}>\n {savedMethods.length > 0 ? (\n <SavedMethods\n methods={savedMethods}\n value={savedMethodID}\n onChange={(next) => {\n setSavedChoice(next)\n clearFailure()\n }}\n disabled={processing}\n idPrefix={`orck-${uid}-saved`}\n />\n ) : null}\n {stripe ? (\n entryOpen && client ? (\n <StripeCardEntry\n key={stripeKey}\n ref={stripeCard}\n psp={railPsp(option)}\n client={client}\n returnURL={cardSetupReturnURL}\n defaultCountry={cardBilling.country || undefined}\n onCompleteChange={setStripeComplete}\n unavailableMessage={m.t(\"paymentMethods.unavailable\")}\n verificationPendingMessage={m.t(\n \"paymentMethods.verificationPending\"\n )}\n />\n ) : null\n ) : (\n // Card fields stay mounted once created so the Collect.js iframes\n // survive rail and card switches; hidden handles visibility.\n <div\n className={cn(\"grid gap-3\", usingSavedMethod && \"hidden\")}\n aria-hidden={usingSavedMethod || undefined}\n >\n <CardBillingFields\n idPrefix={`orck-${uid}-card`}\n value={cardBilling}\n onChange={(next) => {\n setCardBilling(next)\n clearFailure()\n }}\n disabled={processing || !isActive || usingSavedMethod}\n postalError={isActive ? postalError : undefined}\n />\n {native ? (\n <NativeCardFields\n ids={nativeIds}\n card={nativeCard}\n fieldErrors={isActive ? collectErrors : undefined}\n disabled={processing || !isActive || usingSavedMethod}\n />\n ) : (\n <CardFields\n ids={cardIds}\n preview={collect.preview}\n error={isActive ? collect.loadError : undefined}\n fieldErrors={isActive ? collectErrors : undefined}\n />\n )}\n </div>\n )}\n {isActive && cardError ? (\n <p className=\"text-[13px] text-destructive\" role=\"alert\">\n {cardError}\n </p>\n ) : null}\n {newCardOpen && isActive && client ? (\n <p className=\"text-xs text-muted-foreground\">\n {m.t(\"paymentMethods.saveNotice\")}\n </p>\n ) : null}\n </MethodBody>\n )\n }\n\n const paymentColumn = session ? (\n <form\n id={`orck-${uid}-payment-form`}\n name=\"openrails-checkout\"\n aria-label=\"Secure payment\"\n autoComplete=\"on\"\n noValidate\n className=\"grid content-start gap-4\"\n onSubmit={(event) => {\n event.preventDefault()\n void pay()\n }}\n >\n <CompactSummary\n session={session}\n className={cn(\n layout === \"auto\" && \"@3xl/orck:hidden\",\n layout === \"wide\" && \"@xl/orck:hidden\"\n )}\n />\n <MethodList\n rails={options}\n selected={selected}\n onSelect={(optionID) => {\n const next = options.find((option) => option.id === optionID)\n if (next?.driver === \"solana_pay\" && !solanaURL) {\n // A failed request may be retried by returning to Solana.\n solanaStartedFor.current = undefined\n }\n setSelected(optionID)\n clearFailure()\n }}\n disabled={processing}\n idPrefix={`orck-${uid}`}\n renderBody={(option, isActive) => {\n if (isCardRail(option)) return cardBody(option, isActive)\n if (!isActive) return null\n if (option.driver === \"solana_pay\") {\n return (\n <MethodBody>\n <SolanaBody\n amountLabel={solanaAmountLabel(\n session,\n solanaTokenSymbol,\n solanaURL\n )}\n payload={solanaURL}\n statusLine={\n solanaURL\n ? \"Watching for payment…\"\n : payError\n ? \"Payment request unavailable\"\n : \"Preparing payment…\"\n }\n />\n </MethodBody>\n )\n }\n if (option.driver === \"redirect\" && option.rail === \"ccbill\") {\n return (\n <MethodBody>\n <CCBillFields\n idPrefix={`orck-${uid}-ccbill`}\n value={billing}\n onChange={(next) => {\n setBilling(next)\n setPayError(undefined)\n }}\n disabled={processing}\n error={payError}\n />\n <p className=\"text-[13px] text-muted-foreground\">\n You’ll finish payment on CCBill’s secure page.\n </p>\n </MethodBody>\n )\n }\n return (\n <MethodBody>\n <p className=\"text-[13px] text-muted-foreground\">\n You’ll finish payment on Stripe’s secure page.\n </p>\n </MethodBody>\n )\n }}\n />\n {payError && active && active.rail !== \"ccbill\" && !isCardRail(active) ? (\n <p className=\"text-[13px] text-destructive\" role=\"alert\">\n {payError}\n </p>\n ) : null}\n {active && (active.driver !== \"solana_pay\" || Boolean(payError)) ? (\n <PayButton\n label={active.driver === \"solana_pay\" ? \"Try again\" : payLabel}\n processing={processing}\n disabled={\n isCardRail(active) &&\n !usingSavedMethod &&\n (active.driver === \"collect_js\"\n ? !collect.ready || !collect.valid || Boolean(collect.loadError)\n : active.driver === \"card\"\n ? !nativeCard.valid\n : !stripeComplete)\n }\n />\n ) : null}\n {renews && active && isCardRail(active) ? (\n <p className=\"-mt-1 text-center text-xs text-muted-foreground\">\n {`You agree to pay ${amount} ${renews} until you cancel. First charge today; cancel anytime.`}\n </p>\n ) : null}\n <TrustLine />\n </form>\n ) : null\n\n const pendingOperation =\n session?.status === \"requires_action\" ? session.operation : null\n\n return (\n <div\n className={cn(\"orck w-full text-sm leading-normal\", className)}\n data-orck-theme={appearanceTheme(appearance)}\n style={appearanceStyle(appearance)}\n >\n <span aria-live=\"polite\" className=\"sr-only\">\n {phase === \"loading\"\n ? \"Loading checkout\"\n : phase === \"processing\"\n ? \"Processing payment\"\n : phase === \"succeeded\"\n ? \"Payment complete\"\n : \"\"}\n </span>\n {phase === \"loading\" ? (\n <LoadingSkeleton />\n ) : phase === \"error\" ? (\n <TerminalView\n merchantName={merchantName || \"Checkout\"}\n headline=\"Checkout couldn’t load\"\n sub=\"Reload the page to try again.\"\n />\n ) : phase === \"expired\" ? (\n <TerminalView\n merchantName={merchantName}\n headline=\"This checkout link has expired\"\n sub={merchantName ? `Ask ${merchantName} for a new link.` : undefined}\n />\n ) : phase === \"failed\" ? (\n <TerminalView\n merchantName={merchantName}\n headline=\"Payment failed\"\n sub=\"No payment was completed. Start a new checkout to try again.\"\n />\n ) : phase === \"blocked\" ? (\n <TerminalView\n merchantName={merchantName}\n headline=\"This purchase isn’t available\"\n sub={session?.failure_message}\n />\n ) : phase === \"unavailable\" ? (\n <TerminalView\n merchantName={merchantName}\n headline=\"Checkout isn’t available right now\"\n />\n ) : phase === \"processing\" && awaitingPayment(session) ? (\n <div role=\"status\" className=\"grid gap-3 py-6 text-center\">\n <div className=\"font-semibold\">\n {pendingOperation\n ? \"Confirm with your bank\"\n : \"Confirming payment…\"}\n </div>\n <p className=\"text-muted-foreground\">\n {pendingOperation\n ? \"Your bank needs to confirm this payment.\"\n : \"We’re checking the payment status. Don’t start another payment.\"}\n </p>\n {pendingOperation && client && active && isCardRail(active) ? (\n <button\n type=\"button\"\n className=\"mx-auto h-9 rounded-[9px] bg-primary px-4 text-sm font-semibold text-primary-foreground disabled:opacity-60\"\n disabled={authenticating}\n onClick={() => void authenticate(pendingOperation.id)}\n >\n {authenticating ? \"Waiting for your bank…\" : \"Confirm payment\"}\n </button>\n ) : null}\n {payError ? (\n <p className=\"text-xs text-muted-foreground\">{payError}</p>\n ) : null}\n </div>\n ) : phase === \"succeeded\" ? (\n <SucceededView\n merchantName={merchantName}\n embedded={completionMode === \"embedded\"}\n />\n ) : session ? (\n <div\n className={cn(\n \"grid gap-10\",\n layout === \"auto\" &&\n \"@3xl/orck:grid-cols-[minmax(0,1fr)_minmax(0,1fr)] @3xl/orck:gap-16\",\n layout === \"wide\" &&\n \"@xl/orck:grid-cols-[minmax(0,1fr)_minmax(0,1fr)] @xl/orck:gap-12\"\n )}\n >\n {layout !== \"compact\" ? (\n <div\n className={cn(\n \"hidden\",\n layout === \"auto\" && \"@3xl/orck:block\",\n layout === \"wide\" && \"@xl/orck:block\"\n )}\n >\n <OrderSummary session={session} />\n </div>\n ) : null}\n <div>{paymentColumn}</div>\n </div>\n ) : null}\n </div>\n )\n}\n","// CheckoutModal — a host, not a flow. It supplies the one surface (the\n// Dialog) and renders the same Checkout inside. Closing is always possible:\n// an accepted payment settles on the server whether or not the modal stays\n// open. A successful payment closes on the host's terms via onComplete.\nimport * as React from \"react\"\n\nimport { appearanceStyle, appearanceTheme } from \"#orck/appearance\"\nimport { Checkout, type CheckoutProps } from \"#orck/checkout\"\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogTitle,\n} from \"#orck/components/ui/dialog\"\n\nexport interface CheckoutModalProps extends CheckoutProps {\n open: boolean\n onOpenChange: (open: boolean) => void\n /**\n * Rendered instead of the checkout while set, e.g. the host's sign-in.\n * Clear it to continue to payment in the same modal.\n */\n gate?: React.ReactNode\n}\n\nexport function CheckoutModal({\n open,\n onOpenChange,\n onPhaseChange,\n gate,\n ...checkoutProps\n}: CheckoutModalProps) {\n const compact = checkoutProps.layout === \"compact\"\n return (\n <Dialog open={open} onOpenChange={onOpenChange}>\n <DialogContent\n className={`orck max-h-[calc(100dvh-2rem)] max-w-[calc(100vw-2rem)] gap-0 overflow-hidden bg-background text-foreground ring-0 [&>[data-slot=dialog-close]]:top-5 [&>[data-slot=dialog-close]]:right-5 [&>[data-slot=dialog-close]]:text-foreground ${compact ? \"w-[420px] p-6\" : \"w-[860px] p-8 sm:max-w-[calc(100vw-2rem)]\"}`}\n data-orck-theme={appearanceTheme(checkoutProps.appearance)}\n style={appearanceStyle(checkoutProps.appearance)}\n showCloseButton\n >\n <DialogTitle className=\"sr-only\">Checkout</DialogTitle>\n <DialogDescription className=\"sr-only\">\n Complete your payment\n </DialogDescription>\n <div\n className={`min-h-0 touch-pan-y [scrollbar-width:none] overflow-y-auto overscroll-contain pr-6 [-webkit-overflow-scrolling:touch] [&::-webkit-scrollbar]:hidden ${compact ? \"max-h-[calc(100dvh-5rem)] pt-7\" : \"max-h-[calc(100dvh-6rem)]\"}`}\n >\n {gate ?? (\n <Checkout {...checkoutProps} onPhaseChange={onPhaseChange} />\n )}\n </div>\n </DialogContent>\n </Dialog>\n )\n}\n","// The frame protocol between an app's <CheckoutFrame> and the payment page's\n// <CheckoutPage>. Both sides check the other's window and origin on every\n// message; the page posts only to the origin recorded on its session.\nimport { z } from \"zod\"\n\nimport { checkoutSessionStatusSchema } from \"./types\"\n\nconst SOURCE = \"openrails-checkout\"\n\n/** The page's color scheme, chosen by the framing app. */\nexport type CheckoutFrameTheme = \"light\" | \"dark\" | \"auto\"\n\nconst pageMessageSchema = z.discriminatedUnion(\"type\", [\n z.object({ source: z.literal(SOURCE), type: z.literal(\"ready\") }),\n z.object({\n source: z.literal(SOURCE),\n type: z.literal(\"resize\"),\n height: z.number().finite().nonnegative(),\n }),\n z.object({\n source: z.literal(SOURCE),\n type: z.literal(\"complete\"),\n status: checkoutSessionStatusSchema,\n }),\n z.object({\n source: z.literal(SOURCE),\n type: z.literal(\"redirect\"),\n url: z.string(),\n }),\n])\nexport type PageMessage = z.infer<typeof pageMessageSchema>\n\nconst appMessageSchema = z.object({\n source: z.literal(SOURCE),\n type: z.literal(\"init\"),\n theme: z.enum([\"light\", \"dark\", \"auto\"]),\n})\nexport type AppMessage = z.infer<typeof appMessageSchema>\n\ntype Body<M> = M extends unknown ? Omit<M, \"source\"> : never\n\nexport const pageMessage = (body: Body<PageMessage>): PageMessage =>\n ({ source: SOURCE, ...body }) as PageMessage\n\nexport const appMessage = (body: Body<AppMessage>): AppMessage =>\n ({ source: SOURCE, ...body }) as AppMessage\n\nexport function parsePageMessage(data: unknown): PageMessage | null {\n const parsed = pageMessageSchema.safeParse(data)\n return parsed.success ? parsed.data : null\n}\n\nexport function parseAppMessage(data: unknown): AppMessage | null {\n const parsed = appMessageSchema.safeParse(data)\n return parsed.success ? parsed.data : null\n}\n\n/** The origin of a payment page URL, or null when it is not one. */\nexport function pageOrigin(url: string): string | null {\n try {\n const parsed = new URL(url)\n if (\n (parsed.protocol !== \"https:\" && parsed.protocol !== \"http:\") ||\n parsed.username ||\n parsed.password\n )\n return null\n return parsed.origin\n } catch {\n return null\n }\n}\n","// CheckoutPage — the shared payment page. A host serves it from one HTML entry\n// at Config.HTTP.Checkout.PageURL behind the adapter's CheckoutFramePolicy.\n// The session id arrives in the URL fragment; the page reads and pays the\n// session with it and, when framed by the app that minted it, speaks the\n// frame protocol with that app only.\nimport * as React from \"react\"\n\nimport type { CheckoutAppearance } from \"#orck/appearance\"\nimport { Checkout, type CheckoutLayout } from \"#orck/checkout\"\nimport { createBillingClient, type BillingClient } from \"#orck/client/client\"\nimport { TerminalView } from \"#orck/components/states\"\nimport {\n pageMessage,\n parseAppMessage,\n type CheckoutFrameTheme,\n type PageMessage,\n} from \"#orck/frame\"\nimport { BillingUiRoot } from \"#orck/scope\"\nimport type { CheckoutSource } from \"#orck/source\"\nimport type { PayResult } from \"#orck/types\"\n\nexport interface CheckoutPageProps {\n /** OpenRails mount on this host. Default \"/billing/v1\". */\n baseUrl?: string\n /** Replaces the client built from `baseUrl`. */\n client?: BillingClient\n /** This host's branding; the framing app chooses the theme. */\n appearance?: CheckoutAppearance\n layout?: CheckoutLayout\n defaultCountry?: string\n className?: string\n}\n\nconst sessionIdFromHash = () => window.location.hash.replace(/^#/, \"\").trim()\n\nexport function CheckoutPage({\n baseUrl,\n client,\n appearance,\n layout = \"auto\",\n defaultCountry,\n className,\n}: CheckoutPageProps) {\n const [sessionId, setSessionId] = React.useState(sessionIdFromHash)\n React.useEffect(() => {\n const onHash = () => setSessionId(sessionIdFromHash())\n window.addEventListener(\"hashchange\", onHash)\n return () => window.removeEventListener(\"hashchange\", onHash)\n }, [])\n\n const billing = React.useMemo(\n () => client ?? createBillingClient({ baseUrl }),\n [client, baseUrl]\n )\n const framed = window.parent !== window\n // The app that minted the session, as the server recorded it.\n const [appOrigin, setAppOrigin] = React.useState<string>()\n const [theme, setTheme] = React.useState<CheckoutFrameTheme>()\n\n const source = React.useMemo<CheckoutSource | null>(() => {\n if (!sessionId) return null\n const inner = billing.checkoutSource(sessionId)\n return {\n async getSession() {\n const session = await inner.getSession()\n if (session.embed_origin) setAppOrigin(session.embed_origin)\n return session\n },\n pay: inner.pay,\n }\n }, [billing, sessionId])\n\n const post = React.useCallback(\n (message: PageMessage) => {\n if (framed && appOrigin) window.parent.postMessage(message, appOrigin)\n },\n [framed, appOrigin]\n )\n\n React.useEffect(() => {\n if (!framed || !appOrigin) return\n const onMessage = (event: MessageEvent) => {\n if (event.source !== window.parent || event.origin !== appOrigin) return\n const message = parseAppMessage(event.data)\n if (message) setTheme(message.theme)\n }\n window.addEventListener(\"message\", onMessage)\n window.parent.postMessage(pageMessage({ type: \"ready\" }), appOrigin)\n return () => window.removeEventListener(\"message\", onMessage)\n }, [framed, appOrigin])\n\n const root = React.useRef<HTMLDivElement>(null)\n React.useEffect(() => {\n const element = root.current\n if (!element || !framed || !appOrigin) return\n const report = () =>\n post(\n pageMessage({\n type: \"resize\",\n height: Math.ceil(element.getBoundingClientRect().height),\n })\n )\n const observer = new ResizeObserver(report)\n observer.observe(element)\n report()\n return () => observer.disconnect()\n }, [framed, appOrigin, post])\n\n const onComplete = React.useCallback(\n (result: PayResult) => {\n if (result.status === \"succeeded\")\n post(pageMessage({ type: \"complete\", status: result.status }))\n },\n [post]\n )\n // A nested frame may not navigate the top window: its app does.\n const onRedirect = React.useCallback(\n (url: string) => post(pageMessage({ type: \"redirect\", url })),\n [post]\n )\n\n const pageAppearance: CheckoutAppearance = {\n ...appearance,\n theme: theme ?? appearance?.theme,\n }\n return (\n <div ref={root} className={className}>\n {source ? (\n <Checkout\n source={source}\n appearance={pageAppearance}\n layout={layout}\n defaultCountry={defaultCountry}\n completionMode=\"embedded\"\n onComplete={onComplete}\n onRedirect={framed && appOrigin ? onRedirect : undefined}\n />\n ) : (\n <BillingUiRoot appearance={pageAppearance}>\n <TerminalView\n merchantName=\"\"\n headline=\"This checkout link is incomplete\"\n sub=\"Start checkout again from the site you were buying on.\"\n />\n </BillingUiRoot>\n )}\n </div>\n )\n}\n","// CheckoutFrame — an app's view of the shared payment page. It frames the\n// minted session's url, sizes itself to the page, gives it the app's theme and\n// navigates the app for redirect rails. It exchanges messages with the page's\n// origin only. `onComplete` is a hint: confirm access from your own API.\nimport * as React from \"react\"\n\nimport {\n appMessage,\n pageOrigin,\n parsePageMessage,\n type CheckoutFrameTheme,\n} from \"#orck/frame\"\nimport { safeRedirectURL } from \"#orck/lib/redirect\"\nimport type { CheckoutSessionStatus } from \"#orck/types\"\n\nexport interface CheckoutFrameProps {\n /** The minted session's `url` (createCheckoutSession). */\n url: string\n onComplete?: (status: CheckoutSessionStatus) => void\n /** Default \"auto\": the buyer's system preference. */\n theme?: CheckoutFrameTheme\n /** Accessible name of the frame. */\n title?: string\n /** Height before the page reports its own, in pixels. Default 480. */\n minHeight?: number\n className?: string\n style?: React.CSSProperties\n}\n\nexport function CheckoutFrame({\n url,\n onComplete,\n theme = \"auto\",\n title = \"Secure checkout\",\n minHeight = 480,\n className,\n style,\n}: CheckoutFrameProps) {\n const frame = React.useRef<HTMLIFrameElement>(null)\n const origin = React.useMemo(() => pageOrigin(url), [url])\n const [height, setHeight] = React.useState<number>()\n const ready = React.useRef(false)\n const themeRef = React.useRef(theme)\n const onCompleteRef = React.useRef(onComplete)\n React.useEffect(() => {\n onCompleteRef.current = onComplete\n })\n\n React.useEffect(() => {\n ready.current = false\n if (!origin) return\n const onMessage = (event: MessageEvent) => {\n const page = frame.current?.contentWindow\n if (!page || event.source !== page || event.origin !== origin) return\n const message = parsePageMessage(event.data)\n if (!message) return\n switch (message.type) {\n case \"ready\":\n ready.current = true\n page.postMessage(\n appMessage({ type: \"init\", theme: themeRef.current }),\n origin\n )\n return\n case \"resize\":\n setHeight(Math.ceil(message.height))\n return\n case \"complete\":\n onCompleteRef.current?.(message.status)\n return\n case \"redirect\": {\n const href = safeRedirectURL(message.url)\n if (href) (window.top ?? window).location.href = href\n return\n }\n }\n }\n window.addEventListener(\"message\", onMessage)\n return () => window.removeEventListener(\"message\", onMessage)\n }, [origin, url])\n\n React.useEffect(() => {\n themeRef.current = theme\n const page = frame.current?.contentWindow\n if (ready.current && page && origin)\n page.postMessage(appMessage({ type: \"init\", theme }), origin)\n }, [theme, origin])\n\n if (!origin) return null\n return (\n <iframe\n ref={frame}\n src={url}\n title={title}\n allow=\"payment\"\n className={className}\n style={{\n width: \"100%\",\n border: 0,\n display: \"block\",\n ...style,\n height: Math.max(minHeight, height ?? 0),\n }}\n />\n )\n}\n","// CheckoutSource is the flow's only data dependency: how to read the session\n// and how to pay it. The HTTP source targets the #45 session API with the\n// session id as the sole credential; tests and previews inject fixtures\n// through the same interface.\nimport {\n checkoutSessionSchema,\n payResultSchema,\n type CheckoutSession,\n type PayRequest,\n type PayResult,\n} from \"./types\"\n\nexport interface CheckoutSource {\n getSession(): Promise<CheckoutSession>\n pay(request: PayRequest): Promise<PayResult>\n}\n\nexport class CheckoutSourceError extends Error {\n readonly status?: number\n constructor(message: string, status?: number) {\n super(message)\n this.name = \"CheckoutSourceError\"\n this.status = status\n }\n}\n\nasync function parseJSON(response: Response): Promise<unknown> {\n try {\n return await response.json()\n } catch {\n throw new CheckoutSourceError(\"invalid response\", response.status)\n }\n}\n\nfunction parseSession(response: Response, value: unknown): CheckoutSession {\n const parsed = checkoutSessionSchema.safeParse(value)\n if (!parsed.success) {\n throw new CheckoutSourceError(\"session unavailable\", response.status)\n }\n return parsed.data\n}\n\nfunction parsePayResult(response: Response, value: unknown): PayResult {\n const parsed = payResultSchema.safeParse(value)\n if (!parsed.success) {\n throw new CheckoutSourceError(\"Payment failed. Try again.\", response.status)\n }\n return parsed.data\n}\n\nexport function createHttpSource(options: {\n baseUrl: string\n sessionId: string\n fetch?: typeof fetch\n}): CheckoutSource {\n const doFetch = options.fetch ?? fetch\n const base = options.baseUrl.replace(/\\/$/, \"\")\n const sessionURL = `${base}/api/v1/checkout/sessions/${encodeURIComponent(options.sessionId)}`\n return {\n async getSession() {\n const response = await doFetch(sessionURL, {\n headers: { Accept: \"application/json\" },\n })\n if (!response.ok) {\n throw new CheckoutSourceError(\"session unavailable\", response.status)\n }\n return parseSession(response, await parseJSON(response))\n },\n async pay(request: PayRequest) {\n const response = await doFetch(`${sessionURL}/pay`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Accept: \"application/json\",\n },\n body: JSON.stringify(request),\n })\n if (!response.ok) {\n let message = \"Payment failed. Try again.\"\n try {\n const body = (await response.json()) as { error?: unknown }\n if (typeof body.error === \"string\" && body.error) {\n message = body.error\n }\n } catch {\n // keep the generic message\n }\n throw new CheckoutSourceError(message, response.status)\n }\n return parsePayResult(response, await parseJSON(response))\n },\n }\n}\n","// Fixture sources: drive every UI state without a backend or gateway. Used\n// by previews and tests; the \"preview_\" tokenization key makes CardFields\n// render inert placeholders instead of live Collect.js iframes.\nimport type { CheckoutSource } from \"./source\"\nimport type { CheckoutSession, PayResult } from \"./types\"\n\nexport function fixtureSession(\n overrides?: Partial<CheckoutSession>\n): CheckoutSession {\n return {\n id: \"ocs_preview\",\n status: \"created\",\n merchant: { display_name: \"Acme Demo\" },\n plan: {\n display_name: \"Premium Membership\",\n unit_amount: \"99000000\",\n currency: \"USD\",\n unit_decimals: 6,\n period_hours: 720,\n automatically_renews: true,\n },\n tax: \"0\",\n rails: [\n {\n id: \"option_1\",\n rail: \"nmi\",\n mode: \"subscription\",\n driver: \"collect_js\",\n public_config: {\n tokenization_key: \"preview_tokenization_key\",\n tokenization_url: \"preview://collect\",\n },\n },\n {\n id: \"option_2\",\n rail: \"stripe\",\n mode: \"subscription\",\n driver: \"redirect\",\n },\n {\n id: \"option_3\",\n rail: \"ccbill\",\n mode: \"subscription\",\n driver: \"redirect\",\n },\n {\n id: \"option_4\",\n rail: \"solana\",\n mode: \"one_off\",\n driver: \"solana_pay\",\n public_config: { token_symbol: \"USDC\", token_name: \"USD Coin\" },\n },\n ],\n saved_methods: [\n {\n id: \"pm_preview_visa\",\n option_id: \"option_1\",\n rail: \"nmi\",\n brand: \"visa\",\n last_four: \"4242\",\n exp_month: 12,\n exp_year: 2030,\n },\n {\n id: \"pm_preview_mc\",\n option_id: \"option_1\",\n rail: \"nmi\",\n brand: \"mastercard\",\n last_four: \"5454\",\n exp_month: 3,\n exp_year: 2029,\n },\n ],\n expires_at: new Date(Date.now() + 30 * 60 * 1000).toISOString(),\n ...overrides,\n }\n}\n\nexport function createFixtureSource(options?: {\n session?: Partial<CheckoutSession>\n payResult?: PayResult\n payDelayMs?: number\n loadDelayMs?: number\n}): CheckoutSource {\n return {\n async getSession() {\n if (options?.loadDelayMs) {\n await new Promise((resolve) => setTimeout(resolve, options.loadDelayMs))\n }\n return fixtureSession(options?.session)\n },\n async pay() {\n await new Promise((resolve) =>\n setTimeout(resolve, options?.payDelayMs ?? 1200)\n )\n return options?.payResult ?? { status: \"succeeded\" }\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAmEA,SAAgB,GACd,GACwB;CACxB,OAAO;AACT;AAEA,IAAa,KAAqC;AAIlD,SAAS,GAAU,GAAc,GAAoB;CACnD,IAAM,IAAY,EAAE,GAAG,EAAO;CAC9B,KAAK,IAAM,CAAC,GAAK,MAAU,OAAO,QAAQ,CAAM,GAAG;EACjD,IAAI,KAAiC,MAAM;EAC3C,IAAM,IAAU,EAAI;EACpB,AAAI,OAAO,KAAU,WACf,MAAU,OAAI,EAAI,KAAO,KACxB,AAGL,EAAI,KAFO,GADF,OAAO,KAAY,WACP,IAEA,CAAC,GAFQ,CAEA;CAElC;CACA,OAAO;AACT;AAGA,SAAgB,GACd,GACmB;CACnB,IAAM,IAAO,IAAW,MAAM,QAAQ,CA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KAAQ,YAAY;IAAW;GAChE;EACF;EACA,eAAe,CACb;GACE,IAAI;GACJ,WAAW;GACX,MAAM;GACN,OAAO;GACP,WAAW;GACX,WAAW;GACX,UAAU;EACZ,GACA;GACE,IAAI;GACJ,WAAW;GACX,MAAM;GACN,OAAO;GACP,WAAW;GACX,WAAW;GACX,UAAU;EACZ,CACF;EACA,YAAY,IAAI,KAAK,KAAK,IAAI,IAAI,IAAc,CAAC,CAAC,YAAY;EAC9D,GAAG;CACL;AACF;AAEA,SAAgB,GAAoB,GAKjB;CACjB,OAAO;EACL,MAAM,aAAa;GAIjB,OAHI,GAAS,eACX,MAAM,IAAI,SAAS,MAAY,WAAW,GAAS,EAAQ,WAAW,CAAC,GAElE,GAAe,GAAS,OAAO;EACxC;EACA,MAAM,MAAM;GAIV,OAHA,MAAM,IAAI,SAAS,MACjB,WAAW,GAAS,GAAS,cAAc,IAAI,CACjD,GACO,GAAS,aAAa,EAAE,QAAQ,YAAY;EACrD;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/i18n/messages.ts","../src/i18n/context.ts","../src/appearance.ts","../src/scope-context.ts","../src/provider.tsx","../src/scope.tsx","../src/components/ui/button.tsx","../src/lib/period.ts","../src/account/format.ts","../src/components/ui/card.tsx","../src/components/ui/skeleton.tsx","../src/account/section.tsx","../src/components/ui/badge.tsx","../src/account/status-badge.tsx","../src/account/payment-history.tsx","../src/lib/card-brands.ts","../src/components/card-brands.tsx","../src/components/ui/alert-dialog.tsx","../src/components/ui/dialog.tsx","../src/components/ui/spinner.tsx","../src/components/ui/input.tsx","../src/components/ui/label.tsx","../src/lib/billing.ts","../src/components/billing-fields.tsx","../src/components/card-fields.tsx","../src/components/pay-button.tsx","../src/lib/stripe.ts","../src/lib/collect.ts","../src/lib/stripe-appearance.ts","../src/components/stripe-card.tsx","../src/lib/card-entry.ts","../src/tokenized-card-form.tsx","../src/save-payment-method.tsx","../src/account/notice.tsx","../src/account/payment-methods-panel.tsx","../src/components/ui/textarea.tsx","../src/account/cancel-dialog.tsx","../src/components/ui/radio-group.tsx","../src/account/change-card-dialog.tsx","../src/account/subscriptions-panel.tsx","../src/account/account-billing.tsx","../src/authenticate.ts","../src/components/ccbill-fields.tsx","../src/lib/ccbill.ts","../src/lib/rail-meta.ts","../src/components/methods.tsx","../src/components/qr.tsx","../src/components/saved-methods.tsx","../src/components/summary.tsx","../src/components/states.tsx","../src/lib/redirect.ts","../src/checkout.tsx","../src/modal.tsx","../src/frame.ts","../src/checkout-page.tsx","../src/checkout-frame.tsx","../src/fixtures.ts"],"sourcesContent":["import { en } from \"../locales/en.ts\"\n\n/**\n * A count-dependent message: CLDR plural categories for the locale, with\n * `other` required. An exact-count key (`\"1\"`) wins over the category, like\n * ICU's `=1`, for locales whose single form differs from `{count}` (毎日).\n */\nexport type PluralMessage = {\n [K in Intl.LDMLPluralRule | \"1\"]?: string\n} & { other: string }\n\ntype Widen<T> = {\n [K in keyof T]: T[K] extends string\n ? string\n : T[K] extends PluralMessage\n ? PluralMessage\n : Widen<T[K]>\n}\n\n/** The complete message tree; English is the reference shape. */\nexport type BillingUiMessages = Widen<typeof en>\n\ntype DeepPartial<T> = {\n [K in keyof T]?: T[K] extends string\n ? string\n : T[K] extends PluralMessage\n ? Partial<PluralMessage>\n : DeepPartial<T[K]>\n}\n\n/** A locale bundle or host override: any subset of the tree. */\nexport type BillingUiMessageBundle = DeepPartial<BillingUiMessages>\n\ntype Paths<T, P extends string = \"\"> = {\n [K in keyof T & string]: T[K] extends string\n ? `${P}${K}`\n : T[K] extends PluralMessage\n ? never\n : Paths<T[K], `${P}${K}.`>\n}[keyof T & string]\n\ntype PluralPaths<T, P extends string = \"\"> = {\n [K in keyof T & string]: T[K] extends string\n ? never\n : T[K] extends PluralMessage\n ? `${P}${K}`\n : PluralPaths<T[K], `${P}${K}.`>\n}[keyof T & string]\n\n/** Dotted key of any message, e.g. `subscriptions.title`. */\nexport type MessageKey = Paths<BillingUiMessages>\n\n/** Dotted key of a count-dependent message, e.g. `interval.every.day`. */\nexport type PluralKey = PluralPaths<BillingUiMessages>\n\nexport type MessageVars = Record<string, string | number>\n\n/**\n * Host translation hook. Receives the bare key (`subscriptions.title`,\n * `errors.not_found`); return nothing or the key itself to use ours.\n */\nexport type BillingUiTranslate = (\n key: string,\n vars?: MessageVars\n) => string | null | undefined\n\n/** Types a locale bundle or override against the message tree. */\nexport function defineMessages(\n bundle: BillingUiMessageBundle\n): BillingUiMessageBundle {\n return bundle\n}\n\nexport const defaultMessages: BillingUiMessages = en\n\ntype Tree = { [key: string]: string | Tree }\n\nfunction mergeInto(target: Tree, source: Tree): Tree {\n const out: Tree = { ...target }\n for (const [key, value] of Object.entries(source)) {\n if (value === undefined || value === null) continue\n const current = out[key]\n if (typeof value === \"string\") {\n if (value !== \"\") out[key] = value\n } else if (typeof current === \"object\") {\n out[key] = mergeInto(current, value)\n } else {\n out[key] = mergeInto({}, value)\n }\n }\n return out\n}\n\n/** Layers bundles over English; later bundles win, missing keys fall back. */\nexport function resolveMessages(\n bundles?: BillingUiMessageBundle | readonly BillingUiMessageBundle[]\n): BillingUiMessages {\n const list = bundles ? (Array.isArray(bundles) ? bundles : [bundles]) : []\n let tree = en as unknown as Tree\n for (const bundle of list) tree = mergeInto(tree, bundle as Tree)\n return tree as unknown as BillingUiMessages\n}\n\nexport function interpolate(template: string, vars?: MessageVars): string {\n if (!vars) return template\n return template.replace(/\\{(\\w+)\\}/g, (match, name: string) =>\n name in vars ? String(vars[name]) : match\n )\n}\n\nfunction lookup(messages: BillingUiMessages, key: string): string | undefined {\n let node: unknown = messages\n for (const part of key.split(\".\")) {\n if (!node || typeof node !== \"object\") return undefined\n node = (node as Tree)[part]\n }\n return typeof node === \"string\" ? node : undefined\n}\n\nexport interface Translator {\n messages: BillingUiMessages\n /** BCP 47 tag used for plural rules and numbers; the runtime's when unset. */\n locale?: string\n t(key: MessageKey, vars?: MessageVars): string\n /**\n * Count-dependent message: tries `<key>.<count>`, then the locale's plural\n * category, then `<key>.other`. `{count}` is locale-formatted.\n */\n plural(key: PluralKey, count: number, vars?: MessageVars): string\n /** Message for an billing error, error code, or thrown value. */\n error(error: unknown, vars?: MessageVars): string\n}\n\nfunction errorCode(error: unknown): string | undefined {\n if (typeof error === \"string\") return error\n if (error && typeof error === \"object\" && \"code\" in error) {\n const code = (error as { code: unknown }).code\n if (typeof code === \"string\") return code\n }\n return undefined\n}\n\nfunction isNetworkError(error: unknown): boolean {\n return error instanceof TypeError && /fetch|network/i.test(error.message)\n}\n\nfunction pluralRules(locale?: string): Intl.PluralRules {\n try {\n return new Intl.PluralRules(locale)\n } catch {\n return new Intl.PluralRules(\"en\")\n }\n}\n\nfunction formatCount(count: number, locale?: string): string {\n try {\n return new Intl.NumberFormat(locale).format(count)\n } catch {\n return String(count)\n }\n}\n\nexport function createTranslator(\n messages: BillingUiMessages,\n hostT?: BillingUiTranslate,\n locale?: string\n): Translator {\n const rules = pluralRules(locale)\n const translate = (key: string, vars?: MessageVars): string | undefined => {\n const hosted = hostT?.(key, vars)\n if (hosted && hosted !== key) return hosted\n const own = lookup(messages, key)\n return own === undefined ? undefined : interpolate(own, vars)\n }\n return {\n messages,\n locale,\n t: (key, vars) => translate(key, vars) ?? key,\n plural(key, count, vars) {\n const all = { ...vars, count: formatCount(count, locale) }\n return (\n translate(`${key}.${count}`, all) ??\n translate(`${key}.${rules.select(count)}`, all) ??\n translate(`${key}.other`, all) ??\n key\n )\n },\n error(error, vars) {\n const code = errorCode(error)\n if (code && code !== \"generic\" && code !== \"network\") {\n const metadata =\n error && typeof error === \"object\" && \"metadata\" in error\n ? (error as { metadata?: MessageVars }).metadata\n : undefined\n const message = translate(`errors.${code}`, { ...metadata, ...vars })\n if (message) return message\n }\n const fallback = isNetworkError(error)\n ? \"errors.network\"\n : \"errors.generic\"\n return translate(fallback, vars) ?? messages.errors.generic\n },\n }\n}\n","import { createContext, useContext } from \"react\"\n\nimport {\n createTranslator,\n defaultMessages,\n type Translator,\n} from \"./messages.ts\"\n\nexport const MessagesContext = createContext<Translator>(\n createTranslator(defaultMessages)\n)\n\n/** English defaults when rendered outside an `BillingUiProvider`. */\nexport function useMessages(): Translator {\n return useContext(MessagesContext)\n}\n","// Integrator theming. The component scopes the standard shadcn token set\n// under its root, so `theme` flips the whole palette and `variables` override\n// individual tokens without the integrator touching our CSS.\nimport type { CSSProperties } from \"react\"\n\n// `inherit` uses the host page's shadcn tokens (`--background`, ...) and its\n// `.dark` class instead of the bundled zinc palette.\nexport type CheckoutTheme = \"light\" | \"dark\" | \"auto\" | \"inherit\"\n\n// The tokens integrators may override. Values are raw CSS color/length\n// strings; they land as custom properties on the checkout root.\nexport interface CheckoutVariables {\n background?: string\n foreground?: string\n card?: string\n mutedForeground?: string\n faintForeground?: string\n border?: string\n input?: string\n primary?: string\n primaryForeground?: string\n destructive?: string\n ring?: string\n radius?: string\n fontFamily?: string\n}\n\nexport interface CheckoutAppearance {\n theme?: CheckoutTheme\n variables?: CheckoutVariables\n}\n\nconst VARIABLE_TO_CSS: Record<keyof CheckoutVariables, string> = {\n background: \"--background\",\n foreground: \"--foreground\",\n card: \"--card\",\n mutedForeground: \"--muted-foreground\",\n faintForeground: \"--orck-faint\",\n border: \"--border\",\n input: \"--input\",\n primary: \"--primary\",\n primaryForeground: \"--primary-foreground\",\n destructive: \"--destructive\",\n ring: \"--ring\",\n radius: \"--radius\",\n fontFamily: \"--orck-font\",\n}\n\nexport function appearanceStyle(\n appearance: CheckoutAppearance | undefined\n): CSSProperties | undefined {\n const variables = appearance?.variables\n if (!variables) return undefined\n const style: Record<string, string> = {}\n for (const [key, value] of Object.entries(variables)) {\n if (!value) continue\n style[VARIABLE_TO_CSS[key as keyof CheckoutVariables]] = value\n }\n return style as CSSProperties\n}\n\nexport function appearanceTheme(\n appearance: CheckoutAppearance | undefined\n): CheckoutTheme {\n return appearance?.theme ?? \"auto\"\n}\n","import { createContext, useContext, type CSSProperties } from \"react\"\n\nimport {\n appearanceStyle,\n appearanceTheme,\n type CheckoutAppearance,\n type CheckoutTheme,\n} from \"./appearance\"\n\nexport type Navigate = (to: string) => void\n\nexport interface UiSettings {\n appearance?: CheckoutAppearance\n locale?: string\n navigate?: Navigate\n}\n\nexport const UiContext = createContext<UiSettings>({})\n\nexport const useUiSettings = (): UiSettings => useContext(UiContext)\n\nexport interface ScopeProps {\n className: string\n \"data-orck-theme\": CheckoutTheme\n style?: CSSProperties\n}\n\n/** Props that make an element a styling root; portals carry them too. */\nexport function useScopeProps(appearance?: CheckoutAppearance): ScopeProps {\n const settings = useUiSettings()\n const resolved = appearance ?? settings.appearance\n return {\n className: \"orck\",\n \"data-orck-theme\": appearanceTheme(resolved),\n style: appearanceStyle(resolved),\n }\n}\n","import { useMemo, type ReactNode } from \"react\"\n\nimport type { CheckoutAppearance } from \"./appearance\"\nimport { MessagesContext } from \"./i18n/context\"\nimport {\n createTranslator,\n resolveMessages,\n type BillingUiMessageBundle,\n type BillingUiTranslate,\n} from \"./i18n/messages\"\nimport { UiContext, type Navigate } from \"./scope-context\"\n\nexport interface BillingUiProviderProps {\n appearance?: CheckoutAppearance\n /** Locale bundle(s) layered over English; later entries win. */\n messages?: BillingUiMessageBundle | readonly BillingUiMessageBundle[]\n /** Host translation hook, consulted before the bundles. */\n t?: BillingUiTranslate\n /** BCP 47 tag for dates, money and plurals; defaults to the browser's. */\n locale?: string\n /** Host router for in-app links (e.g. the plans page). */\n navigate?: Navigate\n children?: ReactNode\n}\n\n/** Renders no DOM; surfaces create their own styling roots. */\nexport function BillingUiProvider({\n appearance,\n messages,\n t,\n locale,\n navigate,\n children,\n}: BillingUiProviderProps) {\n const translator = useMemo(\n () => createTranslator(resolveMessages(messages), t, locale),\n [messages, t, locale]\n )\n const ui = useMemo(\n () => ({ appearance, locale, navigate }),\n [appearance, locale, navigate]\n )\n return (\n <UiContext.Provider value={ui}>\n <MessagesContext.Provider value={translator}>\n {children}\n </MessagesContext.Provider>\n </UiContext.Provider>\n )\n}\n","import type { ComponentProps } from \"react\"\n\nimport type { CheckoutAppearance } from \"./appearance\"\nimport { cn } from \"cn\"\nimport { useScopeProps } from \"./scope-context\"\n\n/** Styling root for in-page billing surfaces. */\nexport function BillingUiRoot({\n appearance,\n className,\n style,\n ...props\n}: ComponentProps<\"div\"> & { appearance?: CheckoutAppearance }) {\n const scope = useScopeProps(appearance)\n return (\n <div\n data-orck-theme={scope[\"data-orck-theme\"]}\n className={cn(scope.className, className)}\n style={{ ...scope.style, ...style }}\n {...props}\n />\n )\n}\n","import { Button as ButtonPrimitive } from \"@base-ui/react/button\"\nimport { cva, type VariantProps } from \"class-variance-authority\"\nimport { cn } from \"cn\"\n\nconst buttonVariants = cva(\n \"group/button inline-flex shrink-0 items-center justify-center rounded-md border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4\",\n {\n variants: {\n variant: {\n default: \"bg-primary text-primary-foreground hover:bg-primary/80\",\n outline:\n \"border-border bg-background shadow-xs hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50\",\n secondary:\n \"bg-secondary text-secondary-foreground hover:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)] aria-expanded:bg-secondary aria-expanded:text-secondary-foreground\",\n ghost:\n \"hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50\",\n destructive:\n \"bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40\",\n link: \"text-primary underline-offset-4 hover:underline\",\n },\n size: {\n default:\n \"h-9 gap-1.5 px-2.5 in-data-[slot=button-group]:rounded-md has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2\",\n xs: \"h-6 gap-1 rounded-[min(var(--radius-md),8px)] px-2 text-xs in-data-[slot=button-group]:rounded-md has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3\",\n sm: \"h-8 gap-1 rounded-[min(var(--radius-md),10px)] px-2.5 in-data-[slot=button-group]:rounded-md has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5\",\n lg: \"h-10 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2\",\n icon: \"size-9\",\n \"icon-xs\":\n \"size-6 rounded-[min(var(--radius-md),8px)] in-data-[slot=button-group]:rounded-md [&_svg:not([class*='size-'])]:size-3\",\n \"icon-sm\":\n \"size-8 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-md\",\n \"icon-lg\": \"size-10\",\n },\n },\n defaultVariants: {\n variant: \"default\",\n size: \"default\",\n },\n }\n)\n\nfunction Button({\n className,\n variant = \"default\",\n size = \"default\",\n ...props\n}: ButtonPrimitive.Props & VariantProps<typeof buttonVariants>) {\n return (\n <ButtonPrimitive\n data-slot=\"button\"\n className={cn(buttonVariants({ variant, size, className }))}\n {...props}\n />\n )\n}\n\nexport { Button, buttonVariants }\n","import type { Translator } from \"../i18n/messages\"\n\n// OpenRails durations are exact hours (720h is 30 days, never \"a month\"), so\n// labels name only units that divide the window exactly.\nexport type PeriodUnit = \"hour\" | \"day\" | \"week\"\n\nexport interface Period {\n unit: PeriodUnit\n count: number\n}\n\nexport function periodOf(hours: number | null | undefined): Period | null {\n if (!hours || !Number.isSafeInteger(hours) || hours <= 0) return null\n if (hours % 168 === 0) return { unit: \"week\", count: hours / 168 }\n if (hours % 24 === 0) return { unit: \"day\", count: hours / 24 }\n return { unit: \"hour\", count: hours }\n}\n\n/** \"every 30 days\" */\nexport function everyLabel(hours: number | null | undefined, m: Translator) {\n const p = periodOf(hours)\n return p ? m.plural(`interval.every.${p.unit}`, p.count) : null\n}\n\n/** \"/ 30 days\" */\nexport function perLabel(hours: number | null | undefined, m: Translator) {\n const p = periodOf(hours)\n return p ? m.plural(`interval.per.${p.unit}`, p.count) : null\n}\n\n/** \"30 days of access\", for a window that does not renew. */\nexport function accessLabel(hours: number | null | undefined, m: Translator) {\n const p = periodOf(hours)\n return p ? m.plural(`interval.access.${p.unit}`, p.count) : null\n}\n","import type {\n CardSummary,\n CurrencyScales,\n Payment,\n Price,\n Subscription,\n} from \"../client/types\"\nimport type { Translator } from \"../i18n/messages\"\nimport { formatAmount } from \"../lib/money\"\nimport { accessLabel, everyLabel } from \"../lib/period\"\n\nexport function formatDate(\n value: string | null | undefined,\n locale?: string\n): string | null {\n if (!value) return null\n const date = new Date(value)\n if (Number.isNaN(date.getTime())) return null\n try {\n return new Intl.DateTimeFormat(locale, { dateStyle: \"medium\" }).format(date)\n } catch {\n return date.toISOString().slice(0, 10)\n }\n}\n\n/** Exact money, or null while the currency's scale is unknown. */\nexport function formatMoney(\n amount: string | null | undefined,\n currency: string,\n scales: CurrencyScales,\n locale?: string\n): string | null {\n if (!amount) return null\n const decimals = scales[currency.toUpperCase()]\n if (decimals === undefined) return null\n return formatAmount(amount, currency, decimals, locale)\n}\n\n/** \"every 30 days\", \"30 days of access\" or \"one-time\". */\nexport function intervalLabel(\n price: Pick<Price, \"access_duration_hours\" | \"billing_interval_hours\"> | null | undefined,\n m: Translator\n): string | null {\n if (!price) return null\n if (price.billing_interval_hours) return everyLabel(price.billing_interval_hours, m)\n return accessLabel(price.access_duration_hours, m) ?? m.t(\"interval.once\")\n}\n\nexport function subscriptionName(s: Subscription, { t }: Translator): string {\n return (\n s.product?.display_name?.trim() ||\n s.price?.key?.trim() ||\n t(\"subscriptions.fallbackName\")\n )\n}\n\n/** What a payment bought: the product's name, else its kind, plus its cadence. */\nexport function paymentItem(\n p: Payment,\n m: Translator\n): { name: string; detail: string | null } {\n const recurring = !!p.price?.billing_interval_hours || !!p.subscription_id\n const name =\n p.product?.display_name?.trim() ||\n m.t(recurring ? \"history.subscription\" : \"history.purchase\")\n return {\n name,\n detail: recurring ? everyLabel(p.price?.billing_interval_hours, m) : null,\n }\n}\n\nexport function brandName(brand: string | null | undefined, fallback: string) {\n const value = brand?.trim()\n if (!value) return fallback\n return value[0].toUpperCase() + value.slice(1).toLowerCase()\n}\n\n/** \"Visa •••• 4242 · 12/30\"; the brand alone when no digits are known. */\nexport function cardText(\n card: CardSummary | null | undefined,\n m: Translator\n): string {\n const brand = brandName(card?.brand, m.t(\"paymentMethods.fallbackBrand\"))\n if (!card?.last4) return brand\n const label = m.t(\"paymentMethods.cardLabel\", { brand, last4: card.last4 })\n const expires = expiry(card)\n return expires ? `${label} · ${expires}` : label\n}\n\nexport function expiry(card: CardSummary | null | undefined): string | null {\n if (!card?.exp_month || !card.exp_year) return null\n return `${String(card.exp_month).padStart(2, \"0\")}/${String(card.exp_year).slice(-2)}`\n}\n\nexport const LIVE_STATUSES = new Set([\n \"active\",\n \"pending\",\n \"past_due\",\n \"awaiting_method\",\n \"unverified\",\n])\n\nconst future = (at: string | null | undefined) =>\n !!at && new Date(at).getTime() > Date.now()\n\n/** A current subscription, or a canceled subscription retaining paid access. */\nexport const isLive = (s: Subscription) =>\n LIVE_STATUSES.has(s.status) ||\n (s.status === \"canceled\" &&\n !!s.access &&\n (!s.access.ends_at || future(s.access.ends_at)))\n\n/** Future billing has stopped or cancellation is scheduled. */\nexport const isEnding = (s: Subscription) =>\n isLive(s) && (!!s.cancel_scheduled || s.status === \"canceled\")\n\nexport type StatusTone = \"success\" | \"warning\" | \"destructive\" | \"neutral\"\n\nconst TONE: Record<string, StatusTone> = {\n active: \"success\",\n succeeded: \"success\",\n paid: \"success\",\n collection: \"neutral\",\n pending: \"warning\",\n past_due: \"warning\",\n awaiting_method: \"warning\",\n cancel_scheduled: \"warning\",\n expiring_soon: \"warning\",\n needs_attention: \"warning\",\n partially_refunded: \"neutral\",\n failed: \"destructive\",\n expired: \"destructive\",\n canceled: \"neutral\",\n refunded: \"neutral\",\n}\n\nexport const statusTone = (status: string): StatusTone =>\n TONE[status] ?? \"neutral\"\n\n// The package ships no preflight, so account surfaces zero UA text margins.\nexport const RESET =\n \"[&_h2]:m-0 [&_p]:m-0 [&_ul]:m-0 [&_ul]:list-none [&_ul]:p-0 [&_table]:border-spacing-0\"\n","import * as React from \"react\"\nimport { cn } from \"cn\"\n\nfunction Card({\n className,\n size = \"default\",\n ...props\n}: React.ComponentProps<\"div\"> & { size?: \"default\" | \"sm\" }) {\n return (\n <div\n data-slot=\"card\"\n data-size={size}\n className={cn(\n \"group/card flex flex-col gap-(--card-spacing) overflow-hidden rounded-xl bg-card py-(--card-spacing) text-sm text-card-foreground shadow-xs ring-1 ring-foreground/10 [--card-spacing:--spacing(6)] has-[>img:first-child]:pt-0 data-[size=sm]:[--card-spacing:--spacing(4)] *:[img:first-child]:rounded-t-xl *:[img:last-child]:rounded-b-xl\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction CardHeader({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-header\"\n className={cn(\n \"group/card-header @container/card-header grid auto-rows-min items-start gap-1 rounded-t-xl px-(--card-spacing) has-data-[slot=card-action]:grid-cols-[1fr_auto] has-data-[slot=card-description]:grid-rows-[auto_auto] [.border-b]:pb-(--card-spacing)\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction CardTitle({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-title\"\n className={cn(\n \"text-base leading-normal font-medium group-data-[size=sm]/card:text-sm\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction CardDescription({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-description\"\n className={cn(\"text-sm text-muted-foreground\", className)}\n {...props}\n />\n )\n}\n\nfunction CardAction({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-action\"\n className={cn(\n \"col-start-2 row-span-2 row-start-1 self-start justify-self-end\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction CardContent({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-content\"\n className={cn(\"flex flex-col gap-3 px-(--card-spacing)\", className)}\n {...props}\n />\n )\n}\n\nfunction CardFooter({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-footer\"\n className={cn(\n \"flex items-center rounded-b-xl px-(--card-spacing) [.border-t]:pt-(--card-spacing)\",\n className\n )}\n {...props}\n />\n )\n}\n\nexport {\n Card,\n CardHeader,\n CardFooter,\n CardTitle,\n CardAction,\n CardDescription,\n CardContent,\n}\n","import { cn } from \"cn\"\n\nfunction Skeleton({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"skeleton\"\n className={cn(\"animate-pulse rounded-md bg-muted\", className)}\n {...props}\n />\n )\n}\n\nexport { Skeleton }\n","import * as React from \"react\"\nimport { cn } from \"cn\"\n\nimport type { CheckoutAppearance } from \"#orck/appearance\"\nimport type { BillingError } from \"#orck/client/errors\"\nimport { Button } from \"#orck/components/ui/button\"\nimport {\n Card,\n CardAction,\n CardContent,\n CardDescription,\n CardHeader,\n CardTitle,\n} from \"#orck/components/ui/card\"\nimport { Skeleton } from \"#orck/components/ui/skeleton\"\nimport { useMessages } from \"#orck/i18n/context\"\nimport { useScopeProps } from \"#orck/scope-context\"\nimport { RESET } from \"./format\"\n\nexport interface SectionProps {\n title: string\n description?: string\n action?: React.ReactNode\n appearance?: CheckoutAppearance\n className?: string\n children?: React.ReactNode\n \"data-testid\"?: string\n}\n\n// Styling root plus card. Each panel is usable alone, so each is a root.\nexport function Section({\n title,\n description,\n action,\n appearance,\n className,\n children,\n ...rest\n}: SectionProps) {\n const scope = useScopeProps(appearance)\n const id = React.useId()\n return (\n <section\n aria-labelledby={id}\n className={cn(scope.className, RESET, \"block\", className)}\n data-orck-theme={scope[\"data-orck-theme\"]}\n style={scope.style}\n data-testid={rest[\"data-testid\"]}\n >\n <Card className=\"gap-4 bg-card text-card-foreground\">\n <CardHeader>\n <CardTitle id={id} role=\"heading\" aria-level={2}>\n {title}\n </CardTitle>\n {description ? (\n <CardDescription>{description}</CardDescription>\n ) : null}\n {action ? <CardAction>{action}</CardAction> : null}\n </CardHeader>\n <CardContent className=\"gap-0\">{children}</CardContent>\n </Card>\n </section>\n )\n}\n\nexport function ListSkeleton({ rows = 2 }: { rows?: number }) {\n return (\n <div className=\"grid gap-4 py-2\" aria-hidden>\n {Array.from({ length: rows }, (_, i) => (\n <div key={i} className=\"flex items-center gap-3\">\n <Skeleton className=\"h-7 w-11 rounded-md\" />\n <div className=\"grid flex-1 gap-2\">\n <Skeleton className=\"h-3.5 w-40\" />\n <Skeleton className=\"h-3 w-28\" />\n </div>\n <Skeleton className=\"h-3.5 w-14\" />\n </div>\n ))}\n </div>\n )\n}\n\nexport function EmptyState({\n title,\n description,\n action,\n}: {\n title: string\n description?: string\n action?: React.ReactNode\n}) {\n return (\n <div className=\"grid justify-items-center gap-1 rounded-lg border border-dashed px-4 py-8 text-center\">\n <p className=\"text-sm font-medium\">{title}</p>\n {description ? (\n <p className=\"text-sm text-muted-foreground\">{description}</p>\n ) : null}\n {action ? <div className=\"mt-3\">{action}</div> : null}\n </div>\n )\n}\n\nexport function ErrorState({\n error,\n message,\n onRetry,\n}: {\n error: BillingError\n /** Replaces the error's own message. */\n message?: string\n onRetry: () => void\n}) {\n const m = useMessages()\n return (\n <div\n role=\"alert\"\n className=\"flex flex-wrap items-center justify-between gap-3 rounded-lg bg-destructive/5 px-4 py-3\"\n >\n <p className=\"text-sm text-destructive\">{message ?? m.error(error)}</p>\n <Button variant=\"outline\" size=\"sm\" onClick={onRetry}>\n {m.t(\"common.retry\")}\n </Button>\n </div>\n )\n}\n","import { mergeProps } from \"@base-ui/react/merge-props\"\nimport { useRender } from \"@base-ui/react/use-render\"\nimport { cva, type VariantProps } from \"class-variance-authority\"\nimport { cn } from \"cn\"\n\nconst badgeVariants = cva(\n \"group/badge inline-flex h-5 w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-4xl border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-all focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3!\",\n {\n variants: {\n variant: {\n default: \"bg-primary text-primary-foreground [a]:hover:bg-primary/80\",\n secondary:\n \"bg-secondary text-secondary-foreground [a]:hover:bg-secondary/80\",\n destructive:\n \"bg-destructive/10 text-destructive focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:focus-visible:ring-destructive/40 [a]:hover:bg-destructive/20\",\n outline:\n \"border-border text-foreground [a]:hover:bg-muted [a]:hover:text-muted-foreground\",\n ghost:\n \"hover:bg-muted hover:text-muted-foreground dark:hover:bg-muted/50\",\n link: \"text-primary underline-offset-4 hover:underline\",\n },\n },\n defaultVariants: {\n variant: \"default\",\n },\n }\n)\n\nfunction Badge({\n className,\n variant = \"default\",\n render,\n ...props\n}: useRender.ComponentProps<\"span\"> & VariantProps<typeof badgeVariants>) {\n return useRender({\n defaultTagName: \"span\",\n props: mergeProps<\"span\">(\n {\n className: cn(badgeVariants({ variant }), className),\n },\n props\n ),\n render,\n state: {\n slot: \"badge\",\n variant,\n },\n })\n}\n\nexport { Badge, badgeVariants }\n","import { cn } from \"cn\"\n\nimport { Badge } from \"#orck/components/ui/badge\"\nimport { useMessages } from \"#orck/i18n/context\"\nimport type { MessageKey } from \"#orck/i18n/messages\"\nimport { statusTone, type StatusTone } from \"./format\"\n\nconst TONE_CLASS: Record<StatusTone, string> = {\n success: \"bg-[color:var(--orck-success)]/12 text-[color:var(--orck-success)]\",\n warning: \"bg-[color:var(--orck-warning)]/14 text-[color:var(--orck-warning)]\",\n destructive: \"bg-destructive/10 text-destructive\",\n neutral: \"bg-muted text-muted-foreground\",\n}\n\nexport interface BillingStatusBadgeProps {\n /** Subscription, payment or card-health status. */\n status: string\n /** Overrides the translated label. */\n label?: string\n className?: string\n}\n\nexport function BillingStatusBadge({\n status,\n label,\n className,\n}: BillingStatusBadgeProps) {\n const { t, messages } = useMessages()\n const key = status\n const text =\n label ??\n (key in messages.status\n ? t(`status.${key}` as MessageKey)\n : status.replace(/_/g, \" \"))\n return (\n <Badge\n data-status={status}\n className={cn(TONE_CLASS[statusTone(status)], \"font-medium\", className)}\n >\n {text}\n </Badge>\n )\n}\n","import * as React from \"react\"\nimport { cn } from \"cn\"\n\nimport type { CheckoutAppearance } from \"#orck/appearance\"\nimport type { Payment } from \"#orck/client/types\"\nimport { Button } from \"#orck/components/ui/button\"\nimport { useMessages } from \"#orck/i18n/context\"\nimport type { MessageKey, Translator } from \"#orck/i18n/messages\"\nimport { usePayments, type PaymentsOptions } from \"#orck/react/hooks\"\nimport { useCurrencyScales } from \"#orck/react/config\"\nimport { useUiSettings } from \"#orck/scope-context\"\nimport { cardText, formatDate, formatMoney, paymentItem } from \"./format\"\nimport { EmptyState, ErrorState, ListSkeleton, Section } from \"./section\"\nimport { BillingStatusBadge } from \"./status-badge\"\n\nexport interface PaymentHistoryProps extends PaymentsOptions {\n appearance?: CheckoutAppearance\n className?: string\n}\n\nfunction methodText(p: Payment, m: Translator): string {\n if (p.card?.last4) return cardText(p.card, m)\n const rail = p.rail ?? \"\"\n return rail in m.messages.history.rail\n ? m.t(`history.rail.${rail}` as MessageKey)\n : rail || m.t(\"common.notAvailable\")\n}\n\nexport function PaymentHistory({\n appearance,\n className,\n ...options\n}: PaymentHistoryProps) {\n const m = useMessages()\n const { t } = m\n const { locale } = useUiSettings()\n const state = usePayments(options)\n const scales = useCurrencyScales()\n\n let body: React.ReactNode\n const payments = state.payments\n if (payments === null && state.error) {\n body = <ErrorState error={state.error} onRetry={state.refetch} />\n } else if (payments === null) {\n body = <ListSkeleton rows={3} />\n } else if (payments.length === 0 && state.page === 0) {\n body = (\n <EmptyState\n title={t(\"history.empty\")}\n description={t(\"history.emptyDescription\")}\n />\n )\n } else {\n body = (\n <div className=\"-mx-1 overflow-x-auto px-1\">\n <table\n className={cn(\n \"w-full border-collapse text-sm\",\n state.loading && \"opacity-60 transition-opacity\"\n )}\n aria-busy={state.loading || undefined}\n >\n <thead>\n <tr className=\"border-b text-left text-xs text-muted-foreground\">\n <th\n scope=\"col\"\n className=\"hidden py-2 pr-3 font-medium @md:table-cell\"\n >\n {t(\"history.date\")}\n </th>\n <th scope=\"col\" className=\"py-2 pr-3 font-medium\">\n {t(\"history.item\")}\n </th>\n <th\n scope=\"col\"\n className=\"hidden py-2 pr-3 font-medium @md:table-cell\"\n >\n {t(\"history.method\")}\n </th>\n <th scope=\"col\" className=\"py-2 pr-3 font-medium\">\n {t(\"history.status\")}\n </th>\n <th scope=\"col\" className=\"py-2 text-right font-medium\">\n {t(\"history.amount\")}\n </th>\n </tr>\n </thead>\n <tbody className=\"divide-y divide-border\">\n {payments.map((p) => {\n const refund = p.kind === \"refund\"\n const status = p.status || (refund ? \"refunded\" : \"unknown\")\n const amount = formatMoney(p.amount, p.currency, scales, locale)\n const refunded =\n !refund && p.amount_refunded && p.amount_refunded !== \"0\"\n ? formatMoney(p.amount_refunded, p.currency, scales, locale)\n : null\n const date =\n formatDate(p.created_at, locale) ?? t(\"common.notAvailable\")\n const item = paymentItem(p, m)\n return (\n <tr key={p.id} data-testid=\"payment-row\" data-payment-id={p.id}>\n <td className=\"hidden py-3 pr-3 align-top whitespace-nowrap tabular-nums @md:table-cell\">\n {date}\n </td>\n <td className=\"py-3 pr-3 align-top\">\n <div data-testid=\"payment-item\" className=\"font-medium\">\n {item.name}\n </div>\n {p.status === \"failed\" && p.failure?.message ? (\n <div\n data-testid=\"payment-failure\"\n className=\"text-xs text-destructive\"\n >\n {p.failure.message}\n </div>\n ) : null}\n {item.detail ? (\n <div\n data-testid=\"payment-period\"\n className=\"text-xs text-muted-foreground\"\n >\n {item.detail}\n </div>\n ) : null}\n <div className=\"text-xs text-muted-foreground tabular-nums @md:hidden\">\n {date} · {methodText(p, m)}\n </div>\n </td>\n <td className=\"hidden py-3 pr-3 align-top text-muted-foreground tabular-nums @md:table-cell\">\n {methodText(p, m)}\n </td>\n <td className=\"py-3 pr-3 align-top\">\n <BillingStatusBadge\n status={status}\n label={refund ? t(\"history.refund\") : undefined}\n />\n </td>\n <td className=\"py-3 text-right align-top font-medium whitespace-nowrap tabular-nums\">\n {amount ?? t(\"common.notAvailable\")}\n {refunded ? (\n <div className=\"text-xs font-normal text-muted-foreground\">\n {t(\"history.refundedAmount\", { amount: refunded })}\n </div>\n ) : null}\n </td>\n </tr>\n )\n })}\n </tbody>\n </table>\n </div>\n )\n }\n\n const paged = state.page > 0 || state.hasMore\n return (\n <Section\n title={t(\"history.title\")}\n description={t(\"history.description\")}\n appearance={appearance}\n className={className}\n data-testid=\"payment-history\"\n >\n {body}\n {payments !== null && state.error ? (\n <div className=\"pt-3\">\n <ErrorState error={state.error} onRetry={state.refetch} />\n </div>\n ) : null}\n {paged ? (\n <nav\n aria-label={t(\"history.title\")}\n className=\"flex items-center justify-between gap-3 pt-4\"\n >\n <span className=\"text-xs text-muted-foreground tabular-nums\">\n {t(\"history.page\", { page: state.page + 1 })}\n </span>\n <div className=\"flex gap-2\">\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={state.page === 0 || state.loading}\n onClick={state.previous}\n >\n {t(\"common.previous\")}\n </Button>\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={!state.hasMore || state.loading}\n onClick={state.next}\n >\n {t(\"common.next\")}\n </Button>\n </div>\n </nav>\n ) : null}\n </Section>\n )\n}\n","// Card-network identity: which marks we ship and how a rail's spelling maps\n// onto them.\nexport type CardBrand = \"visa\" | \"mastercard\" | \"amex\"\n\nconst BRAND_ALIASES: Record<string, CardBrand> = {\n visa: \"visa\",\n mastercard: \"mastercard\",\n mc: \"mastercard\",\n master: \"mastercard\",\n amex: \"amex\",\n americanexpress: \"amex\",\n \"american express\": \"amex\",\n}\n\n// Resolves the rail's spelling of a brand (\"Visa\", \"MASTERCARD\", \"amex\") onto\n// the marks we ship; anything unknown falls back to a text plate.\nexport function resolveCardBrand(brand?: string): CardBrand | undefined {\n const key = brand\n ?.trim()\n .toLowerCase()\n .replace(/[^a-z ]/g, \"\")\n return key ? BRAND_ALIASES[key] : undefined\n}\n","// Card network marks, inlined rather than fetched: this package is meant to\n// run inside someone else's app, where an asset URL of ours would 404. Artwork\n// is each network's own published symbol, unmodified in shape and color.\nimport * as React from \"react\"\n\nimport { resolveCardBrand } from \"#orck/lib/card-brands\"\nimport { cn } from \"cn\"\n\nfunction VisaMark() {\n return (\n <svg viewBox=\"0 0 1000 324.68\" className=\"h-2.5 w-auto\" role=\"presentation\">\n <path\n fill=\"#1434cb\"\n d=\"m651.19.5c-70.93,0-134.32,36.77-134.32,104.69,0,77.9,112.42,83.28,112.42,122.42,0,16.48-18.88,31.23-51.14,31.23-45.77,0-79.98-20.61-79.98-20.61l-14.64,68.55s39.41,17.41,91.73,17.41c77.55,0,138.58-38.57,138.58-107.66,0-82.32-112.89-87.54-112.89-123.86,0-12.91,15.5-27.05,47.66-27.05,36.29,0,65.89,14.99,65.89,14.99l14.33-66.2S696.61.5,651.18.5h0ZM2.22,5.5L.5,15.49s29.84,5.46,56.72,16.36c34.61,12.49,37.07,19.77,42.9,42.35l63.51,244.83h85.14L379.93,5.5h-84.94l-84.28,213.17-34.39-180.7c-3.15-20.68-19.13-32.48-38.68-32.48,0,0-135.41,0-135.41,0Zm411.87,0l-66.63,313.53h81L494.85,5.5h-80.76Zm451.76,0c-19.53,0-29.88,10.46-37.47,28.73l-118.67,284.8h84.94l16.43-47.47h103.48l9.99,47.47h74.95L934.12,5.5h-68.27Zm11.05,84.71l25.18,117.65h-67.45l42.28-117.65h0Z\"\n />\n </svg>\n )\n}\n\nfunction MastercardMark() {\n return (\n <svg viewBox=\"0 0 152.4 108\" className=\"h-4 w-auto\" role=\"presentation\">\n <g>\n <rect y=\"0\" fill=\"none\" width=\"152.4\" height=\"108\" />\n <g>\n <rect x=\"60.4\" y=\"25.7\" fill=\"#FF5F00\" width=\"31.5\" height=\"56.6\" />\n <path\n fill=\"#EB001B\"\n d=\"M62.4,54c0-11,5.1-21.5,13.7-28.3c-15.6-12.3-38.3-9.6-50.6,6.1C13.3,47.4,16,70,31.7,82.3\n\t\t\tc13.1,10.3,31.4,10.3,44.5,0C67.5,75.5,62.4,65,62.4,54z\"\n />\n <path\n fill=\"#F79E1B\"\n d=\"M134.4,54c0,19.9-16.1,36-36,36c-8.1,0-15.9-2.7-22.2-7.7c15.6-12.3,18.3-34.9,6-50.6c-1.8-2.2-3.8-4.3-6-6\n\t\t\tc15.6-12.3,38.3-9.6,50.5,6.1C131.7,38.1,134.4,45.9,134.4,54z\"\n />\n </g>\n </g>\n </svg>\n )\n}\n\nfunction AmexMark() {\n const gradientId = `orck-amex-${React.useId().replace(/[^a-zA-Z0-9-]/g, \"\")}`\n return (\n <svg viewBox=\"0 0 300 300\" className=\"h-full w-auto\" role=\"presentation\">\n <radialGradient\n id={gradientId}\n cx=\"57.3882\"\n cy=\"57.021\"\n r=\"264.5797\"\n gradientUnits=\"userSpaceOnUse\"\n >\n <stop offset=\"0\" stopColor=\"#9DD5F6\" />\n <stop offset=\"0.0711\" stopColor=\"#98D3F5\" />\n <stop offset=\"0.1575\" stopColor=\"#89CEF3\" />\n <stop offset=\"0.2516\" stopColor=\"#70C6EF\" />\n <stop offset=\"0.3514\" stopColor=\"#4EBBEA\" />\n <stop offset=\"0.4546\" stopColor=\"#23ADE3\" />\n <stop offset=\"0.5\" stopColor=\"#0DA6E0\" />\n <stop offset=\"1\" stopColor=\"#2E77BC\" />\n </radialGradient>\n <path\n fill={`url(#${gradientId})`}\n d=\"M289.584,7.598H7.639v282.966h281.945v-93.386c1.12-1.619,1.673-3.69,1.673-6.222\n\tc0-2.898-0.553-4.693-1.673-6.205\"\n />\n <g></g>\n <path\n fill=\"#FFFFFF\"\n d=\"M33.053,130.042l-5.424-13.217l-5.393,13.217 M152.543,124.779c-1.089,0.661-2.377,0.683-3.92,0.683h-9.627\n\tv-7.364h9.758c1.381,0,2.822,0.062,3.758,0.598c1.028,0.483,1.664,1.511,1.664,2.931\n\tC154.176,123.076,153.571,124.242,152.543,124.779z M221.221,130.042l-5.484-13.217l-5.454,13.217H221.221z M93.201,144.348h-8.124\n\tl-0.03-25.966l-11.491,25.966h-6.958l-11.521-25.989v25.989H38.959l-3.045-7.395h-16.5l-3.076,7.395H7.731l14.191-33.154h11.774\n\tl13.478,31.39v-31.39h12.934l10.371,22.491l9.527-22.491h13.194V144.348z M125.58,144.348H99.107v-33.154h26.473v6.904h-18.548\n\tv5.976h18.103v6.796h-18.103v6.621h18.548V144.348z M162.906,120.123c0,5.286-3.528,8.017-5.584,8.837\n\tc1.734,0.66,3.215,1.826,3.92,2.792c1.119,1.649,1.312,3.122,1.312,6.083v6.513h-7.993l-0.03-4.181c0-1.995,0.191-4.864-1.251-6.459\n\tc-1.158-1.166-2.923-1.419-5.776-1.419h-8.507v12.059h-7.924v-33.154h18.227c4.05,0,7.034,0.107,9.596,1.588\n\tC161.403,114.263,162.906,116.425,162.906,120.123z M175.588,144.348h-8.086v-33.154h8.086V144.348z M269.396,144.348h-11.23\n\tl-15.021-24.884v24.884h-16.139l-3.084-7.395H207.46l-2.992,7.395h-9.273c-3.852,0-8.729-0.852-11.491-3.667\n\tc-2.785-2.815-4.234-6.628-4.234-12.657c0-4.917,0.866-9.412,4.272-12.964c2.562-2.646,6.574-3.866,12.035-3.866h7.672v7.104h-7.511\n\tc-2.892,0-4.525,0.43-6.098,1.964c-1.351,1.396-2.278,4.035-2.278,7.51c0,3.552,0.706,6.113,2.179,7.786\n\tc1.22,1.312,3.437,1.71,5.523,1.71h3.559l11.169-26.073h11.874l13.417,31.359v-31.359h12.066l13.93,23.09v-23.09h8.117V144.348z\n\t M7.639,150.86h13.54l3.053-7.364h6.835l3.045,7.364h26.641v-5.63l2.378,5.654h13.83l2.378-5.738v5.714h66.208l-0.031-12.088h1.281\n\tc0.897,0.031,1.159,0.114,1.159,1.595v10.493h34.243v-2.814c2.762,1.48,7.058,2.814,12.711,2.814h14.406l3.083-7.364h6.835\n\tl3.015,7.364h27.761v-6.995l4.204,6.995h22.246v-46.24h-22.016v5.461l-3.083-5.461H228.77v5.461l-2.831-5.461h-30.515\n\tc-5.108,0-9.598,0.713-13.225,2.7v-2.7h-21.058v2.7c-2.308-2.048-5.453-2.7-8.95-2.7H75.258l-5.162,11.943l-5.301-11.943H40.563\n\tv5.461l-2.662-5.461H17.235l-9.597,21.985V150.86z\"\n />\n <path\n fill=\"#FFFFFF\"\n d=\"M289.584,175.315h-14.443c-1.442,0-2.4,0.054-3.207,0.599c-0.836,0.537-1.158,1.334-1.158,2.386\n\tc0,1.251,0.706,2.102,1.733,2.47c0.836,0.291,1.734,0.376,3.054,0.376l4.295,0.115c4.334,0.107,7.227,0.852,8.991,2.669\n\tc0.321,0.253,0.514,0.537,0.735,0.821 M289.584,197.178c-1.925,2.815-5.676,4.242-10.754,4.242h-15.304v-7.111h15.242\n\tc1.512,0,2.57-0.199,3.207-0.821c0.552-0.513,0.937-1.258,0.937-2.163c0-0.966-0.385-1.733-0.968-2.193\n\tc-0.575-0.506-1.412-0.736-2.792-0.736c-7.441-0.253-16.724,0.23-16.724-10.264c0-4.81,3.054-9.873,11.37-9.873h15.785v-6.598\n\th-14.666c-4.426,0-7.641,1.06-9.918,2.708v-2.708h-21.693c-3.469,0-7.541,0.86-9.467,2.708v-2.708h-38.738v2.708\n\tc-3.083-2.224-8.285-2.708-10.686-2.708h-25.552v2.708c-2.439-2.362-7.863-2.708-11.169-2.708h-28.597l-6.544,7.082l-6.129-7.082\n\tH63.706v46.272h41.914l6.743-7.194l6.352,7.194l25.836,0.023v-10.885h2.54c3.428,0.053,7.471-0.085,11.038-1.627v12.488h21.31\n\tv-12.06h1.028c1.312,0,1.441,0.054,1.441,1.365v10.694h64.736c4.11,0,8.406-1.052,10.785-2.961v2.961h20.534\n\tc4.273,0,8.446-0.599,11.621-2.133V197.178z M257.973,183.93c1.543,1.597,2.37,3.613,2.37,7.026c0,7.134-4.457,10.464-12.449,10.464\n\th-15.435v-7.111h15.373c1.503,0,2.569-0.199,3.237-0.821c0.545-0.513,0.936-1.258,0.936-2.163c0-0.966-0.423-1.733-0.967-2.193\n\tc-0.606-0.506-1.442-0.736-2.822-0.736c-7.411-0.253-16.692,0.23-16.692-10.264c0-4.81,3.022-9.873,11.33-9.873h15.887v7.058\n\th-14.537c-1.441,0-2.378,0.054-3.175,0.599c-0.868,0.537-1.19,1.334-1.19,2.386c0,1.251,0.737,2.102,1.734,2.47\n\tc0.836,0.291,1.734,0.376,3.084,0.376l4.266,0.115C253.225,181.368,256.178,182.112,257.973,183.93z M186.465,181.882\n\tc-1.06,0.629-2.371,0.683-3.913,0.683h-9.627v-7.448h9.758c1.411,0,2.823,0.03,3.782,0.599c1.027,0.537,1.641,1.564,1.641,2.983\n\tS187.492,181.261,186.465,181.882z M191.251,186.009c1.764,0.651,3.206,1.818,3.882,2.784c1.119,1.619,1.281,3.13,1.313,6.053v6.574\n\th-7.956v-4.149c0-1.995,0.192-4.949-1.281-6.491c-1.158-1.188-2.923-1.472-5.814-1.472h-8.469v12.112h-7.963v-33.162h18.296\n\tc4.012,0,6.934,0.177,9.535,1.565c2.501,1.511,4.074,3.581,4.074,7.364C196.867,182.48,193.337,185.181,191.251,186.009z\n\t M201.262,168.258h26.449v6.858h-18.557v6.029h18.104v6.766h-18.104v6.598l18.557,0.03v6.881h-26.449V168.258z M147.795,183.562\n\th-10.241v-8.445h10.333c2.861,0,4.847,1.166,4.847,4.066C152.734,182.051,150.84,183.562,147.795,183.562z M129.661,198.404\n\tl-12.167-13.508l12.167-13.079V198.404z M98.24,194.509H78.756v-6.598h17.398v-6.766H78.756v-6.029h19.868l8.668,9.664\n\tL98.24,194.509z M161.242,179.183c0,9.212-6.873,11.114-13.8,11.114h-9.888v11.123h-15.403l-9.758-10.978l-10.141,10.978h-31.39\n\tv-33.162h31.873l9.75,10.87l10.08-10.87h25.322C154.176,168.258,161.242,169.999,161.242,179.183z\"\n />\n </svg>\n )\n}\n\n// A fixed plate keeps every row's leading edge aligned whatever the mark's\n// aspect ratio.\nexport function CardBrandPlate({\n brand,\n fallback,\n className,\n}: {\n brand?: string\n fallback: string\n className?: string\n}) {\n const resolved = resolveCardBrand(brand)\n return (\n <span\n aria-hidden\n className={cn(\n \"grid h-7 w-11 shrink-0 place-items-center overflow-hidden rounded-md\",\n // White ground only because the marks are drawn for light surfaces —\n // on a light page it simply disappears and the mark stands alone.\n resolved\n ? \"bg-white\"\n : \"bg-muted text-[10px] font-semibold tracking-wide text-muted-foreground uppercase\",\n className\n )}\n >\n {resolved === \"visa\" ? (\n <VisaMark />\n ) : resolved === \"mastercard\" ? (\n <MastercardMark />\n ) : resolved === \"amex\" ? (\n <AmexMark />\n ) : (\n fallback\n )}\n </span>\n )\n}\n","\"use client\"\n\nimport * as React from \"react\"\nimport { AlertDialog as AlertDialogPrimitive } from \"@base-ui/react/alert-dialog\"\nimport { cn } from \"cn\"\n\nimport { Button } from \"#orck/components/ui/button\"\n\nfunction AlertDialog({ ...props }: AlertDialogPrimitive.Root.Props) {\n return <AlertDialogPrimitive.Root data-slot=\"alert-dialog\" {...props} />\n}\n\nfunction AlertDialogTrigger({ ...props }: AlertDialogPrimitive.Trigger.Props) {\n return (\n <AlertDialogPrimitive.Trigger data-slot=\"alert-dialog-trigger\" {...props} />\n )\n}\n\nfunction AlertDialogPortal({ ...props }: AlertDialogPrimitive.Portal.Props) {\n return (\n <AlertDialogPrimitive.Portal data-slot=\"alert-dialog-portal\" {...props} />\n )\n}\n\nfunction AlertDialogOverlay({\n className,\n ...props\n}: AlertDialogPrimitive.Backdrop.Props) {\n return (\n <AlertDialogPrimitive.Backdrop\n data-slot=\"alert-dialog-overlay\"\n className={cn(\n \"fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction AlertDialogContent({\n className,\n size = \"default\",\n ...props\n}: AlertDialogPrimitive.Popup.Props & {\n size?: \"default\" | \"sm\"\n}) {\n return (\n <AlertDialogPortal>\n <AlertDialogOverlay />\n <AlertDialogPrimitive.Popup\n data-slot=\"alert-dialog-content\"\n data-size={size}\n className={cn(\n \"group/alert-dialog-content fixed top-1/2 left-1/2 z-50 grid w-full -translate-x-1/2 -translate-y-1/2 gap-6 rounded-xl bg-popover p-6 text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none data-[size=default]:max-w-xs data-[size=sm]:max-w-xs data-[size=default]:sm:max-w-lg data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95\",\n className\n )}\n {...props}\n />\n </AlertDialogPortal>\n )\n}\n\nfunction AlertDialogHeader({\n className,\n ...props\n}: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"alert-dialog-header\"\n className={cn(\n \"grid grid-rows-[auto_1fr] place-items-center gap-1.5 text-center has-data-[slot=alert-dialog-media]:grid-rows-[auto_auto_1fr] has-data-[slot=alert-dialog-media]:gap-x-6 sm:group-data-[size=default]/alert-dialog-content:place-items-start sm:group-data-[size=default]/alert-dialog-content:text-left sm:group-data-[size=default]/alert-dialog-content:has-data-[slot=alert-dialog-media]:grid-rows-[auto_1fr]\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction AlertDialogFooter({\n className,\n ...props\n}: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"alert-dialog-footer\"\n className={cn(\n \"flex flex-col-reverse gap-2 group-data-[size=sm]/alert-dialog-content:grid group-data-[size=sm]/alert-dialog-content:grid-cols-2 sm:flex-row sm:justify-end\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction AlertDialogMedia({\n className,\n ...props\n}: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"alert-dialog-media\"\n className={cn(\n \"mb-2 inline-flex size-16 items-center justify-center rounded-md bg-muted sm:group-data-[size=default]/alert-dialog-content:row-span-2 *:[svg:not([class*='size-'])]:size-8\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction AlertDialogTitle({\n className,\n ...props\n}: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {\n return (\n <AlertDialogPrimitive.Title\n data-slot=\"alert-dialog-title\"\n className={cn(\n \"text-lg font-medium sm:group-data-[size=default]/alert-dialog-content:group-has-data-[slot=alert-dialog-media]/alert-dialog-content:col-start-2\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction AlertDialogDescription({\n className,\n ...props\n}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {\n return (\n <AlertDialogPrimitive.Description\n data-slot=\"alert-dialog-description\"\n className={cn(\n \"text-sm text-balance text-muted-foreground md:text-pretty *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction AlertDialogAction({\n className,\n ...props\n}: React.ComponentProps<typeof Button>) {\n return (\n <Button\n data-slot=\"alert-dialog-action\"\n className={cn(className)}\n {...props}\n />\n )\n}\n\nfunction AlertDialogCancel({\n className,\n variant = \"outline\",\n size = \"default\",\n ...props\n}: AlertDialogPrimitive.Close.Props &\n Pick<React.ComponentProps<typeof Button>, \"variant\" | \"size\">) {\n return (\n <AlertDialogPrimitive.Close\n data-slot=\"alert-dialog-cancel\"\n className={cn(className)}\n render={<Button variant={variant} size={size} />}\n {...props}\n />\n )\n}\n\nexport {\n AlertDialog,\n AlertDialogAction,\n AlertDialogCancel,\n AlertDialogContent,\n AlertDialogDescription,\n AlertDialogFooter,\n AlertDialogHeader,\n AlertDialogMedia,\n AlertDialogOverlay,\n AlertDialogPortal,\n AlertDialogTitle,\n AlertDialogTrigger,\n}\n","import * as React from \"react\"\nimport { Dialog as DialogPrimitive } from \"@base-ui/react/dialog\"\nimport { cn } from \"cn\"\n\nimport { Button } from \"#orck/components/ui/button\"\nimport { HugeiconsIcon } from \"@hugeicons/react\"\nimport { Cancel01Icon } from \"@hugeicons/core-free-icons\"\n\nfunction Dialog({ ...props }: DialogPrimitive.Root.Props) {\n return <DialogPrimitive.Root data-slot=\"dialog\" {...props} />\n}\n\nfunction DialogTrigger({ ...props }: DialogPrimitive.Trigger.Props) {\n return <DialogPrimitive.Trigger data-slot=\"dialog-trigger\" {...props} />\n}\n\nfunction DialogPortal({ ...props }: DialogPrimitive.Portal.Props) {\n return <DialogPrimitive.Portal data-slot=\"dialog-portal\" {...props} />\n}\n\nfunction DialogClose({ ...props }: DialogPrimitive.Close.Props) {\n return <DialogPrimitive.Close data-slot=\"dialog-close\" {...props} />\n}\n\nfunction DialogOverlay({\n className,\n ...props\n}: DialogPrimitive.Backdrop.Props) {\n return (\n <DialogPrimitive.Backdrop\n data-slot=\"dialog-overlay\"\n className={cn(\n \"fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction DialogContent({\n className,\n children,\n showCloseButton = true,\n ...props\n}: DialogPrimitive.Popup.Props & {\n showCloseButton?: boolean\n}) {\n return (\n <DialogPortal>\n <DialogOverlay />\n <DialogPrimitive.Popup\n data-slot=\"dialog-content\"\n className={cn(\n \"fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-6 rounded-xl bg-popover p-6 text-sm text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none sm:max-w-md data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95\",\n className\n )}\n {...props}\n >\n {children}\n {showCloseButton && (\n <DialogPrimitive.Close\n data-slot=\"dialog-close\"\n render={\n <Button\n variant=\"ghost\"\n className=\"absolute top-4 right-4\"\n size=\"icon-sm\"\n />\n }\n >\n <HugeiconsIcon icon={Cancel01Icon} strokeWidth={2} />\n <span className=\"sr-only\">Close</span>\n </DialogPrimitive.Close>\n )}\n </DialogPrimitive.Popup>\n </DialogPortal>\n )\n}\n\nfunction DialogHeader({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"dialog-header\"\n className={cn(\"flex flex-col gap-2\", className)}\n {...props}\n />\n )\n}\n\nfunction DialogFooter({\n className,\n showCloseButton = false,\n children,\n ...props\n}: React.ComponentProps<\"div\"> & {\n showCloseButton?: boolean\n}) {\n return (\n <div\n data-slot=\"dialog-footer\"\n className={cn(\n \"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end\",\n className\n )}\n {...props}\n >\n {children}\n {showCloseButton && (\n <DialogPrimitive.Close render={<Button variant=\"outline\" />}>\n Close\n </DialogPrimitive.Close>\n )}\n </div>\n )\n}\n\nfunction DialogTitle({ className, ...props }: DialogPrimitive.Title.Props) {\n return (\n <DialogPrimitive.Title\n data-slot=\"dialog-title\"\n className={cn(\"leading-none font-medium\", className)}\n {...props}\n />\n )\n}\n\nfunction DialogDescription({\n className,\n ...props\n}: DialogPrimitive.Description.Props) {\n return (\n <DialogPrimitive.Description\n data-slot=\"dialog-description\"\n className={cn(\n \"text-sm text-muted-foreground *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground\",\n className\n )}\n {...props}\n />\n )\n}\n\nexport {\n Dialog,\n DialogClose,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogOverlay,\n DialogPortal,\n DialogTitle,\n DialogTrigger,\n}\n","import { cn } from \"cn\"\nimport { HugeiconsIcon } from \"@hugeicons/react\"\nimport { Loading03Icon } from \"@hugeicons/core-free-icons\"\n\nimport { useMessages } from \"#orck/i18n/context\"\n\n// Local: HugeiconsIcon props, since its strokeWidth rejects the svg string type.\nfunction Spinner({\n className,\n ...props\n}: Omit<React.ComponentProps<typeof HugeiconsIcon>, \"icon\">) {\n const { t } = useMessages() // Local: i18n \"Loading\" label.\n return (\n <HugeiconsIcon\n icon={Loading03Icon}\n strokeWidth={2}\n data-slot=\"spinner\"\n role=\"status\"\n aria-label={t(\"common.loading\")}\n className={cn(\"size-4 animate-spin\", className)}\n {...props}\n />\n )\n}\n\nexport { Spinner }\n","import * as React from \"react\"\nimport { Input as InputPrimitive } from \"@base-ui/react/input\"\nimport { cn } from \"cn\"\n\nfunction Input({ className, type, ...props }: React.ComponentProps<\"input\">) {\n return (\n <InputPrimitive\n type={type}\n data-slot=\"input\"\n className={cn(\n \"h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-2.5 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40\",\n className\n )}\n {...props}\n />\n )\n}\n\nexport { Input }\n","import * as React from \"react\"\nimport { cn } from \"cn\"\n\nfunction Label({ className, ...props }: React.ComponentProps<\"label\">) {\n return (\n <label\n data-slot=\"label\"\n className={cn(\n \"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50\",\n className\n )}\n {...props}\n />\n )\n}\n\nexport { Label }\n","import { z } from \"zod\"\n\nconst ISO_COUNTRY_CODES =\n \"AD AE AF AG AI AL AM AO AQ AR AS AT AU AW AX AZ BA BB BD BE BF BG BH BI BJ BL BM BN BO BQ BR BS BT BV BW BY BZ CA CC CD CF CG CH CI CK CL CM CN CO CR CU CV CW CX CY CZ DE DJ DK DM DO DZ EC EE EG EH ER ES ET FI FJ FK FM FO FR GA GB GD GE GF GG GH GI GL GM GN GP GQ GR GS GT GU GW GY HK HM HN HR HT HU ID IE IL IM IN IO IQ IR IS IT JE JM JO JP KE KG KH KI KM KN KP KR KW KY KZ LA LB LC LI LK LR LS LT LU LV LY MA MC MD ME MF MG MH MK ML MM MN MO MP MQ MR MS MT MU MV MW MX MY MZ NA NC NE NF NG NI NL NO NP NR NU NZ OM PA PE PF PG PH PK PL PM PN PR PS PT PW PY QA RE RO RS RU RW SA SB SC SD SE SG SH SI SJ SK SL SM SN SO SR SS ST SV SX SY SZ TC TD TF TG TH TJ TK TL TM TN TO TR TT TV TW TZ UA UG UM US UY UZ VA VC VE VG VI VN VU WF WS YE YT ZA ZM ZW\".split(\n \" \"\n )\n\n// ISO-3166 alpha-2 projection of the UPU's \"List of countries which do not\n// require postal codes\" (Universal DataBase, September 2025). Keep a postal\n// code when a customer supplies one, but do not block tokenization when the\n// destination does not require it.\n// https://www.upu.int/UPU/media/upu/documents/PostCode/General-Addressing-Issues.pdf\nconst POSTAL_OPTIONAL_COUNTRIES = new Set([\n \"AE\",\n \"AG\",\n \"AO\",\n \"AQ\",\n \"AW\",\n \"BF\",\n \"BI\",\n \"BJ\",\n \"BO\",\n \"BQ\",\n \"BS\",\n \"BV\",\n \"BW\",\n \"BZ\",\n \"CF\",\n \"CG\",\n \"CI\",\n \"CK\",\n \"CM\",\n \"CW\",\n \"DM\",\n \"ER\",\n \"FJ\",\n \"GA\",\n \"GD\",\n \"GM\",\n \"GQ\",\n \"JM\",\n \"KM\",\n \"KP\",\n \"LY\",\n \"ML\",\n \"MR\",\n \"QA\",\n \"RW\",\n \"SB\",\n \"SC\",\n \"SL\",\n \"SO\",\n \"SR\",\n \"SS\",\n \"ST\",\n \"SX\",\n \"SY\",\n \"TD\",\n \"TG\",\n \"TK\",\n \"TO\",\n \"TV\",\n \"UM\",\n \"VU\",\n \"YE\",\n \"ZW\",\n])\n\nconst POSTAL_PLACEHOLDERS: Record<string, string> = {\n AR: \"C1000\",\n BR: \"01000-000\",\n CA: \"A1A 1A1\",\n CL: \"8320000\",\n CN: \"100000\",\n CO: \"110111\",\n DE: \"10115\",\n ES: \"28001\",\n JP: \"100-0001\",\n KR: \"04524\",\n MX: \"01000\",\n PE: \"15001\",\n US: \"12345\",\n}\n\nconst displayNames = new Intl.DisplayNames([\"en\"], { type: \"region\" })\n\nexport const COUNTRY_OPTIONS = ISO_COUNTRY_CODES.map((code) => ({\n code,\n name: displayNames.of(code) ?? code,\n})).sort((left, right) => left.name.localeCompare(right.name))\n\nexport const nameOnCardSchema = z\n .string()\n .trim()\n .min(1, \"Name on card is required\")\n .max(200, \"Name on card is too long\")\n\nexport const countryCodeSchema = z\n .string()\n .trim()\n .regex(/^[A-Za-z]{2}$/, \"Select a country\")\n .transform((value) => value.toUpperCase())\n\nexport function isPostalRequired(country: string): boolean {\n const code = country.trim().toUpperCase()\n return code === \"\" || !POSTAL_OPTIONAL_COUNTRIES.has(code)\n}\n\nexport function postalField(\n country: string,\n required: boolean\n): {\n label: string\n placeholder: string\n inputMode: \"numeric\" | \"text\"\n pattern?: string\n} {\n const code = country.trim().toUpperCase()\n const baseLabel =\n code === \"US\"\n ? \"ZIP code\"\n : code === \"GB\" || code === \"AU\" || code === \"NZ\"\n ? \"Postcode\"\n : \"Postal code\"\n return {\n label: required ? baseLabel : `${baseLabel} (optional)`,\n placeholder: POSTAL_PLACEHOLDERS[code] ?? baseLabel,\n inputMode: code === \"US\" ? \"numeric\" : \"text\",\n pattern: code === \"US\" ? \"[0-9]{5}(?:-[0-9]{4})?\" : undefined,\n }\n}\n\nexport const nmiBillingSchema = z\n .object({\n name_on_card: nameOnCardSchema,\n country: countryCodeSchema,\n zip: z.string().trim().max(32, \"Postal code is too long\"),\n })\n .superRefine((value, context) => {\n if (isPostalRequired(value.country) && !value.zip) {\n context.addIssue({\n code: \"custom\",\n message: `${postalField(value.country, true).label} is required`,\n path: [\"zip\"],\n })\n }\n if (\n value.country === \"US\" &&\n value.zip &&\n !/^\\d{5}(?:-\\d{4})?$/.test(value.zip)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"Enter a valid ZIP code\",\n path: [\"zip\"],\n })\n }\n })\n\nexport type NMIBilling = z.infer<typeof nmiBillingSchema>\n\n/** A card form's billing fields as a saved card's billing details. */\nexport function billingDetailsOf(billing: {\n name_on_card?: string\n email?: string\n zip?: string\n country?: string\n}) {\n const address = {\n ...(billing.zip ? { postal_code: billing.zip } : {}),\n ...(billing.country ? { country: billing.country } : {}),\n }\n return {\n ...(billing.name_on_card ? { name: billing.name_on_card } : {}),\n ...(billing.email ? { email: billing.email } : {}),\n ...(Object.keys(address).length > 0 ? { address } : {}),\n }\n}\n\nexport const emptyNMIBilling: NMIBilling = {\n name_on_card: \"\",\n country: \"\",\n zip: \"\",\n}\n\n/** The buyer's likely billing country from the browser locale, or \"\". */\nexport function browserCountry(): string {\n try {\n if (typeof navigator === \"undefined\" || !navigator.language) return \"\"\n const region = new Intl.Locale(navigator.language).maximize().region\n return region && /^[A-Z]{2}$/.test(region) ? region : \"\"\n } catch {\n return \"\"\n }\n}\n\n/** The host's country when it is a known code, else the browser's region. */\nexport function initialCountry(hostCountry?: string): string {\n const code = hostCountry?.trim().toUpperCase() ?? \"\"\n if (COUNTRY_OPTIONS.some((option) => option.code === code)) return code\n const region = browserCountry()\n return COUNTRY_OPTIONS.some((option) => option.code === region) ? region : \"\"\n}\n","import type * as React from \"react\"\n\nimport { Input } from \"#orck/components/ui/input\"\nimport { Label } from \"#orck/components/ui/label\"\nimport {\n COUNTRY_OPTIONS,\n isPostalRequired,\n postalField,\n type NMIBilling,\n} from \"#orck/lib/billing\"\n\nconst LABEL = \"text-[13px] font-medium text-foreground\"\nconst CONTROL =\n \"h-[38px] rounded-[9px] border border-input bg-card text-sm text-foreground\"\nconst INPUT = `${CONTROL} px-2.5`\n\nexport function BillingTextField({\n id,\n name,\n label,\n value,\n onChange,\n autoComplete,\n placeholder,\n disabled,\n maxLength,\n required,\n type,\n inputMode,\n pattern,\n}: {\n id: string\n name: string\n label: string\n value: string\n onChange: (value: string) => void\n autoComplete: string\n placeholder?: string\n disabled?: boolean\n maxLength?: number\n required?: boolean\n type?: React.HTMLInputTypeAttribute\n inputMode?: React.HTMLAttributes<HTMLInputElement>[\"inputMode\"]\n pattern?: string\n}) {\n return (\n <div className=\"grid gap-1.5\">\n <Label htmlFor={id} className={LABEL}>\n {label}\n </Label>\n <Input\n id={id}\n name={name}\n type={type}\n className={INPUT}\n value={value}\n autoComplete={autoComplete}\n placeholder={placeholder}\n disabled={disabled}\n maxLength={maxLength}\n required={required}\n inputMode={inputMode}\n pattern={pattern}\n onChange={(event) => onChange(event.target.value)}\n />\n </div>\n )\n}\n\nexport function CountryField({\n id,\n value,\n onChange,\n disabled,\n}: {\n id: string\n value: string\n onChange: (value: string) => void\n disabled?: boolean\n}) {\n return (\n <div className=\"grid gap-1.5\">\n <Label htmlFor={id} className={LABEL}>\n Country\n </Label>\n <select\n id={id}\n name=\"country\"\n className={`${CONTROL} w-full px-2.5`}\n value={value}\n autoComplete=\"billing country\"\n disabled={disabled}\n required\n onChange={(event) => onChange(event.target.value)}\n >\n <option value=\"\">Select country</option>\n {COUNTRY_OPTIONS.map((country) => (\n <option key={country.code} value={country.code}>\n {country.name}\n </option>\n ))}\n </select>\n </div>\n )\n}\n\nexport function PostalField({\n id,\n value,\n country,\n onChange,\n disabled,\n required,\n error,\n}: {\n id: string\n value: string\n country: string\n onChange: (value: string) => void\n disabled?: boolean\n required: boolean\n error?: string\n}) {\n const field = postalField(country, required)\n return (\n <div className=\"grid gap-1.5\">\n <BillingTextField\n id={id}\n name=\"zip\"\n label={field.label}\n value={value}\n onChange={onChange}\n autoComplete=\"billing postal-code\"\n placeholder={field.placeholder}\n disabled={disabled}\n maxLength={32}\n required={required}\n inputMode={field.inputMode}\n pattern={field.pattern}\n />\n {error ? (\n <p className=\"text-[12.5px] text-destructive\" role=\"alert\">\n {error}\n </p>\n ) : null}\n </div>\n )\n}\n\nexport function CardBillingFields({\n idPrefix,\n value,\n onChange,\n disabled,\n postalError,\n}: {\n idPrefix: string\n value: NMIBilling\n onChange: (next: NMIBilling) => void\n disabled?: boolean\n postalError?: string\n}) {\n const set = (key: keyof NMIBilling) => (next: string) =>\n onChange({ ...value, [key]: next })\n const postalRequired = isPostalRequired(value.country)\n return (\n <div className=\"grid gap-3\">\n <BillingTextField\n id={`${idPrefix}-name-on-card`}\n name=\"name_on_card\"\n label=\"Name on card\"\n value={value.name_on_card}\n onChange={set(\"name_on_card\")}\n autoComplete=\"cc-name\"\n placeholder=\"Name as shown on card\"\n disabled={disabled}\n maxLength={200}\n required\n />\n <div className=\"grid grid-cols-2 gap-3\">\n <CountryField\n id={`${idPrefix}-country`}\n value={value.country}\n onChange={set(\"country\")}\n disabled={disabled}\n />\n <PostalField\n id={`${idPrefix}-postal-code`}\n value={value.zip}\n country={value.country}\n onChange={set(\"zip\")}\n disabled={disabled}\n required={postalRequired}\n error={postalError}\n />\n </div>\n </div>\n )\n}\n","// Card entry for the NMI rail. Live mode mounts Collect.js hosted iframes\n// into these containers (card data never touches our code); preview mode\n// (fixture tokenization keys) renders inert placeholders with the same\n// geometry so every state is designable without a gateway. A PSP that takes\n// cards on OpenRails itself gets NativeCardFields instead.\nimport type * as React from \"react\"\n\nimport { Label } from \"#orck/components/ui/label\"\nimport type { CardEntryState } from \"#orck/lib/card-entry\"\nimport type { CollectFieldErrors } from \"#orck/lib/collect\"\nimport { cn } from \"cn\"\n\nfunction FieldError({ id, message }: { id: string; message?: string }) {\n return message ? (\n <p id={id} className=\"text-[12.5px] text-destructive\" role=\"alert\">\n {message}\n </p>\n ) : null\n}\n\nconst FIELD =\n \"orck-collect-field h-[38px] overflow-hidden rounded-[9px] border border-[color:var(--border)] bg-card px-[3px]\"\nconst PREVIEW_FIELD =\n \"flex h-[38px] items-center rounded-[9px] border border-[color:var(--border)] bg-card px-[11px] text-sm text-[color:var(--orck-faint)] tabular-nums\"\n\nexport interface CardFieldIds {\n number: string\n expiry: string\n cvv: string\n}\n\nexport function CardFields({\n ids,\n preview,\n error,\n fieldErrors = {},\n hidden,\n}: {\n ids: CardFieldIds\n preview: boolean\n error?: string\n /** Inline per-field errors (gateway validation or a decline). */\n fieldErrors?: CollectFieldErrors\n // Kept mounted while hidden: the Collect.js iframes cannot be recreated\n // cheaply, so switching to a stored card must not unmount them.\n hidden?: boolean\n}) {\n return (\n <div\n className={cn(\"grid gap-3\", hidden && \"hidden\")}\n aria-hidden={hidden || undefined}\n >\n <div className=\"grid gap-1.5\">\n <Label\n htmlFor={ids.number}\n className=\"text-[13px] font-medium text-foreground\"\n >\n Card number\n </Label>\n {preview ? (\n <div id={ids.number} className={PREVIEW_FIELD}>\n 1234 1234 1234 1234\n </div>\n ) : (\n <div\n id={ids.number}\n className={cn(FIELD, fieldErrors.number && \"border-destructive\")}\n />\n )}\n <FieldError id={`${ids.number}-error`} message={fieldErrors.number} />\n </div>\n <div className=\"grid grid-cols-2 gap-3\">\n <div className=\"grid gap-1.5\">\n <Label\n htmlFor={ids.expiry}\n className=\"text-[13px] font-medium text-foreground\"\n >\n Expiry\n </Label>\n {preview ? (\n <div id={ids.expiry} className={PREVIEW_FIELD}>\n MM / YY\n </div>\n ) : (\n <div\n id={ids.expiry}\n className={cn(FIELD, fieldErrors.expiry && \"border-destructive\")}\n />\n )}\n <FieldError id={`${ids.expiry}-error`} message={fieldErrors.expiry} />\n </div>\n <div className=\"grid gap-1.5\">\n <Label\n htmlFor={ids.cvv}\n className=\"text-[13px] font-medium text-foreground\"\n >\n CVC\n </Label>\n {preview ? (\n <div id={ids.cvv} className={PREVIEW_FIELD}>\n CVC\n </div>\n ) : (\n <div\n id={ids.cvv}\n className={cn(FIELD, fieldErrors.cvv && \"border-destructive\")}\n />\n )}\n <FieldError id={`${ids.cvv}-error`} message={fieldErrors.cvv} />\n </div>\n </div>\n {error ? (\n <p className={cn(\"text-[13px] text-destructive\")} role=\"alert\">\n {error}\n </p>\n ) : null}\n </div>\n )\n}\n\nconst NATIVE_FIELD =\n \"h-[38px] w-full min-w-0 rounded-[9px] border border-[color:var(--border)] bg-card px-[11px] text-sm text-foreground tabular-nums outline-none placeholder:text-[color:var(--orck-faint)] focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:opacity-50\"\n\n/**\n * Card entry for a PSP that takes cards on OpenRails itself (driver \"card\"):\n * plain inputs in the same layout as the Collect.js containers. The card is\n * posted to OpenRails; no gateway script is loaded.\n */\nexport function NativeCardFields({\n ids,\n card,\n fieldErrors = {},\n disabled,\n hidden,\n}: {\n ids: CardFieldIds\n card: CardEntryState\n /** Inline errors beyond the form's own (a decline naming a field). */\n fieldErrors?: CollectFieldErrors\n disabled?: boolean\n hidden?: boolean\n}) {\n const errors = { ...card.fieldErrors, ...fieldErrors }\n const field = (\n id: string,\n name: \"number\" | \"expiry\" | \"cvc\",\n error: string | undefined,\n props: React.ComponentProps<\"input\">\n ) => (\n <>\n <input\n id={id}\n name={`card-${name}`}\n className={cn(NATIVE_FIELD, error && \"border-destructive\")}\n value={card.input[name]}\n onChange={(event) => card.change(name, event.target.value)}\n onBlur={() => card.leave(name)}\n inputMode=\"numeric\"\n spellCheck={false}\n disabled={disabled}\n required\n aria-invalid={error ? true : undefined}\n aria-describedby={error ? `${id}-error` : undefined}\n {...props}\n />\n <FieldError id={`${id}-error`} message={error} />\n </>\n )\n return (\n <div\n className={cn(\"grid gap-3\", hidden && \"hidden\")}\n aria-hidden={hidden || undefined}\n >\n <div className=\"grid gap-1.5\">\n <Label\n htmlFor={ids.number}\n className=\"text-[13px] font-medium text-foreground\"\n >\n Card number\n </Label>\n {field(ids.number, \"number\", errors.number, {\n autoComplete: \"cc-number\",\n placeholder: \"1234 1234 1234 1234\",\n maxLength: 23,\n })}\n </div>\n <div className=\"grid grid-cols-2 gap-3\">\n <div className=\"grid gap-1.5\">\n <Label\n htmlFor={ids.expiry}\n className=\"text-[13px] font-medium text-foreground\"\n >\n Expiry\n </Label>\n {field(ids.expiry, \"expiry\", errors.expiry, {\n autoComplete: \"cc-exp\",\n placeholder: \"MM / YY\",\n maxLength: 7,\n })}\n </div>\n <div className=\"grid gap-1.5\">\n <Label\n htmlFor={ids.cvv}\n className=\"text-[13px] font-medium text-foreground\"\n >\n CVC\n </Label>\n {field(ids.cvv, \"cvc\", errors.cvv, {\n autoComplete: \"cc-csc\",\n placeholder: \"CVC\",\n maxLength: 4,\n })}\n </div>\n </div>\n </div>\n )\n}\n","// The one bold element on the surface: the ink button carrying the amount.\n// Redirect rails relabel it; Solana has no button at all.\nimport { Button } from \"#orck/components/ui/button\"\nimport { cn } from \"cn\"\n\nexport function PayButton({\n label,\n processing,\n disabled,\n}: {\n label: string\n processing: boolean\n disabled?: boolean\n}) {\n return (\n <Button\n type=\"submit\"\n className={cn(\n \"h-[42px] w-full rounded-[10px] text-sm font-semibold tabular-nums\",\n processing && \"opacity-75\"\n )}\n disabled={disabled || processing}\n >\n {processing ? (\n <>\n <span\n aria-hidden\n className=\"size-3.5 animate-spin rounded-full border-2 border-[color:var(--primary-foreground)]/35 border-t-[color:var(--primary-foreground)] motion-reduce:animate-none\"\n />\n Processing…\n </>\n ) : (\n label\n )}\n </Button>\n )\n}\n\nexport function TrustLine() {\n return (\n <div className=\"-mt-1 flex items-center justify-center gap-1.5 text-xs text-[color:var(--orck-faint)]\">\n <svg\n viewBox=\"0 0 16 16\"\n fill=\"currentColor\"\n aria-hidden\n className=\"size-[11px]\"\n >\n <path d=\"M8 1a3.5 3.5 0 0 0-3.5 3.5V6H4a1.5 1.5 0 0 0-1.5 1.5v5A1.5 1.5 0 0 0 4 14h8a1.5 1.5 0 0 0 1.5-1.5v-5A1.5 1.5 0 0 0 12 6h-.5V4.5A3.5 3.5 0 0 0 8 1Zm2 5H6V4.5a2 2 0 1 1 4 0V6Z\" />\n </svg>\n Secured by OpenRails\n </div>\n )\n}\n","// Stripe.js for in-page card setup and payment authentication. Loaded on first\n// use, so hosts without a Stripe PSP never fetch it.\nimport type { Stripe } from \"@stripe/stripe-js\"\n\nconst loaded = new Map<string, Promise<Stripe>>()\n\nexport function loadStripeFor(publishableKey: string): Promise<Stripe> {\n let stripe = loaded.get(publishableKey)\n if (!stripe) {\n stripe = import(\"@stripe/stripe-js\")\n .then(({ loadStripe }) => loadStripe(publishableKey))\n .then((value) => {\n if (!value) throw new Error(\"Stripe could not be loaded.\")\n return value\n })\n stripe.catch(() => loaded.delete(publishableKey))\n loaded.set(publishableKey, stripe)\n }\n return stripe\n}\n","// Collect.js (NMI browser tokenization). The gateway script mounts hosted\n// iframes into our field containers, so card data never touches this code —\n// we receive a one-time token plus display metadata. Collect.js has no\n// teardown API: the script and configuration persist for the page lifetime;\n// reconfiguring re-mounts fields.\nimport * as React from \"react\"\n\nexport interface CollectCard {\n number?: string\n type?: string\n exp?: string\n}\n\nexport interface CollectResponse {\n token: string\n card?: CollectCard\n}\n\ndeclare global {\n interface Window {\n CollectJS?: {\n configure: (config: Record<string, unknown>) => void\n startPaymentRequest: () => void\n }\n }\n}\n\nconst SCRIPT_ID = \"openrails-collectjs\"\nconst TIMEOUT_MS = 30_000\nconst collectScriptStates = new WeakMap<\n HTMLScriptElement,\n \"loading\" | \"loaded\" | \"failed\"\n>()\n\nfunction safeCollectScriptURL(raw: string): string | undefined {\n try {\n const parsed = new URL(raw)\n if (\n parsed.protocol !== \"https:\" ||\n parsed.username ||\n parsed.password ||\n parsed.hash\n ) {\n return undefined\n }\n return parsed.toString()\n } catch {\n return undefined\n }\n}\n\n// toPlainColor normalizes a CSS color into rgb()/rgba() form, the least\n// common denominator the gateway's CSS sanitizer accepts. Chrome serializes\n// the theme tokens in their authored oklch space (canvas fillStyle keeps it\n// too), so oklch is converted numerically; everything else round-trips\n// through a canvas fillStyle. Unparseable input returns \"\".\nexport function toPlainColor(value: string | undefined): string {\n if (!value) return \"\"\n const oklch = oklchToRGB(value)\n if (oklch) return oklch\n try {\n const context = document.createElement(\"canvas\").getContext(\"2d\")\n if (!context) return \"\"\n context.fillStyle = \"#010203\"\n context.fillStyle = value\n const normalized = context.fillStyle\n if (normalized === \"#010203\" && value !== \"#010203\") return \"\"\n return normalized.startsWith(\"oklch\") ? \"\" : normalized\n } catch {\n return \"\"\n }\n}\n\n// oklchToRGB converts \"oklch(L C H)\" / \"oklch(L C H / A)\" (L as 0..1 or %)\n// to an rgb()/rgba() string via OKLab → linear sRGB (Ottosson's matrices).\nfunction oklchToRGB(value: string): string {\n const match =\n /^oklch\\(\\s*([\\d.]+%?)\\s+([\\d.]+)\\s+([\\d.]+)(?:deg)?\\s*(?:\\/\\s*([\\d.]+%?)\\s*)?\\)$/i.exec(\n value.trim()\n )\n if (!match) return \"\"\n const number = (raw: string) =>\n raw.endsWith(\"%\") ? parseFloat(raw) / 100 : parseFloat(raw)\n const L = number(match[1])\n const C = parseFloat(match[2])\n const H = (parseFloat(match[3]) * Math.PI) / 180\n const alpha = match[4] === undefined ? 1 : number(match[4])\n const a = C * Math.cos(H)\n const b = C * Math.sin(H)\n const l = (L + 0.3963377774 * a + 0.2158037573 * b) ** 3\n const m = (L - 0.1055613458 * a - 0.0638541728 * b) ** 3\n const s = (L - 0.0894841775 * a - 1.291485548 * b) ** 3\n const channel = (linear: number) => {\n const gamma =\n linear <= 0.0031308\n ? 12.92 * linear\n : 1.055 * Math.max(linear, 0) ** (1 / 2.4) - 0.055\n return Math.round(Math.min(1, Math.max(0, gamma)) * 255)\n }\n const red = channel(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s)\n const green = channel(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s)\n const blue = channel(-0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s)\n return alpha >= 1\n ? `rgb(${red}, ${green}, ${blue})`\n : `rgba(${red}, ${green}, ${blue}, ${alpha})`\n}\n\n// Preview keys skip the live script entirely so fixture-driven previews can\n// render the card fields without a real gateway.\nexport function isPreviewTokenizationKey(key: string): boolean {\n return key.startsWith(\"preview_\")\n}\n\n/** Inline field errors, keyed by our field names. */\nexport interface CollectFieldErrors {\n number?: string\n expiry?: string\n cvv?: string\n}\n\nconst FIELD_NAMES: Record<string, keyof CollectFieldErrors> = {\n ccnumber: \"number\",\n ccexp: \"expiry\",\n cvv: \"cvv\",\n}\n\nconst FIELD_MESSAGES: Record<keyof CollectFieldErrors, string> = {\n number: \"Enter a valid card number\",\n expiry: \"Enter a valid expiry date\",\n cvv: \"Enter a valid security code\",\n}\n\nexport interface CollectFieldSelectors {\n number: string\n expiry: string\n cvv: string\n}\n\nexport function useCollectJS(config: {\n enabled: boolean\n active: boolean\n tokenizationKey: string\n scriptURL: string\n selectors: CollectFieldSelectors\n}): {\n ready: boolean\n preview: boolean\n loadError?: string\n /** Every field reported valid by the gateway. */\n valid: boolean\n fieldErrors: CollectFieldErrors\n tokenize: () => Promise<CollectResponse>\n} {\n const preview =\n config.enabled && isPreviewTokenizationKey(config.tokenizationKey)\n const [ready, setReady] = React.useState(false)\n const [loadError, setLoadError] = React.useState<string>()\n // Validity per field as Collect.js reports it on edit and blur.\n const [validity, setValidity] = React.useState<\n Partial<\n Record<keyof CollectFieldErrors, { valid: boolean; message?: string }>\n >\n >({})\n const pending = React.useRef<\n | {\n resolve: (r: CollectResponse) => void\n reject: (e: Error) => void\n timer: number\n }\n | undefined\n >(undefined)\n const configuredFor = React.useRef<string | undefined>(undefined)\n const { number, expiry, cvv } = config.selectors\n\n React.useEffect(() => {\n if (\n !config.enabled ||\n preview ||\n !config.tokenizationKey ||\n !config.scriptURL ||\n typeof document === \"undefined\"\n ) {\n return\n }\n const scriptURL = safeCollectScriptURL(config.scriptURL)\n if (!scriptURL) {\n void Promise.resolve().then(() => {\n setReady(false)\n setLoadError(\"Card fields failed to load\")\n })\n return\n }\n const configuration = [\n config.tokenizationKey,\n scriptURL,\n number,\n expiry,\n cvv,\n ].join(\"\\u0000\")\n const configurationChanged = configuredFor.current !== configuration\n if (!configurationChanged && !config.active) return\n configuredFor.current = configuration\n\n let canceled = false\n const settle = (fn: () => void) => {\n if (!canceled) fn()\n }\n const configure = () => {\n if (canceled) return\n const collect = window.CollectJS\n if (!collect) {\n settle(() => setLoadError(\"Card fields failed to load\"))\n return\n }\n settle(() => {\n // Replacing stale hosted iframes invalidates readiness until NMI\n // confirms that every new field is available.\n setReady(false)\n setLoadError(undefined)\n setValidity({})\n })\n // The hosted iframes cannot inherit the page theme; hand them the\n // container's resolved colors so dark mode reaches inside the fields.\n // Chrome serializes computed colors in their authored space (oklch),\n // which the gateway's CSS sanitizer drops — normalize through a canvas\n // fillStyle round-trip to a format it accepts. (Resolved once per\n // configure — an in-place OS theme flip re-themes on the next load.)\n const probe = document.querySelector<HTMLElement>(number)\n const probeStyle = probe ? window.getComputedStyle(probe) : undefined\n const probeBackground = toPlainColor(probeStyle?.backgroundColor)\n const fieldBackground =\n probeBackground &&\n probeBackground !== \"transparent\" &&\n probeBackground !== \"rgba(0, 0, 0, 0)\"\n ? probeBackground\n : \"#ffffff\"\n const fieldColor = toPlainColor(probeStyle?.color) || \"#18181b\"\n const placeholderColor =\n toPlainColor(\n probeStyle?.getPropertyValue(\"--muted-foreground\").trim()\n ) || fieldColor\n try {\n collect.configure({\n variant: \"inline\",\n styleSniffer: true,\n customCss: {\n height: \"38px\",\n \"line-height\": \"38px\",\n padding: \"0 8px\",\n \"font-size\": \"14px\",\n \"font-family\": probeStyle?.fontFamily || \"inherit\",\n \"background-color\": fieldBackground,\n color: fieldColor,\n },\n placeholderCss: {\n color: placeholderColor,\n },\n invalidCss: {\n color:\n toPlainColor(\n probeStyle?.getPropertyValue(\"--destructive\").trim()\n ) || \"#dc2626\",\n },\n focusCss: {\n outline: \"none\",\n },\n // Collect.js owns the cross-origin inputs and therefore controls\n // their autocomplete behavior. Titles and placeholders are the\n // accessibility/browser hints its public field API supports.\n fields: {\n ccnumber: {\n selector: number,\n title: \"Card number\",\n placeholder: \"1234 1234 1234 1234\",\n },\n ccexp: {\n selector: expiry,\n title: \"Expiration date\",\n placeholder: \"MM / YY\",\n },\n cvv: {\n selector: cvv,\n title: \"Card security code\",\n placeholder: \"CVC\",\n },\n },\n fieldsAvailableCallback: () => settle(() => setReady(true)),\n validationCallback: (\n field: string,\n status: boolean,\n message: string\n ) => {\n const name = FIELD_NAMES[field]\n if (!name) return\n settle(() =>\n setValidity((current) => ({\n ...current,\n [name]: {\n valid: status,\n message: status\n ? undefined\n : message && message !== \"Field is empty\"\n ? `${FIELD_MESSAGES[name]}.`\n : FIELD_MESSAGES[name],\n },\n }))\n )\n },\n timeoutDuration: TIMEOUT_MS,\n timeoutCallback: () => {\n const request = pending.current\n pending.current = undefined\n if (request) {\n window.clearTimeout(request.timer)\n request.reject(new Error(\"Card entry timed out\"))\n }\n },\n callback: (response: CollectResponse) => {\n const request = pending.current\n pending.current = undefined\n if (request) {\n window.clearTimeout(request.timer)\n request.resolve(response)\n }\n },\n })\n } catch {\n settle(() => setLoadError(\"Card fields failed to load\"))\n }\n }\n let existing = document.getElementById(SCRIPT_ID)\n if (\n existing instanceof HTMLScriptElement &&\n (existing.src !== scriptURL ||\n collectScriptStates.get(existing) === \"failed\")\n ) {\n // A white-label merchant may use a different Collect.js distribution.\n // Never configure one merchant's key against another merchant's script,\n // and allow a later modal open to retry a failed network load.\n existing.remove()\n if (existing.src !== scriptURL) {\n Reflect.deleteProperty(window, \"CollectJS\")\n }\n existing = null\n }\n if (existing instanceof HTMLScriptElement) {\n if (window.CollectJS) {\n configure()\n return () => {\n canceled = true\n }\n }\n if (collectScriptStates.get(existing) === \"loaded\") {\n settle(() => setLoadError(\"Card fields failed to load\"))\n return () => {\n canceled = true\n }\n }\n const failed = () =>\n settle(() => setLoadError(\"Card fields failed to load\"))\n existing.addEventListener(\"load\", configure)\n existing.addEventListener(\"error\", failed)\n return () => {\n canceled = true\n existing.removeEventListener(\"load\", configure)\n existing.removeEventListener(\"error\", failed)\n }\n }\n const script = document.createElement(\"script\")\n script.id = SCRIPT_ID\n script.src = scriptURL\n script.async = true\n script.dataset.tokenizationKey = config.tokenizationKey\n collectScriptStates.set(script, \"loading\")\n script.onload = () => {\n collectScriptStates.set(script, \"loaded\")\n configure()\n }\n script.onerror = () => {\n collectScriptStates.set(script, \"failed\")\n settle(() => setLoadError(\"Card fields failed to load\"))\n }\n document.head.appendChild(script)\n return () => {\n canceled = true\n }\n }, [\n config.enabled,\n config.active,\n preview,\n config.tokenizationKey,\n config.scriptURL,\n number,\n expiry,\n cvv,\n ])\n\n const tokenize = React.useCallback(\n () =>\n new Promise<CollectResponse>((resolve, reject) => {\n if (preview) {\n // Preview sessions demo the full flow; a real backend rejects this\n // token, fixture sources accept it.\n resolve({\n token: \"preview_payment_token\",\n card: { number: \"4242424242424242\", type: \"visa\", exp: \"1227\" },\n })\n return\n }\n const collect = window.CollectJS\n if (!collect || !ready) {\n reject(new Error(\"Card fields are not ready\"))\n return\n }\n if (pending.current) {\n reject(new Error(\"Card entry is already in progress\"))\n return\n }\n const timer = window.setTimeout(() => {\n pending.current = undefined\n reject(new Error(\"Card entry timed out\"))\n }, TIMEOUT_MS + 5_000)\n pending.current = { resolve, reject, timer }\n collect.startPaymentRequest()\n }),\n [preview, ready]\n )\n\n const fieldErrors: CollectFieldErrors = {}\n for (const name of [\"number\", \"expiry\", \"cvv\"] as const) {\n const state = validity[name]\n if (state && !state.valid) fieldErrors[name] = state.message\n }\n const valid =\n preview ||\n ([\"number\", \"expiry\", \"cvv\"] as const).every(\n (name) => validity[name]?.valid === true\n )\n return {\n ready: ready || preview,\n preview,\n loadError,\n valid,\n fieldErrors,\n tokenize,\n }\n}\n\n/** Display metadata of a tokenized card: never the PAN. */\nexport function collectCardDisplay(card?: CollectCard): {\n last_four?: string\n card_type?: string\n expiry_date?: string\n} {\n const digits = (card?.number ?? \"\").replace(/\\D/g, \"\")\n const exp = (card?.exp ?? \"\").replace(/\\D/g, \"\")\n return {\n ...(digits.length >= 4 ? { last_four: digits.slice(-4) } : {}),\n ...(card?.type ? { card_type: card.type } : {}),\n ...(exp.length === 4\n ? { expiry_date: `${exp.slice(0, 2)}/${exp.slice(2)}` }\n : {}),\n }\n}\n","// Stripe Elements appearance from the page's resolved theme tokens, so the\n// Payment Element matches our inputs (height, radius, type, colors).\nimport type { Appearance } from \"@stripe/stripe-js\"\n\nimport { toPlainColor } from \"#orck/lib/collect\"\n\nexport function stripeAppearance(host: HTMLElement): Appearance {\n const style = window.getComputedStyle(host)\n const token = (name: string) =>\n toPlainColor(style.getPropertyValue(name).trim()) || undefined\n const dark = !!host.closest(\".dark\")\n return {\n theme: dark ? \"night\" : \"stripe\",\n variables: {\n colorPrimary: token(\"--primary\"),\n colorBackground: token(\"--card\"),\n colorText: token(\"--foreground\"),\n colorTextSecondary: token(\"--muted-foreground\"),\n colorDanger: token(\"--destructive\"),\n fontFamily: style.fontFamily || undefined,\n fontSizeBase: \"14px\",\n borderRadius: \"9px\",\n spacingUnit: \"3px\",\n },\n rules: {\n \".Input\": {\n padding: \"9px 10px\",\n boxShadow: \"none\",\n borderColor: token(\"--border\") ?? \"\",\n },\n \".Input:focus\": {\n borderColor: token(\"--ring\") ?? \"\",\n boxShadow: \"none\",\n },\n \".Label\": { fontSize: \"13px\", fontWeight: \"500\", marginBottom: \"6px\" },\n \".Error\": { fontSize: \"12.5px\" },\n },\n }\n}\n","// Stripe Payment Element on an OpenRails card setup (SetupIntent). The card\n// lives only in Stripe's frames; save() confirms the setup in the page (3-D\n// Secure included) and returns the saved OpenRails payment method id.\nimport * as React from \"react\"\nimport type {\n Stripe,\n StripeElements,\n StripePaymentElementChangeEvent,\n} from \"@stripe/stripe-js\"\n\nimport type { BillingClient } from \"#orck/client/client\"\nimport type { CardSetup } from \"#orck/client/types\"\nimport { loadStripeFor } from \"#orck/lib/stripe\"\nimport { stripeAppearance } from \"#orck/lib/stripe-appearance\"\nimport type { PspConfig } from \"#orck/psp\"\n\nexport interface StripeCardHandle {\n /** Confirms the setup and returns the saved payment method id. */\n save(): Promise<string>\n}\n\nconst defaultReturnURL = (setupId: string) => {\n const url = new URL(window.location.href)\n url.searchParams.set(\"setup_id\", setupId)\n return url.href\n}\n\nexport const StripeCardEntry = React.forwardRef<\n StripeCardHandle,\n {\n psp: PspConfig\n client: BillingClient\n returnURL?: (setupId: string) => string\n defaultCountry?: string\n /** Completeness of the entered card, from the element's change events. */\n onCompleteChange?: (complete: boolean) => void\n unavailableMessage: string\n verificationPendingMessage: string\n }\n>(function StripeCardEntry(\n {\n psp,\n client,\n returnURL = defaultReturnURL,\n defaultCountry,\n onCompleteChange,\n unavailableMessage,\n verificationPendingMessage,\n },\n ref\n) {\n const [idempotencyKey] = React.useState(() => crypto.randomUUID())\n const [setup, setSetup] = React.useState<CardSetup>()\n const [error, setError] = React.useState<string>()\n const host = React.useRef<HTMLDivElement>(null)\n const mounted = React.useRef<{ stripe: Stripe; elements: StripeElements }>(\n null\n )\n const completeRef = React.useRef(onCompleteChange)\n React.useEffect(() => {\n completeRef.current = onCompleteChange\n })\n\n React.useEffect(() => {\n let canceled = false\n client\n .createCardSetup({ pspId: psp.psp_id, idempotencyKey })\n .then((created) => {\n if (canceled) return\n if (!created.client_secret && !created.payment_method_id)\n throw new Error(unavailableMessage)\n setSetup(created)\n if (created.payment_method_id) completeRef.current?.(true)\n })\n .catch((cause: unknown) => {\n if (!canceled)\n setError(cause instanceof Error ? cause.message : unavailableMessage)\n })\n return () => {\n canceled = true\n }\n }, [client, psp.psp_id, idempotencyKey, unavailableMessage])\n\n const secret = setup?.client_secret\n const publishable = psp.config?.publishable_key\n React.useEffect(() => {\n if (!secret || !publishable || !host.current) return\n let canceled = false\n let unmount: (() => void) | undefined\n void loadStripeFor(publishable).then(\n (stripe) => {\n if (canceled || !host.current) return\n const elements = stripe.elements({\n clientSecret: secret,\n appearance: stripeAppearance(host.current),\n })\n // Cards only: the panel saves a card, so no Link bank or wallets.\n const element = elements.create(\"payment\", {\n wallets: { link: \"never\", applePay: \"never\", googlePay: \"never\" },\n ...(defaultCountry\n ? {\n defaultValues: {\n billingDetails: { address: { country: defaultCountry } },\n },\n }\n : {}),\n })\n element.on(\"change\", (event: StripePaymentElementChangeEvent) => {\n completeRef.current?.(event.complete)\n })\n element.mount(host.current)\n mounted.current = { stripe, elements }\n unmount = () => element.destroy()\n },\n (cause: unknown) => {\n if (!canceled)\n setError(cause instanceof Error ? cause.message : unavailableMessage)\n }\n )\n return () => {\n canceled = true\n mounted.current = null\n unmount?.()\n }\n }, [secret, publishable, defaultCountry, unavailableMessage])\n\n React.useImperativeHandle(\n ref,\n () => ({\n async save() {\n if (setup?.payment_method_id) return setup.payment_method_id\n const current = mounted.current\n if (!setup || !current) throw new Error(unavailableMessage)\n setError(undefined)\n const validation = await current.elements.submit()\n if (validation.error)\n throw new Error(validation.error.message ?? unavailableMessage)\n const result = await current.stripe.confirmSetup({\n elements: current.elements,\n confirmParams: { return_url: returnURL(setup.id) },\n redirect: \"if_required\",\n })\n if (result.error)\n throw new Error(result.error.message ?? unavailableMessage)\n const verified = await client.confirmCardSetup(setup.id)\n if (!verified.payment_method_id)\n throw new Error(verificationPendingMessage)\n return verified.payment_method_id\n },\n }),\n [setup, client, returnURL, unavailableMessage, verificationPendingMessage]\n )\n\n return (\n <div className=\"grid gap-2\">\n <div ref={host} data-testid=\"stripe-card-entry\" />\n {error ? (\n <p role=\"alert\" className=\"text-[13px] text-destructive\">\n {error}\n </p>\n ) : null}\n </div>\n )\n})\n","// Native card entry (driver \"card\"): the PSP declares card_entry: server, so\n// the page posts the card to OpenRails, which vaults it at the gateway. No\n// gateway script is loaded. The card lives in component state only until it\n// is submitted.\nimport * as React from \"react\"\n\nimport type { CollectFieldErrors } from \"#orck/lib/collect\"\n\n/** A card as OpenRails' `card` field takes it. */\nexport interface CardEntry {\n number: string\n exp_month: number\n exp_year: number\n cvc: string\n}\n\n/** What the buyer typed, as typed. */\nexport interface CardEntryInput {\n number: string\n expiry: string\n cvc: string\n}\n\nexport const FIELD_MESSAGES: Required<CollectFieldErrors> = {\n number: \"Enter a valid card number\",\n expiry: \"Enter a valid expiry date\",\n cvv: \"Enter a valid security code\",\n}\n\nconst digitsOf = (value: string) => value.replace(/\\D/g, \"\")\n\nfunction luhn(digits: string): boolean {\n let sum = 0\n for (let i = 0; i < digits.length; i++) {\n let d = digits.charCodeAt(digits.length - 1 - i) - 48\n if (i % 2 === 1) {\n d *= 2\n if (d > 9) d -= 9\n }\n sum += d\n }\n return sum % 10 === 0\n}\n\n/** The card network a number's leading digits name (\"\" when none). */\nexport function cardBrandOf(number: string): string {\n const d = digitsOf(number)\n const p = (n: number) => (d.length >= n ? Number(d.slice(0, n)) : -1)\n if (p(1) === 4) return \"visa\"\n if (p(2) === 34 || p(2) === 37) return \"amex\"\n if ((p(2) >= 51 && p(2) <= 55) || (p(4) >= 2221 && p(4) <= 2720))\n return \"mastercard\"\n if (p(4) === 6011 || p(2) === 65 || (p(3) >= 644 && p(3) <= 649))\n return \"discover\"\n if (p(2) === 35) return \"jcb\"\n if (p(2) === 36 || p(2) === 38 || (p(3) >= 300 && p(3) <= 305))\n return \"diners\"\n return \"\"\n}\n\n/** Groups a number as it is printed: 4-6-5 for Amex, fours otherwise. */\nexport function formatCardNumber(value: string): string {\n const d = digitsOf(value).slice(0, 19)\n if (cardBrandOf(d) === \"amex\")\n return [d.slice(0, 4), d.slice(4, 10), d.slice(10, 15)]\n .filter(Boolean)\n .join(\" \")\n return d.replace(/(\\d{4})(?=\\d)/g, \"$1 \")\n}\n\n/** MM / YY as it is typed. */\nexport function formatExpiry(value: string): string {\n const d = digitsOf(value).slice(0, 4)\n return d.length > 2 ? `${d.slice(0, 2)} / ${d.slice(2)}` : d\n}\n\nfunction parseExpiry(value: string, now: Date) {\n const d = digitsOf(value)\n if (d.length !== 4 && d.length !== 6) return null\n const month = Number(d.slice(0, 2))\n const year = d.length === 4 ? 2000 + Number(d.slice(2)) : Number(d.slice(2))\n if (month < 1 || month > 12) return null\n const lapsed =\n year < now.getFullYear() ||\n (year === now.getFullYear() && month < now.getMonth() + 1)\n return lapsed ? null : { month, year }\n}\n\n/** Every field's error; an empty object means the card is complete. */\nexport function cardEntryErrors(\n input: CardEntryInput,\n now = new Date()\n): CollectFieldErrors {\n const errors: CollectFieldErrors = {}\n const number = digitsOf(input.number)\n if (number.length < 12 || number.length > 19 || !luhn(number))\n errors.number = FIELD_MESSAGES.number\n if (!parseExpiry(input.expiry, now)) errors.expiry = FIELD_MESSAGES.expiry\n const cvc = digitsOf(input.cvc)\n const want = cardBrandOf(number) === \"amex\" ? 4 : 3\n if (cvc !== input.cvc.trim() || (cvc.length !== want && cvc.length !== 4))\n errors.cvv = FIELD_MESSAGES.cvv\n return errors\n}\n\n/** The card OpenRails takes, or null while any field is invalid. */\nexport function parseCardEntry(\n input: CardEntryInput,\n now = new Date()\n): CardEntry | null {\n if (Object.keys(cardEntryErrors(input, now)).length > 0) return null\n const expiry = parseExpiry(input.expiry, now)!\n return {\n number: digitsOf(input.number),\n exp_month: expiry.month,\n exp_year: expiry.year,\n cvc: digitsOf(input.cvc),\n }\n}\n\n/** A card's display facts, the ones a saved card is labelled with. */\nexport function cardEntryDisplay(card: CardEntry): {\n last_four: string\n card_type?: string\n expiry_date: string\n} {\n const brand = cardBrandOf(card.number)\n return {\n last_four: card.number.slice(-4),\n ...(brand ? { card_type: brand } : {}),\n expiry_date: `${String(card.exp_month).padStart(2, \"0\")}/${String(card.exp_year % 100).padStart(2, \"0\")}`,\n }\n}\n\nconst empty: CardEntryInput = { number: \"\", expiry: \"\", cvc: \"\" }\n\n/**\n * The state of one native card form. Errors show once a field was left;\n * `take` hands the card over and clears the form, so the page keeps it no\n * longer than the request that sends it.\n */\nexport function useCardEntry() {\n const [input, setInput] = React.useState<CardEntryInput>(empty)\n const [touched, setTouched] = React.useState<\n Partial<Record<keyof CardEntryInput, boolean>>\n >({})\n const errors = cardEntryErrors(input)\n const shown: CollectFieldErrors = {}\n if (touched.number && errors.number) shown.number = errors.number\n if (touched.expiry && errors.expiry) shown.expiry = errors.expiry\n if (touched.cvc && errors.cvv) shown.cvv = errors.cvv\n const clear = React.useCallback(() => {\n setInput(empty)\n setTouched({})\n }, [])\n return {\n input,\n fieldErrors: shown,\n valid: Object.keys(errors).length === 0,\n change: (field: keyof CardEntryInput, value: string) =>\n setInput((current) => ({\n ...current,\n [field]:\n field === \"number\"\n ? formatCardNumber(value)\n : field === \"expiry\"\n ? formatExpiry(value)\n : digitsOf(value).slice(0, 4),\n })),\n leave: (field: keyof CardEntryInput) =>\n setTouched((current) => ({ ...current, [field]: true })),\n take: (): CardEntry | null => {\n const card = parseCardEntry(input)\n if (!card) {\n setTouched({ number: true, expiry: true, cvc: true })\n return null\n }\n clear()\n return card\n },\n clear,\n }\n}\n\nexport type CardEntryState = ReturnType<typeof useCardEntry>\n","import * as React from \"react\"\nimport {\n appearanceStyle,\n appearanceTheme,\n type CheckoutAppearance,\n} from \"./appearance\"\nimport { CardBillingFields } from \"./components/billing-fields\"\nimport { CardFields } from \"./components/card-fields\"\nimport { PayButton, TrustLine } from \"./components/pay-button\"\nimport {\n emptyNMIBilling,\n initialCountry,\n nmiBillingSchema,\n} from \"./lib/billing\"\nimport { collectCardDisplay, useCollectJS } from \"./lib/collect\"\nimport { cn } from \"cn\"\n\n// Only tokenized billing details cross the iframe boundary. PAN/CVC are never\n// accepted by this component or handed to the host callback.\nexport interface TokenizedCardData {\n payment_token: string\n name_on_card: string\n country: string\n zip?: string\n /** Display metadata from the gateway: last four, brand, MM/YY. */\n last_four?: string\n card_type?: string\n expiry_date?: string\n}\nexport interface TokenizedCardFormProps {\n tokenizationKey: string\n tokenizationURL: string\n onTokenized: (card: TokenizedCardData) => Promise<void>\n submitLabel?: string\n disabled?: boolean\n /** Billing country to preselect; default: the browser locale's region. */\n defaultCountry?: string\n appearance?: CheckoutAppearance\n className?: string\n}\n\n// The host supplies consent and performs its authorized save-card operation.\n// This component neither creates a checkout nor implies payment success.\nexport function TokenizedCardForm({\n tokenizationKey,\n tokenizationURL,\n onTokenized,\n submitLabel = \"Save card\",\n disabled = false,\n defaultCountry,\n appearance,\n className,\n}: TokenizedCardFormProps) {\n const uid = React.useId().replace(/[^a-zA-Z0-9-]/g, \"\")\n const ids = React.useMemo(\n () => ({\n number: `orck-save-${uid}-number`,\n expiry: `orck-save-${uid}-expiry`,\n cvv: `orck-save-${uid}-cvv`,\n }),\n [uid]\n )\n const [billing, setBilling] = React.useState(() => ({\n ...emptyNMIBilling,\n country: initialCountry(defaultCountry),\n }))\n const [busy, setBusy] = React.useState(false)\n const [submitted, setSubmitted] = React.useState(false)\n const [error, setError] = React.useState<string>()\n const authorization = React.useRef({ generation: 0, disabled })\n React.useLayoutEffect(() => {\n authorization.current = {\n generation: authorization.current.generation + 1,\n disabled,\n }\n }, [tokenizationKey, tokenizationURL, disabled])\n const mounted = React.useRef(true)\n React.useEffect(() => {\n mounted.current = true\n return () => {\n mounted.current = false\n }\n }, [])\n const collect = useCollectJS({\n enabled: true,\n active: true,\n tokenizationKey,\n scriptURL: tokenizationURL,\n selectors: {\n number: `#${ids.number}`,\n expiry: `#${ids.expiry}`,\n cvv: `#${ids.cvv}`,\n },\n })\n const submit = async (event: React.FormEvent) => {\n event.preventDefault()\n if (disabled || busy || submitted) return\n const parsed = nmiBillingSchema.safeParse(billing)\n if (!parsed.success) {\n setError(parsed.error.issues[0]?.message ?? \"Check the billing details\")\n return\n }\n setBusy(true)\n setError(undefined)\n const generation = authorization.current.generation\n let sent = false\n try {\n const token = await collect.tokenize()\n if (\n !mounted.current ||\n authorization.current.generation !== generation ||\n authorization.current.disabled\n )\n return\n sent = true\n setSubmitted(true)\n await onTokenized({\n payment_token: token.token,\n ...parsed.data,\n ...collectCardDisplay(token.card),\n })\n } catch (cause) {\n if (mounted.current)\n setError(\n sent\n ? \"The card-save result is not confirmed. Check your saved cards before starting another attempt.\"\n : cause instanceof Error\n ? cause.message\n : \"Card entry could not be completed.\"\n )\n } finally {\n if (mounted.current) setBusy(false)\n }\n }\n return (\n <div\n className={cn(\"orck\", className)}\n data-orck-theme={appearanceTheme(appearance)}\n style={appearanceStyle(appearance)}\n >\n <form\n aria-label=\"Secure card setup\"\n autoComplete=\"on\"\n className=\"grid gap-4\"\n onSubmit={(event) => void submit(event)}\n >\n <CardBillingFields\n idPrefix={`orck-save-${uid}`}\n value={billing}\n onChange={setBilling}\n disabled={disabled || busy || submitted}\n />\n <CardFields\n ids={ids}\n preview={collect.preview}\n error={collect.loadError}\n fieldErrors={collect.fieldErrors}\n />\n {error ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {error}\n </p>\n ) : null}\n <PayButton\n label={submitLabel}\n processing={busy}\n disabled={\n disabled ||\n submitted ||\n !collect.ready ||\n !collect.valid ||\n Boolean(collect.loadError)\n }\n />\n <TrustLine />\n </form>\n </div>\n )\n}\n","import * as React from \"react\"\n\nimport {\n appearanceStyle,\n appearanceTheme,\n type CheckoutAppearance,\n} from \"./appearance\"\nimport { isBillingError } from \"./client/errors\"\nimport { CardBillingFields } from \"./components/billing-fields\"\nimport { NativeCardFields } from \"./components/card-fields\"\nimport { PayButton, TrustLine } from \"./components/pay-button\"\nimport {\n StripeCardEntry,\n type StripeCardHandle,\n} from \"./components/stripe-card\"\nimport { useMessages } from \"./i18n/context\"\nimport {\n billingDetailsOf,\n emptyNMIBilling,\n initialCountry,\n nmiBillingSchema,\n} from \"./lib/billing\"\nimport { useCardEntry } from \"./lib/card-entry\"\nimport { cardSetupDriver, type PspConfig } from \"./psp\"\nimport { useBillingContext } from \"./react/context\"\nimport {\n TokenizedCardForm,\n type TokenizedCardData,\n} from \"./tokenized-card-form\"\nimport { cn } from \"cn\"\n\nexport interface SavePaymentMethodProps {\n /** The PSP to save the card with, from OpenRails's payment config. */\n psp: PspConfig\n onSaved: (paymentMethodId: string) => void\n /**\n * Where the provider returns after an off-page verification (3-D Secure),\n * given the setup id to confirm with `client.confirmCardSetup`. Default:\n * the current page with `?setup_id=`.\n */\n returnURL?: (setupId: string) => string\n /** Billing country to preselect; default: the browser locale's region. */\n defaultCountry?: string\n submitLabel?: string\n appearance?: CheckoutAppearance\n className?: string\n}\n\n/**\n * Saves a card to the customer's account with any PSP OpenRails serves, in\n * the page. The PSP's configuration picks the flow: card data enters the\n * provider's own frames, or, for a PSP whose card_entry is server, is posted\n * to OpenRails. Requires `BillingProvider`.\n */\nexport function SavePaymentMethod(props: SavePaymentMethodProps) {\n const { t } = useMessages()\n const driver = cardSetupDriver(props.psp)\n if (!driver)\n return (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {t(\"paymentMethods.unavailable\")}\n </p>\n )\n return (\n <div\n className={cn(\"orck grid gap-4\", props.className)}\n data-orck-theme={appearanceTheme(props.appearance)}\n style={appearanceStyle(props.appearance)}\n >\n <p className=\"text-sm text-muted-foreground\">\n {t(\"paymentMethods.saveNotice\")}\n </p>\n {driver === \"collect_js\" ? (\n <TokenizedSetup {...props} />\n ) : driver === \"card\" ? (\n <NativeCardSetup {...props} />\n ) : (\n <ElementsSetup {...props} />\n )}\n </div>\n )\n}\n\n// Provider SDK errors carry customer-facing text (\"Your card was declined.\").\nconst describe = (m: ReturnType<typeof useMessages>, cause: unknown) =>\n !isBillingError(cause) && cause instanceof Error && cause.message\n ? cause.message\n : m.error(cause)\n\nfunction TokenizedSetup({\n psp,\n onSaved,\n submitLabel,\n appearance,\n defaultCountry,\n}: SavePaymentMethodProps) {\n const m = useMessages()\n const { client, notify } = useBillingContext()\n const [formKey, setFormKey] = React.useState(0)\n const [error, setError] = React.useState<string>()\n const save = async (card: TokenizedCardData) => {\n setError(undefined)\n let method\n try {\n method = await client.addPaymentMethod({\n psp_id: psp.psp_id,\n payment_token: card.payment_token,\n billing_details: billingDetailsOf(card),\n })\n } catch (cause) {\n setError(describe(m, cause))\n setFormKey((key) => key + 1)\n return\n }\n notify({ type: \"payment_method.added\", paymentMethodId: method.id })\n onSaved(method.id)\n }\n return (\n <>\n {error ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {error}\n </p>\n ) : null}\n <TokenizedCardForm\n key={formKey}\n tokenizationKey={psp.config!.tokenization_key!}\n tokenizationURL={psp.config!.tokenization_url!}\n onTokenized={save}\n defaultCountry={defaultCountry}\n submitLabel={submitLabel ?? m.t(\"paymentMethods.save\")}\n appearance={appearance}\n />\n </>\n )\n}\n\nfunction NativeCardSetup({\n psp,\n onSaved,\n submitLabel,\n defaultCountry,\n}: SavePaymentMethodProps) {\n const m = useMessages()\n const { client, notify } = useBillingContext()\n const uid = React.useId().replace(/[^a-zA-Z0-9-]/g, \"\")\n const ids = React.useMemo(\n () => ({\n number: `orck-save-${uid}-number`,\n expiry: `orck-save-${uid}-expiry`,\n cvv: `orck-save-${uid}-cvv`,\n }),\n [uid]\n )\n const card = useCardEntry()\n const [billing, setBilling] = React.useState(() => ({\n ...emptyNMIBilling,\n country: initialCountry(defaultCountry),\n }))\n const [busy, setBusy] = React.useState(false)\n const [error, setError] = React.useState<string>()\n\n const submit = async (event: React.FormEvent) => {\n event.preventDefault()\n if (busy) return\n const parsed = nmiBillingSchema.safeParse(billing)\n if (!parsed.success) {\n setError(parsed.error.issues[0]?.message ?? \"Check the billing details\")\n return\n }\n const entered = card.take()\n if (!entered) return\n setBusy(true)\n setError(undefined)\n try {\n const method = await client.addPaymentMethod({\n psp_id: psp.psp_id,\n card: entered,\n billing_details: billingDetailsOf(parsed.data),\n })\n notify({ type: \"payment_method.added\", paymentMethodId: method.id })\n onSaved(method.id)\n } catch (cause) {\n setError(describe(m, cause))\n } finally {\n setBusy(false)\n }\n }\n\n return (\n <form\n aria-label=\"Secure card setup\"\n autoComplete=\"on\"\n className=\"grid gap-4\"\n noValidate\n onSubmit={(event) => void submit(event)}\n >\n <CardBillingFields\n idPrefix={`orck-save-${uid}`}\n value={billing}\n onChange={setBilling}\n disabled={busy}\n />\n <NativeCardFields ids={ids} card={card} disabled={busy} />\n {error ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {error}\n </p>\n ) : null}\n <PayButton\n label={submitLabel ?? m.t(\"paymentMethods.save\")}\n processing={busy}\n disabled={!card.valid}\n />\n <TrustLine />\n </form>\n )\n}\n\nfunction ElementsSetup({\n psp,\n onSaved,\n returnURL,\n submitLabel,\n defaultCountry,\n}: SavePaymentMethodProps) {\n const m = useMessages()\n const { t } = m\n const { client, notify } = useBillingContext()\n const card = React.useRef<StripeCardHandle>(null)\n const [complete, setComplete] = React.useState(false)\n const [busy, setBusy] = React.useState(false)\n const [error, setError] = React.useState<string>()\n const country = React.useMemo(\n () => initialCountry(defaultCountry),\n [defaultCountry]\n )\n\n const submit = async (event: React.FormEvent) => {\n event.preventDefault()\n if (!card.current || busy) return\n setBusy(true)\n setError(undefined)\n try {\n const id = await card.current.save()\n notify({ type: \"payment_method.added\", paymentMethodId: id })\n onSaved(id)\n } catch (cause) {\n setError(describe(m, cause))\n } finally {\n setBusy(false)\n }\n }\n\n return (\n <form className=\"grid gap-4\" onSubmit={(event) => void submit(event)}>\n <StripeCardEntry\n ref={card}\n psp={psp}\n client={client}\n returnURL={returnURL}\n defaultCountry={country || undefined}\n onCompleteChange={setComplete}\n unavailableMessage={t(\"paymentMethods.unavailable\")}\n verificationPendingMessage={t(\"paymentMethods.verificationPending\")}\n />\n {error ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {error}\n </p>\n ) : null}\n <PayButton\n label={submitLabel ?? t(\"paymentMethods.save\")}\n processing={busy}\n disabled={!complete}\n />\n <TrustLine />\n </form>\n )\n}\n","import * as React from \"react\"\nimport { cn } from \"cn\"\n\n/** Polite confirmation line that clears itself. */\nexport function useNotice(): [React.ReactNode, (text: string) => void] {\n const [text, setText] = React.useState<string | null>(null)\n React.useEffect(() => {\n if (!text) return\n const timer = setTimeout(() => setText(null), 6000)\n return () => clearTimeout(timer)\n }, [text])\n const node = (\n <p\n role=\"status\"\n aria-live=\"polite\"\n className={cn(\"text-sm text-muted-foreground\", text ? \"pt-3\" : \"sr-only\")}\n >\n {text}\n </p>\n )\n return [node, setText]\n}\n","import * as React from \"react\"\nimport { HugeiconsIcon } from \"@hugeicons/react\"\nimport { Add01Icon, Delete02Icon } from \"@hugeicons/core-free-icons\"\n\nimport type { CheckoutAppearance } from \"#orck/appearance\"\nimport type { BillingError } from \"#orck/client/errors\"\nimport type { PaymentMethod } from \"#orck/client/types\"\nimport { CardBrandPlate } from \"#orck/components/card-brands\"\nimport {\n AlertDialog,\n AlertDialogCancel,\n AlertDialogContent,\n AlertDialogDescription,\n AlertDialogFooter,\n AlertDialogHeader,\n AlertDialogTitle,\n} from \"#orck/components/ui/alert-dialog\"\nimport { Button } from \"#orck/components/ui/button\"\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogHeader,\n DialogTitle,\n} from \"#orck/components/ui/dialog\"\nimport { Spinner } from \"#orck/components/ui/spinner\"\nimport { useMessages } from \"#orck/i18n/context\"\nimport type { Translator } from \"#orck/i18n/messages\"\nimport { useConfig } from \"#orck/react/config\"\nimport { usePaymentMethods } from \"#orck/react/hooks\"\nimport { useScopeProps } from \"#orck/scope-context\"\nimport { canSavePaymentMethod, cardRetryAfter, checkoutPsps } from \"#orck/psp\"\nimport { SavePaymentMethod } from \"#orck/save-payment-method\"\nimport { cardText, RESET } from \"./format\"\nimport { EmptyState, ErrorState, ListSkeleton, Section } from \"./section\"\nimport { useNotice } from \"./notice\"\nimport { BillingStatusBadge } from \"./status-badge\"\n\nexport interface PaymentMethodsPanelProps {\n /** Return target after off-page card verification; see `SavePaymentMethod`. */\n cardSetupReturnURL?: (setupId: string) => string\n /** Offers to make a card the one that collects this currency's invoices. */\n collectionCurrency?: string\n /** Billing country to preselect when adding a card. */\n defaultCountry?: string\n appearance?: CheckoutAppearance\n className?: string\n}\n\nfunction methodLabel(method: PaymentMethod, m: Translator): string {\n return cardText(method.card, m)\n}\n\nfunction removeMessage(error: BillingError, m: Translator): string {\n if (error.status === 409 && error.code === \"resource_conflict\")\n return m.t(\"paymentMethods.inUse\")\n return m.error(error)\n}\n\n/**\n * The customer's saved cards. \"Add card\" offers each PSP of the merchant's\n * payment setup (`GET /config`) that saves a card in the page.\n */\nexport function PaymentMethodsPanel({\n cardSetupReturnURL,\n collectionCurrency,\n defaultCountry,\n appearance,\n className,\n}: PaymentMethodsPanelProps) {\n const m = useMessages()\n const { t } = m\n const scope = useScopeProps(appearance)\n const state = usePaymentMethods()\n const [removing, setRemoving] = React.useState<PaymentMethod | null>(null)\n const [removeError, setRemoveError] = React.useState<string | null>(null)\n const [rowError, setRowError] = React.useState<{\n id: string\n message: string\n } | null>(null)\n const [adding, setAdding] = React.useState(false)\n const config = useConfig()\n const psps = checkoutPsps(config.config?.payment?.psps ?? [])\n const savable = psps.filter(canSavePaymentMethod)\n const retryAfter = savable.length > 0 ? null : cardRetryAfter(psps)\n const { refetch: refetchConfig } = config\n React.useEffect(() => {\n if (retryAfter === null) return\n const timer = setTimeout(refetchConfig, retryAfter * 1000)\n return () => clearTimeout(timer)\n }, [retryAfter, refetchConfig, config.config])\n const [pspId, setPspId] = React.useState<string>()\n const psp = savable.find((item) => item.psp_id === pspId) ?? savable[0]\n const [notice, announce] = useNotice()\n const currency = collectionCurrency?.toUpperCase()\n\n const confirmRemove = async () => {\n if (!removing) return\n setRemoveError(null)\n const error = await state.remove(removing.id)\n if (error) {\n setRemoveError(removeMessage(error, m))\n return\n }\n setRemoving(null)\n announce(t(\"paymentMethods.removed\"))\n }\n\n const collectWith = async (method: PaymentMethod) => {\n if (!currency) return\n setRowError(null)\n const error = await state.setCollection(method.id, currency)\n if (error) setRowError({ id: method.id, message: m.error(error) })\n else announce(t(\"paymentMethods.usedForInvoices\"))\n }\n\n let body: React.ReactNode\n const methods = state.methods\n if (methods === null && state.error) {\n body = <ErrorState error={state.error} onRetry={state.refetch} />\n } else if (methods === null) {\n body = <ListSkeleton />\n } else if (methods.length === 0) {\n body = (\n <EmptyState\n title={t(\"paymentMethods.empty\")}\n description={t(\"paymentMethods.emptyDescription\")}\n />\n )\n } else {\n body = (\n <ul className=\"-my-1 divide-y divide-border\">\n {methods.map((method) => {\n const label = methodLabel(method, m)\n const users = (method.subscriptions ?? [])\n .map((s) => s.display_name)\n .filter(Boolean)\n const health = method.health?.expiry_status\n const collects = method.collection_currencies ?? []\n const pending = state.pending[method.id]\n const meta = [\n users.length > 0 &&\n t(\"paymentMethods.usedBy\", { names: users.join(\", \") }),\n ].filter(Boolean)\n return (\n <li\n key={method.id}\n data-testid=\"payment-method-row\"\n data-payment-method-id={method.id}\n className=\"flex flex-wrap items-center gap-x-3 gap-y-2 py-3.5\"\n >\n <CardBrandPlate\n brand={method.card?.brand ?? undefined}\n fallback={(method.card?.brand ?? \"card\").slice(0, 4)}\n />\n <div className=\"grid min-w-40 flex-1 gap-0.5\">\n <div className=\"flex flex-wrap items-center gap-x-2 gap-y-1\">\n <span className=\"text-sm font-medium tabular-nums\">\n {label}\n </span>\n {health === \"expired\" || health === \"expiring_soon\" ? (\n <BillingStatusBadge status={health} />\n ) : method.health?.active === false ? (\n <BillingStatusBadge status=\"needs_attention\" />\n ) : null}\n {collects.length > 0 ? (\n <BillingStatusBadge\n status=\"collection\"\n label={t(\"paymentMethods.collectsFor\", {\n currencies: collects.join(\", \"),\n })}\n />\n ) : null}\n </div>\n {meta.length > 0 ? (\n <p className=\"text-sm text-muted-foreground tabular-nums\">\n {meta.join(\" · \")}\n </p>\n ) : null}\n {rowError?.id === method.id ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {rowError.message}\n </p>\n ) : null}\n </div>\n <div className=\"ml-auto flex items-center gap-1\">\n {currency && !collects.includes(currency) ? (\n <Button\n variant=\"ghost\"\n size=\"sm\"\n className=\"text-muted-foreground\"\n disabled={!!pending}\n onClick={() => void collectWith(method)}\n >\n {pending === \"collection\" ? <Spinner /> : null}\n {t(\"paymentMethods.useForInvoices\")}\n </Button>\n ) : null}\n <Button\n variant=\"ghost\"\n size=\"icon-sm\"\n className=\"text-muted-foreground hover:text-destructive\"\n aria-label={t(\"paymentMethods.removeLabel\", { label })}\n title={t(\"paymentMethods.remove\")}\n disabled={!!pending}\n onClick={() => {\n setRemoveError(null)\n setRemoving(method)\n }}\n >\n {pending === \"remove\" ? (\n <Spinner />\n ) : (\n <HugeiconsIcon icon={Delete02Icon} aria-hidden />\n )}\n </Button>\n </div>\n </li>\n )\n })}\n </ul>\n )\n }\n\n const removingBusy = removing\n ? state.pending[removing.id] === \"remove\"\n : false\n const removingLabel = removing ? methodLabel(removing, m) : \"\"\n\n return (\n <Section\n title={t(\"paymentMethods.title\")}\n description={t(\"paymentMethods.description\")}\n appearance={appearance}\n className={className}\n data-testid=\"payment-methods-panel\"\n action={\n psp ? (\n <Button variant=\"outline\" size=\"sm\" onClick={() => setAdding(true)}>\n <HugeiconsIcon\n icon={Add01Icon}\n aria-hidden\n data-icon=\"inline-start\"\n />\n {t(\"paymentMethods.add\")}\n </Button>\n ) : null\n }\n >\n {body}\n {methods !== null && state.error ? (\n <div className=\"pt-3\">\n <ErrorState error={state.error} onRetry={state.refetch} />\n </div>\n ) : null}\n {config.error ? (\n <div className=\"pt-3\">\n <ErrorState\n error={config.error}\n message={t(\"paymentMethods.addUnavailable\")}\n onRetry={config.refetch}\n />\n </div>\n ) : retryAfter !== null ? (\n <p role=\"status\" className=\"pt-3 text-sm text-muted-foreground\">\n {t(\"paymentMethods.addUnavailable\")}\n </p>\n ) : null}\n {notice}\n\n <AlertDialog\n open={removing !== null}\n onOpenChange={(open) => {\n if (!open && !removingBusy) setRemoving(null)\n }}\n >\n <AlertDialogContent\n className={`${scope.className} ${RESET} bg-popover text-popover-foreground`}\n data-orck-theme={scope[\"data-orck-theme\"]}\n style={scope.style}\n >\n <AlertDialogHeader>\n <AlertDialogTitle>\n {t(\"paymentMethods.removeTitle\", { label: removingLabel })}\n </AlertDialogTitle>\n <AlertDialogDescription>\n {t(\"paymentMethods.removeDescription\")}\n </AlertDialogDescription>\n </AlertDialogHeader>\n {removeError ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {removeError}\n </p>\n ) : null}\n <AlertDialogFooter>\n <AlertDialogCancel disabled={removingBusy}>\n {t(\"common.cancel\")}\n </AlertDialogCancel>\n <Button\n variant=\"destructive\"\n disabled={removingBusy}\n onClick={() => void confirmRemove()}\n >\n {removingBusy ? <Spinner /> : null}\n {t(\"paymentMethods.removeConfirm\")}\n </Button>\n </AlertDialogFooter>\n </AlertDialogContent>\n </AlertDialog>\n\n {psp ? (\n <Dialog open={adding} onOpenChange={setAdding}>\n <DialogContent\n className={`${scope.className} ${RESET} max-h-[calc(100dvh-2rem)] overflow-y-auto bg-popover text-popover-foreground`}\n data-orck-theme={scope[\"data-orck-theme\"]}\n style={scope.style}\n >\n <DialogHeader>\n <DialogTitle>{t(\"paymentMethods.addTitle\")}</DialogTitle>\n <DialogDescription>\n {t(\"paymentMethods.addDescription\")}\n </DialogDescription>\n </DialogHeader>\n {savable.length > 1 ? (\n <label className=\"grid gap-1.5 text-sm\">\n {t(\"paymentMethods.provider\")}\n <select\n className=\"h-9 rounded-md border border-input bg-transparent px-2\"\n value={psp.psp_id}\n onChange={(event) => setPspId(event.target.value)}\n >\n {savable.map((item) => (\n <option key={item.psp_id} value={item.psp_id}>\n {item.display_name}\n </option>\n ))}\n </select>\n </label>\n ) : null}\n <SavePaymentMethod\n key={psp.psp_id}\n psp={psp}\n returnURL={cardSetupReturnURL}\n defaultCountry={defaultCountry}\n appearance={appearance}\n onSaved={() => {\n setAdding(false)\n announce(t(\"paymentMethods.added\"))\n }}\n />\n </DialogContent>\n </Dialog>\n ) : null}\n </Section>\n )\n}\n","import * as React from \"react\"\nimport { cn } from \"cn\"\n\nfunction Textarea({ className, ...props }: React.ComponentProps<\"textarea\">) {\n return (\n <textarea\n data-slot=\"textarea\"\n className={cn(\n \"flex field-sizing-content min-h-16 w-full rounded-md border border-input bg-transparent px-2.5 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40\",\n className\n )}\n {...props}\n />\n )\n}\n\nexport { Textarea }\n","import * as React from \"react\"\n\nimport type { CheckoutAppearance } from \"#orck/appearance\"\n\nimport {\n CANCEL_REASON_MAX,\n CANCEL_REASON_MIN,\n isWalletRejection,\n} from \"#orck/client/client\"\nimport type { BillingError } from \"#orck/client/errors\"\nimport {\n AlertDialog,\n AlertDialogCancel,\n AlertDialogContent,\n AlertDialogDescription,\n AlertDialogFooter,\n AlertDialogHeader,\n AlertDialogTitle,\n} from \"#orck/components/ui/alert-dialog\"\nimport { Button } from \"#orck/components/ui/button\"\nimport { Label } from \"#orck/components/ui/label\"\nimport { Spinner } from \"#orck/components/ui/spinner\"\nimport { Textarea } from \"#orck/components/ui/textarea\"\nimport { useMessages } from \"#orck/i18n/context\"\nimport type { SubscriptionAction } from \"#orck/react/hooks\"\nimport { useScopeProps } from \"#orck/scope-context\"\nimport { RESET } from \"./format\"\n\n// Key it per subscription so each opening starts blank.\nexport interface CancelSubscriptionDialogProps {\n open: boolean\n onOpenChange: (open: boolean) => void\n /** Subscription display name. */\n name: string\n /** On-chain (Solana) cancel: the wallet signs after the reason. */\n onChain?: boolean\n /** In-flight stage, when cancelling. */\n pending?: SubscriptionAction\n /** Resolves null on success; the dialog then closes. */\n onConfirm: (reason: string) => Promise<BillingError | null>\n appearance?: CheckoutAppearance\n}\n\nexport function CancelSubscriptionDialog({\n open,\n onOpenChange,\n name,\n onChain = false,\n pending,\n onConfirm,\n appearance,\n}: CancelSubscriptionDialogProps) {\n const m = useMessages()\n const { t } = m\n const scope = useScopeProps(appearance)\n const reasonId = React.useId()\n const hintId = React.useId()\n const [reason, setReason] = React.useState(\"\")\n const [touched, setTouched] = React.useState(false)\n const [error, setError] = React.useState<BillingError | null>(null)\n const busy = pending !== undefined\n\n const length = reason.trim().length\n const tooShort = length < CANCEL_REASON_MIN\n const confirm = async () => {\n setTouched(true)\n if (tooShort || busy) return\n setError(null)\n const result = await onConfirm(reason)\n if (!result) onOpenChange(false)\n else if (!isWalletRejection(result)) setError(result)\n }\n\n const stageLabel =\n pending === \"cancel\" && onChain\n ? t(\"cancel.preparing\")\n : pending === \"signing\"\n ? t(\"cancel.signing\")\n : pending === \"confirming\"\n ? t(\"cancel.confirming\")\n : busy\n ? t(\"cancel.working\")\n : onChain\n ? t(\"cancel.confirmWallet\")\n : t(\"cancel.confirm\")\n\n return (\n <AlertDialog\n open={open}\n onOpenChange={(next) => {\n if (!next && busy) return\n onOpenChange(next)\n }}\n >\n <AlertDialogContent\n className={`${scope.className} ${RESET} bg-popover text-popover-foreground`}\n data-orck-theme={scope[\"data-orck-theme\"]}\n style={scope.style}\n >\n <form\n className=\"grid gap-5\"\n noValidate\n onSubmit={(event) => {\n event.preventDefault()\n void confirm()\n }}\n >\n <AlertDialogHeader>\n <AlertDialogTitle>{t(\"cancel.title\", { name })}</AlertDialogTitle>\n <AlertDialogDescription>\n {onChain\n ? t(\"cancel.solanaDescription\")\n : t(\"cancel.description\")}\n </AlertDialogDescription>\n </AlertDialogHeader>\n <div className=\"grid gap-2\">\n <Label htmlFor={reasonId}>{t(\"cancel.reasonLabel\")}</Label>\n <Textarea\n id={reasonId}\n value={reason}\n maxLength={CANCEL_REASON_MAX}\n placeholder={t(\"cancel.reasonPlaceholder\")}\n aria-describedby={hintId}\n aria-invalid={touched && tooShort ? true : undefined}\n disabled={busy}\n required\n rows={3}\n className=\"[font:inherit]\"\n onChange={(event) => setReason(event.target.value)}\n onBlur={() => length > 0 && setTouched(true)}\n />\n <div\n id={hintId}\n className=\"flex justify-between gap-3 text-xs text-muted-foreground\"\n >\n <span className={touched && tooShort ? \"text-destructive\" : \"\"}>\n {touched && tooShort\n ? t(\"cancel.reasonTooShort\", { min: CANCEL_REASON_MIN })\n : \"\"}\n </span>\n <span className=\"tabular-nums\">\n {t(\"cancel.reasonHint\", {\n count: reason.length,\n max: CANCEL_REASON_MAX,\n })}\n </span>\n </div>\n </div>\n {error ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {m.error(error)}\n </p>\n ) : null}\n <AlertDialogFooter>\n <AlertDialogCancel disabled={busy}>\n {t(\"cancel.keep\")}\n </AlertDialogCancel>\n <Button type=\"submit\" variant=\"destructive\" disabled={busy}>\n {busy ? <Spinner /> : null}\n {stageLabel}\n </Button>\n </AlertDialogFooter>\n </form>\n </AlertDialogContent>\n </AlertDialog>\n )\n}\n","\"use client\"\n\nimport { Radio as RadioPrimitive } from \"@base-ui/react/radio\"\nimport { RadioGroup as RadioGroupPrimitive } from \"@base-ui/react/radio-group\"\nimport { cn } from \"cn\"\n\nfunction RadioGroup({ className, ...props }: RadioGroupPrimitive.Props) {\n return (\n <RadioGroupPrimitive\n data-slot=\"radio-group\"\n className={cn(\"grid w-full gap-3\", className)}\n {...props}\n />\n )\n}\n\nfunction RadioGroupItem({ className, ...props }: RadioPrimitive.Root.Props) {\n return (\n <RadioPrimitive.Root\n data-slot=\"radio-group-item\"\n className={cn(\n \"group/radio-group-item peer relative flex aspect-square size-4 shrink-0 rounded-full border border-input outline-none group-has-[:focus-visible]/field-label:ring-0 group-has-[:focus-visible]/field-label:not-data-checked:border-input after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 aria-invalid:aria-checked:border-primary dark:bg-input/30 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:border-primary data-checked:bg-primary data-checked:text-primary-foreground group-has-[:focus-visible]/field-label:data-checked:border-primary dark:data-checked:bg-primary\",\n className\n )}\n {...props}\n >\n <RadioPrimitive.Indicator\n data-slot=\"radio-group-indicator\"\n className=\"flex size-4 items-center justify-center\"\n >\n <span className=\"absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2 rounded-full bg-primary-foreground\" />\n </RadioPrimitive.Indicator>\n </RadioPrimitive.Root>\n )\n}\n\nexport { RadioGroup, RadioGroupItem }\n","import * as React from \"react\"\n\nimport type { CheckoutAppearance } from \"#orck/appearance\"\nimport { cn } from \"cn\"\n\nimport type { BillingError } from \"#orck/client/errors\"\nimport type { PaymentMethod, Subscription } from \"#orck/client/types\"\nimport { CardBrandPlate } from \"#orck/components/card-brands\"\nimport { Button } from \"#orck/components/ui/button\"\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n} from \"#orck/components/ui/dialog\"\nimport { Label } from \"#orck/components/ui/label\"\nimport { RadioGroup, RadioGroupItem } from \"#orck/components/ui/radio-group\"\nimport { Spinner } from \"#orck/components/ui/spinner\"\nimport { useMessages } from \"#orck/i18n/context\"\nimport { usePaymentMethods } from \"#orck/react/hooks\"\nimport { useScopeProps } from \"#orck/scope-context\"\nimport { cardText, RESET } from \"./format\"\nimport { ErrorState, ListSkeleton } from \"./section\"\n\n/** Cards the subscription's PSP can charge; expired cards are left out. */\nfunction eligibleCards(\n s: Subscription,\n methods: readonly PaymentMethod[]\n): PaymentMethod[] {\n return methods.filter(\n (m) =>\n m.health?.expiry_status !== \"expired\" &&\n (!s.psp_id || !m.psp_id || m.psp_id === s.psp_id) &&\n (!s.rail || !m.rail || m.rail === s.rail)\n )\n}\n\nexport interface ChangeCardDialogProps {\n subscription: Subscription | null\n name: string\n onOpenChange: (open: boolean) => void\n pending: boolean\n /** Resolves null on success; the dialog then closes. */\n onConfirm: (paymentMethodId: string) => Promise<BillingError | null>\n appearance?: CheckoutAppearance\n}\n\nexport function ChangeCardDialog({\n subscription,\n name,\n onOpenChange,\n pending,\n onConfirm,\n appearance,\n}: ChangeCardDialogProps) {\n const scope = useScopeProps(appearance)\n return (\n <Dialog\n open={subscription !== null}\n onOpenChange={(next) => {\n if (!next && pending) return\n onOpenChange(next)\n }}\n >\n <DialogContent\n showCloseButton={false}\n className={`${scope.className} ${RESET} bg-popover text-popover-foreground`}\n data-orck-theme={scope[\"data-orck-theme\"]}\n style={scope.style}\n >\n {subscription ? (\n <ChangeCardForm\n subscription={subscription}\n name={name}\n pending={pending}\n onCancel={() => onOpenChange(false)}\n onConfirm={onConfirm}\n />\n ) : null}\n </DialogContent>\n </Dialog>\n )\n}\n\n// Mounted only while open, so the card list loads on demand.\nfunction ChangeCardForm({\n subscription,\n name,\n pending,\n onCancel,\n onConfirm,\n}: {\n subscription: Subscription\n name: string\n pending: boolean\n onCancel: () => void\n onConfirm: (paymentMethodId: string) => Promise<BillingError | null>\n}) {\n const m = useMessages()\n const { t } = m\n const idPrefix = React.useId()\n const methods = usePaymentMethods()\n const current = subscription.payment_method_id ?? \"\"\n const [selected, setSelected] = React.useState(current)\n const [error, setError] = React.useState<BillingError | null>(null)\n const cards = methods.methods\n ? eligibleCards(subscription, methods.methods)\n : null\n const canSwitch = !!cards && cards.some((c) => c.id !== current)\n\n const confirm = async () => {\n if (!selected || selected === current || pending) return\n setError(null)\n const result = await onConfirm(selected)\n if (result) setError(result)\n }\n\n let list: React.ReactNode\n if (cards === null && methods.error) {\n list = <ErrorState error={methods.error} onRetry={methods.refetch} />\n } else if (cards === null) {\n list = <ListSkeleton rows={2} />\n } else {\n list = (\n <RadioGroup\n value={selected}\n onValueChange={(next) => {\n if (typeof next === \"string\" && next) setSelected(next)\n }}\n disabled={pending}\n aria-label={t(\"changeCard.title\", { name })}\n className=\"grid gap-0\"\n >\n {cards.map((card) => {\n const id = `${idPrefix}-${card.id}`\n return (\n <Label\n key={card.id}\n htmlFor={id}\n data-testid=\"change-card-option\"\n className={cn(\n \"flex cursor-pointer items-center gap-3 py-1.5 select-none\",\n pending && \"cursor-default\"\n )}\n >\n <RadioGroupItem id={id} value={card.id} />\n <CardBrandPlate\n brand={card.card?.brand ?? undefined}\n fallback={(card.card?.brand ?? \"card\").slice(0, 4)}\n />\n <span className=\"min-w-0 flex-1 truncate text-sm font-medium tabular-nums\">\n {cardText(card.card, m)}\n </span>\n {card.id === current ? (\n <span className=\"shrink-0 text-xs text-muted-foreground\">\n {t(\"changeCard.current\")}\n </span>\n ) : null}\n </Label>\n )\n })}\n </RadioGroup>\n )\n }\n\n return (\n <form\n className=\"grid gap-5\"\n noValidate\n onSubmit={(event) => {\n event.preventDefault()\n void confirm()\n }}\n >\n <DialogHeader>\n <DialogTitle>{t(\"changeCard.title\", { name })}</DialogTitle>\n <DialogDescription>\n {cards !== null && !canSwitch\n ? t(\"changeCard.none\")\n : t(\"changeCard.description\")}\n </DialogDescription>\n </DialogHeader>\n {list}\n {error ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {m.error(error)}\n </p>\n ) : null}\n <DialogFooter>\n <Button\n type=\"button\"\n variant=\"outline\"\n disabled={pending}\n onClick={onCancel}\n >\n {t(\"common.cancel\")}\n </Button>\n <Button\n type=\"submit\"\n disabled={pending || !selected || selected === current}\n >\n {pending ? <Spinner /> : null}\n {t(\"changeCard.confirm\")}\n </Button>\n </DialogFooter>\n </form>\n )\n}\n","import * as React from \"react\"\nimport { HugeiconsIcon } from \"@hugeicons/react\"\nimport { ArrowUpRight01Icon } from \"@hugeicons/core-free-icons\"\nimport { cn } from \"cn\"\n\nimport type { CheckoutAppearance } from \"#orck/appearance\"\nimport type { SendSolanaTransaction } from \"#orck/client/client\"\nimport type { Subscription } from \"#orck/client/types\"\nimport { Button, buttonVariants } from \"#orck/components/ui/button\"\nimport { Spinner } from \"#orck/components/ui/spinner\"\nimport { useMessages } from \"#orck/i18n/context\"\nimport { useSubscriptions, type SubscriptionsOptions } from \"#orck/react/hooks\"\nimport { useCurrencyScales } from \"#orck/react/config\"\nimport { useUiSettings } from \"#orck/scope-context\"\nimport { CancelSubscriptionDialog } from \"./cancel-dialog\"\nimport { ChangeCardDialog } from \"./change-card-dialog\"\nimport {\n brandName,\n formatDate,\n formatMoney,\n intervalLabel,\n isEnding,\n isLive,\n LIVE_STATUSES,\n subscriptionName,\n} from \"./format\"\nimport { EmptyState, ErrorState, ListSkeleton, Section } from \"./section\"\nimport { useNotice } from \"./notice\"\nimport { BillingStatusBadge } from \"./status-badge\"\n\nexport interface SubscriptionsPanelProps extends SubscriptionsOptions {\n /**\n * Wallet for Solana-rail subscriptions. Without it their cancel action is\n * hidden.\n */\n sendSolanaTransaction?: SendSolanaTransaction\n /** Empty-state link to the host's plans page (uses `navigate` if set). */\n plansHref?: string\n /** Host content under a row, e.g. a plan-change control. */\n renderSubscriptionFooter?: (subscription: Subscription) => React.ReactNode\n appearance?: CheckoutAppearance\n className?: string\n}\n\nexport function SubscriptionsPanel({\n sendSolanaTransaction,\n plansHref,\n renderSubscriptionFooter,\n appearance,\n className,\n ...options\n}: SubscriptionsPanelProps) {\n const m = useMessages()\n const { t } = m\n const { locale, navigate } = useUiSettings()\n const state = useSubscriptions(options)\n const scales = useCurrencyScales()\n const [cancelling, setCancelling] = React.useState<Subscription | null>(null)\n const [changingCard, setChangingCard] = React.useState<Subscription | null>(\n null\n )\n const [rowError, setRowError] = React.useState<{\n id: string\n message: string\n } | null>(null)\n const [notice, announce] = useNotice()\n\n const rows = React.useMemo(() => {\n const list = state.subscriptions ?? []\n return [...list.filter(isLive), ...list.filter((s) => !isLive(s))]\n }, [state.subscriptions])\n\n const resume = async (s: Subscription) => {\n setRowError(null)\n const error = await state.resume(s.id)\n if (error) setRowError({ id: s.id, message: m.error(error) })\n else announce(t(\"subscriptions.resumed\"))\n }\n\n const onChain = cancelling?.rail === \"solana\"\n\n let body: React.ReactNode\n if (state.subscriptions === null && state.error) {\n body = <ErrorState error={state.error} onRetry={state.refetch} />\n } else if (state.subscriptions === null) {\n body = <ListSkeleton />\n } else if (rows.length === 0) {\n body = (\n <EmptyState\n title={t(\"subscriptions.empty\")}\n description={t(\"subscriptions.emptyDescription\")}\n action={\n plansHref ? (\n <a\n href={plansHref}\n className={buttonVariants({ variant: \"outline\", size: \"sm\" })}\n onClick={(event) => {\n if (!navigate) return\n event.preventDefault()\n navigate(plansHref)\n }}\n >\n {t(\"subscriptions.browsePlans\")}\n </a>\n ) : null\n }\n />\n )\n } else {\n body = (\n <ul className=\"-my-1 divide-y divide-border\">\n {rows.map((s) => {\n const live = isLive(s)\n const pending = state.pending[s.id]\n const name = subscriptionName(s, m)\n const price = s.price\n ? formatMoney(s.price.unit_amount, s.price.currency, scales, locale)\n : null\n const interval = intervalLabel(s.price, m)\n const periodEnd = formatDate(s.current_period_ends_at, locale)\n const accessEnd = formatDate(s.access?.ends_at, locale)\n const endedAt = formatDate(\n s.ended_at ?? s.canceled_at ?? s.current_period_ends_at,\n locale\n )\n const scheduled = isEnding(s)\n const renews = live && !scheduled && !!s.price?.billing_interval_hours\n const when = !live\n ? s.status === \"canceled\"\n ? t(\"subscriptions.noMorePayments\")\n : endedAt && t(\"subscriptions.endedOn\", { date: endedAt })\n : renews && periodEnd\n ? t(\"subscriptions.renews\", { date: periodEnd })\n : accessEnd\n ? t(\"subscriptions.endsOn\", { date: accessEnd })\n : t(\"subscriptions.noMorePayments\")\n const paidWith =\n s.rail === \"solana\"\n ? t(\"subscriptions.wallet\")\n : s.card?.last4\n ? t(\"subscriptions.paidWith\", {\n brand: brandName(\n s.card.brand,\n t(\"paymentMethods.fallbackBrand\")\n ),\n last4: s.card.last4,\n })\n : null\n const portal = live && !scheduled ? s.cancel_portal_url : null\n const canCancel =\n LIVE_STATUSES.has(s.status) &&\n !scheduled &&\n !portal &&\n (s.rail !== \"solana\" || !!sendSolanaTransaction)\n const canChangeCard =\n (s.status === \"active\" ||\n s.status === \"past_due\" ||\n s.status === \"awaiting_method\" ||\n s.status === \"unverified\") &&\n !scheduled &&\n !portal &&\n s.rail !== \"solana\" &&\n !!s.payment_method_id\n const status = s.cancel_scheduled ? \"cancel_scheduled\" : s.status\n const footer = renderSubscriptionFooter?.(s)\n return (\n <li\n key={s.id}\n data-testid=\"subscription-row\"\n data-subscription-id={s.id}\n className=\"grid gap-3 py-4 @md:grid-cols-[1fr_auto] @md:items-center\"\n >\n <div className=\"grid min-w-0 gap-1\">\n <div className=\"flex flex-wrap items-center gap-x-2 gap-y-1\">\n <span\n className={cn(\n \"truncate text-sm font-semibold\",\n !live && \"text-muted-foreground\"\n )}\n >\n {name}\n </span>\n <BillingStatusBadge status={status} />\n </div>\n <p className=\"text-sm text-muted-foreground tabular-nums\">\n {[when, paidWith].filter(Boolean).join(\" · \") ||\n t(\"common.notAvailable\")}\n </p>\n {price ? (\n <p\n className={cn(\n \"text-sm tabular-nums\",\n !live && \"text-muted-foreground\"\n )}\n >\n <span className=\"font-medium\">{price}</span>\n {interval ? (\n <span className=\"text-muted-foreground\"> {interval}</span>\n ) : null}\n </p>\n ) : null}\n {s.status === \"past_due\" || s.status === \"awaiting_method\" ? (\n <p className=\"text-sm text-destructive\">\n {t(\"subscriptions.pastDue\")}\n </p>\n ) : null}\n {rowError?.id === s.id ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {rowError.message}\n </p>\n ) : null}\n </div>\n <div className=\"flex flex-wrap gap-2 @md:justify-end\">\n {s.resumable ? (\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={!!pending}\n onClick={() => void resume(s)}\n >\n {pending === \"resume\" ? <Spinner /> : null}\n {pending === \"resume\"\n ? t(\"subscriptions.updating\")\n : t(\"subscriptions.resume\")}\n </Button>\n ) : null}\n {portal ? (\n <a\n href={portal}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n className={buttonVariants({\n variant: \"outline\",\n size: \"sm\",\n })}\n >\n {t(\"subscriptions.manageAtProvider\")}\n <HugeiconsIcon icon={ArrowUpRight01Icon} aria-hidden />\n </a>\n ) : null}\n {canChangeCard ? (\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={!!pending}\n aria-label={t(\"subscriptions.changeCardLabel\", { name })}\n onClick={() => {\n setRowError(null)\n setChangingCard(s)\n }}\n >\n {pending === \"payment_method\" ? <Spinner /> : null}\n {t(\"subscriptions.changeCard\")}\n </Button>\n ) : null}\n {canCancel ? (\n <Button\n variant=\"ghost\"\n size=\"sm\"\n className=\"text-muted-foreground hover:text-destructive\"\n disabled={!!pending}\n aria-label={t(\"subscriptions.cancelLabel\", { name })}\n onClick={() => {\n setRowError(null)\n setCancelling(s)\n }}\n >\n {pending &&\n pending !== \"resume\" &&\n pending !== \"payment_method\" &&\n pending !== \"change_tier\" ? (\n <Spinner />\n ) : null}\n {t(\"subscriptions.cancel\")}\n </Button>\n ) : null}\n </div>\n {footer ? (\n <div\n data-testid=\"subscription-footer\"\n className=\"border-t border-border/60 pt-3 @md:col-span-2\"\n >\n {footer}\n </div>\n ) : null}\n </li>\n )\n })}\n </ul>\n )\n }\n\n return (\n <Section\n title={t(\"subscriptions.title\")}\n description={t(\"subscriptions.description\")}\n appearance={appearance}\n className={className}\n data-testid=\"subscriptions-panel\"\n >\n {body}\n {state.subscriptions !== null && state.error ? (\n <div className=\"pt-3\">\n <ErrorState error={state.error} onRetry={state.refetch} />\n </div>\n ) : null}\n {notice}\n <ChangeCardDialog\n key={`card-${changingCard?.id ?? \"closed\"}`}\n subscription={changingCard}\n name={changingCard ? subscriptionName(changingCard, m) : \"\"}\n onOpenChange={(open) => !open && setChangingCard(null)}\n appearance={appearance}\n pending={\n !!changingCard && state.pending[changingCard.id] === \"payment_method\"\n }\n onConfirm={async (paymentMethodId) => {\n if (!changingCard) return null\n const error = await state.setPaymentMethod(\n changingCard.id,\n paymentMethodId\n )\n if (!error) {\n setChangingCard(null)\n announce(t(\"changeCard.done\"))\n }\n return error\n }}\n />\n <CancelSubscriptionDialog\n key={cancelling?.id ?? \"closed\"}\n open={cancelling !== null}\n onOpenChange={(open) => !open && setCancelling(null)}\n name={cancelling ? subscriptionName(cancelling, m) : \"\"}\n onChain={onChain}\n appearance={appearance}\n pending={cancelling ? state.pending[cancelling.id] : undefined}\n onConfirm={async (reason) => {\n if (!cancelling) return null\n const error = await state.cancel(\n cancelling.id,\n reason,\n sendSolanaTransaction\n )\n if (!error) announce(t(\"cancel.done\"))\n return error\n }}\n />\n </Section>\n )\n}\n","import { cn } from \"cn\"\n\nimport type { CheckoutAppearance } from \"#orck/appearance\"\nimport type { SendSolanaTransaction } from \"#orck/client/client\"\nimport { BillingUiRoot } from \"#orck/scope\"\nimport { PaymentHistory } from \"./payment-history\"\nimport {\n PaymentMethodsPanel,\n type PaymentMethodsPanelProps,\n} from \"./payment-methods-panel\"\nimport {\n SubscriptionsPanel,\n type SubscriptionsPanelProps,\n} from \"./subscriptions-panel\"\n\nexport interface AccountBillingProps {\n cardSetupReturnURL?: PaymentMethodsPanelProps[\"cardSetupReturnURL\"]\n /** Offers to make a card the one that collects this currency's invoices. */\n collectionCurrency?: string\n /** Billing country to preselect when adding a card. */\n defaultCountry?: string\n sendSolanaTransaction?: SendSolanaTransaction\n plansHref?: string\n renderSubscriptionFooter?: SubscriptionsPanelProps[\"renderSubscriptionFooter\"]\n historyPageSize?: number\n appearance?: CheckoutAppearance\n className?: string\n}\n\n/** Subscriptions, payment methods and history in one column. */\nexport function AccountBilling({\n cardSetupReturnURL,\n collectionCurrency,\n defaultCountry,\n sendSolanaTransaction,\n plansHref,\n renderSubscriptionFooter,\n historyPageSize,\n appearance,\n className,\n}: AccountBillingProps) {\n return (\n <BillingUiRoot\n appearance={appearance}\n className={cn(\"grid gap-6\", className)}\n data-testid=\"account-billing\"\n >\n <SubscriptionsPanel\n sendSolanaTransaction={sendSolanaTransaction}\n plansHref={plansHref}\n renderSubscriptionFooter={renderSubscriptionFooter}\n appearance={appearance}\n />\n <PaymentMethodsPanel\n cardSetupReturnURL={cardSetupReturnURL}\n collectionCurrency={collectionCurrency}\n defaultCountry={defaultCountry}\n appearance={appearance}\n />\n <PaymentHistory pageSize={historyPageSize} appearance={appearance} />\n </BillingUiRoot>\n )\n}\n","import type { BillingClient } from \"./client/client\"\nimport { loadStripeFor } from \"./lib/stripe\"\nimport { canAuthenticatePayment, type PspConfig } from \"./psp\"\n\n/**\n * Completes the provider challenge (3-D Secure) a pending payment operation\n * waits on. \"not_required\" when the provider has none outstanding; the\n * operation's own status remains the result.\n */\nexport async function authenticatePayment(\n client: BillingClient,\n operationId: string,\n psp: PspConfig\n): Promise<\"authenticated\" | \"not_required\"> {\n if (!canAuthenticatePayment(psp)) return \"not_required\"\n const { client_secret: secret } =\n await client.getPaymentAuthentication(operationId)\n if (!secret) return \"not_required\"\n const stripe = await loadStripeFor(psp.config!.publishable_key!)\n const result = await stripe.confirmCardPayment(secret)\n if (result.error)\n throw new Error(result.error.message ?? \"Authentication failed.\")\n await client.confirmPaymentAuthentication(operationId)\n return \"authenticated\"\n}\n","// CCBill credit-card hand-off uses the compact billing identity below. Name\n// stays canonical; the server binds verified email/IP and projects the provider.\nimport {\n BillingTextField,\n CountryField,\n PostalField,\n} from \"#orck/components/billing-fields\"\nimport type { CCBillBilling } from \"#orck/lib/ccbill\"\n\nexport function CCBillFields({\n idPrefix,\n value,\n onChange,\n disabled,\n error,\n}: {\n idPrefix: string\n value: CCBillBilling\n onChange: (next: CCBillBilling) => void\n disabled?: boolean\n error?: string\n}) {\n const set = (key: keyof CCBillBilling) => (next: string) =>\n onChange({ ...value, [key]: next })\n return (\n <>\n <BillingTextField\n id={`${idPrefix}-name-on-card`}\n name=\"name_on_card\"\n label=\"Name on card\"\n value={value.name_on_card}\n onChange={set(\"name_on_card\")}\n autoComplete=\"cc-name\"\n placeholder=\"Name as shown on card\"\n disabled={disabled}\n maxLength={200}\n required\n />\n <div className=\"grid grid-cols-2 gap-3\">\n <CountryField\n id={`${idPrefix}-country`}\n value={value.country}\n onChange={set(\"country\")}\n disabled={disabled}\n />\n <PostalField\n id={`${idPrefix}-zip`}\n value={value.zip}\n country={value.country}\n onChange={set(\"zip\")}\n disabled={disabled}\n required\n />\n </div>\n {error ? (\n <p className=\"text-[13px] text-destructive\" role=\"alert\">\n {error}\n </p>\n ) : null}\n </>\n )\n}\n","// CCBill credit-card identity. Verified account email and customer IP remain\n// server-owned; configurable street/city/state fields are not collected here.\nimport { z } from \"zod\"\n\nimport { countryCodeSchema, nameOnCardSchema } from \"#orck/lib/billing\"\n\nexport const ccbillBillingSchema = z.object({\n name_on_card: nameOnCardSchema,\n zip: z.string().trim().min(1, \"ZIP is required\"),\n country: countryCodeSchema,\n})\n\nexport type CCBillBilling = z.infer<typeof ccbillBillingSchema>\n\nexport const emptyCCBillBilling: CCBillBilling = {\n name_on_card: \"\",\n zip: \"\",\n country: \"\",\n}\n","// Customer-facing rail vocabulary. Unknown rails are not rendered — a rail\n// the UI cannot execute must not be offered.\nimport type { PaymentOption } from \"#orck/types\"\n\nexport interface RailMeta {\n label: string\n hint?: string\n}\n\n// A card taken in the page reads \"Card\" whichever PSP charges it.\nexport function railMeta(option: PaymentOption): RailMeta {\n if (\n option.driver === \"collect_js\" ||\n option.driver === \"card\" ||\n option.driver === \"stripe_elements\"\n )\n return { label: \"Card\" }\n return RAIL_META[option.rail]\n}\n\nexport const RAIL_META: Record<string, RailMeta> = {\n nmi: { label: \"Card\" },\n stripe: { label: \"Stripe\", hint: \"Opens Stripe\" },\n ccbill: { label: \"CCBill\", hint: \"Opens CCBill\" },\n // The Solana hint is not static: it names the token the host bound to the\n // option (see solanaToken), so the buyer sees the mint they will actually pay\n // with, on the network the host is actually on.\n solana: { label: \"Crypto\" },\n}\n\n// The Solana token the host bound to an option, read from its public_config:\n// - token_symbol — required; the SPL mint the price is bound to (USDC, USD1…).\n// - token_name — optional buyer-facing name (\"USD Coin\").\n// - network — optional Solana cluster (\"mainnet-beta\", \"devnet\",\n// \"testnet\"); anything but mainnet-beta is named in the UI so a\n// test-network payment is never mistaken for a real one.\n// The package never assumes a token: an option without token_symbol is not\n// offered (supportedOptions) — a rail the UI cannot execute must not be shown.\nexport interface SolanaToken {\n symbol: string\n name?: string\n network?: string\n}\n\nexport function solanaToken(option: PaymentOption): SolanaToken | undefined {\n const symbol = option.public_config?.token_symbol?.trim().toUpperCase()\n if (!symbol) return undefined\n const name = option.public_config?.token_name?.trim()\n const network = option.public_config?.network?.trim().toLowerCase()\n return {\n symbol,\n name: name || undefined,\n network: network || undefined,\n }\n}\n\nexport function solanaHint(token: SolanaToken): string {\n const label =\n token.name && token.name.toUpperCase() !== token.symbol\n ? `${token.name} (${token.symbol})`\n : token.symbol\n const chain =\n token.network && token.network !== \"mainnet-beta\"\n ? `Solana ${token.network}`\n : \"Solana\"\n return `${label} on ${chain}`\n}\n\nexport function supportedOptions(options: PaymentOption[]): PaymentOption[] {\n return options.filter((option) => {\n if (RAIL_META[option.rail] === undefined) return false\n if (option.driver === \"collect_js\" || option.driver === \"card\")\n return option.rail === \"nmi\"\n if (option.driver === \"stripe_elements\") return option.rail === \"stripe\"\n if (option.driver === \"redirect\")\n return option.rail === \"stripe\" || option.rail === \"ccbill\"\n return (\n option.driver === \"solana_pay\" &&\n option.rail === \"solana\" &&\n solanaToken(option) !== undefined\n )\n })\n}\n","// The method list: flat hairline-separated rows on a shared radio group.\n// Selection reads through the filled radio and the row title going ink —\n// never a highlighted container (containment budget: one, owned by the\n// host). Each row expands its body in place.\nimport { cn } from \"cn\"\nimport { Label } from \"#orck/components/ui/label\"\nimport { RadioGroup, RadioGroupItem } from \"#orck/components/ui/radio-group\"\nimport { railMeta, solanaHint, solanaToken } from \"#orck/lib/rail-meta\"\nimport type { PaymentOption } from \"#orck/types\"\n\nexport function MethodList({\n rails,\n selected,\n onSelect,\n disabled,\n idPrefix,\n renderBody,\n}: {\n rails: PaymentOption[]\n selected: string\n onSelect: (optionID: string) => void\n disabled?: boolean\n idPrefix: string\n renderBody: (option: PaymentOption, active: boolean) => React.ReactNode\n}) {\n // One rail needs no chooser: render its body alone.\n if (rails.length === 1)\n return (\n <div className=\"[&>div]:pt-0 [&>div]:pb-0 [&>div]:pl-0\">\n {renderBody(rails[0], true)}\n </div>\n )\n return (\n <RadioGroup\n aria-label=\"Payment method\"\n className=\"grid w-full gap-0\"\n value={selected}\n onValueChange={(value) => {\n if (typeof value === \"string\" && value) onSelect(value)\n }}\n disabled={disabled}\n >\n {rails.map((option) => {\n const meta = railMeta(option)\n const token = option.rail === \"solana\" ? solanaToken(option) : undefined\n const hint = token ? solanaHint(token) : meta.hint\n const active = option.id === selected\n const controlId = `${idPrefix}-option-${option.id}`\n return (\n <div\n key={option.id}\n className=\"border-t border-[color:var(--orck-hairline)] first:border-t-0\"\n >\n <Label\n htmlFor={controlId}\n className={cn(\n \"flex cursor-pointer items-center gap-2.5 py-[13px] text-sm font-medium text-muted-foreground select-none\",\n active && \"font-semibold text-foreground\",\n disabled && \"cursor-default\"\n )}\n >\n <RadioGroupItem id={controlId} value={option.id} />\n {meta.label}\n {hint ? (\n <span className=\"ml-auto text-xs font-normal text-[color:var(--orck-faint)]\">\n {hint}\n </span>\n ) : null}\n </Label>\n {renderBody(option, active)}\n </div>\n )\n })}\n </RadioGroup>\n )\n}\n\nexport function MethodBody({\n children,\n hidden,\n}: {\n children: React.ReactNode\n hidden?: boolean\n}) {\n return (\n <div\n aria-hidden={hidden || undefined}\n className={cn(\n \"grid gap-3.5 pt-1 pb-[18px] pl-[26px]\",\n hidden && \"hidden\"\n )}\n >\n {children}\n </div>\n )\n}\n","// Solana Pay transfer request: the official SDK owns QR rendering while the\n// checkout owns lifecycle copy and the same-device wallet link.\nimport * as React from \"react\"\n\nimport { buttonVariants } from \"#orck/components/ui/button\"\nimport { cn } from \"cn\"\n\n// Keep the official renderer's full quiet zone. Cropping it makes the tile\n// denser but materially reduces scan reliability on lower-quality cameras.\nconst QR_SIZE = 208\n\nexport function SolanaBody({\n amountLabel,\n payload,\n statusLine,\n}: {\n amountLabel: string\n payload?: string\n statusLine: string\n}) {\n const qrRef = React.useRef<HTMLDivElement | null>(null)\n const [qrState, setQrState] = React.useState<\"loading\" | \"ready\" | \"failed\">(\n \"loading\"\n )\n\n React.useEffect(() => {\n const container = qrRef.current\n if (!container || !payload) return\n\n let canceled = false\n container.replaceChildren()\n setQrState(\"loading\")\n void import(\"@solana/pay\")\n .then(({ createQR }) => {\n if (canceled) return\n createQR(payload, QR_SIZE, \"#ffffff\", \"#18181b\").append(container)\n setQrState(\"ready\")\n })\n .catch(() => {\n if (!canceled) setQrState(\"failed\")\n })\n return () => {\n canceled = true\n container.replaceChildren()\n }\n }, [payload])\n\n return (\n <div className=\"grid justify-items-center gap-3 py-1\">\n <div className=\"grid place-items-center rounded-xl bg-white p-1 shadow-sm ring-1 ring-black/10\">\n {payload ? (\n <div\n role=\"img\"\n aria-label=\"Solana Pay QR code\"\n className=\"relative overflow-hidden rounded-lg\"\n style={{ width: QR_SIZE, height: QR_SIZE }}\n >\n <div ref={qrRef} className=\"absolute inset-0\" />\n {qrState === \"loading\" ? (\n <div\n aria-hidden\n className=\"absolute inset-0 animate-pulse rounded-lg bg-zinc-100\"\n />\n ) : null}\n {qrState === \"failed\" ? (\n <div className=\"absolute inset-0 grid place-items-center text-center text-xs text-zinc-600\">\n QR code unavailable\n </div>\n ) : null}\n </div>\n ) : (\n <div\n aria-hidden\n className=\"animate-pulse rounded-lg bg-zinc-100\"\n style={{ width: QR_SIZE, height: QR_SIZE }}\n />\n )}\n </div>\n <div className=\"text-[13px] font-medium text-balance\">\n Scan with a Solana wallet\n </div>\n <div\n className=\"text-center text-[12.5px] text-pretty text-muted-foreground tabular-nums\"\n aria-live=\"polite\"\n >\n {amountLabel} · {statusLine}\n </div>\n {payload ? (\n <a\n href={payload}\n className={cn(\n buttonVariants({ variant: \"secondary\" }),\n \"h-9 w-full max-w-56\"\n )}\n >\n Open in wallet\n </a>\n ) : null}\n </div>\n )\n}\n","// Reuse of a card the customer already stored with this merchant. Selecting\n// one skips gateway tokenization entirely — the pay request carries the\n// stored method's id instead of a fresh token. Rows stay surfaceless like the\n// rail list above them; the brand plate and ink shift carry selection, so the\n// containment budget still belongs to the host.\nimport { HugeiconsIcon } from \"@hugeicons/react\"\nimport { Add01Icon } from \"@hugeicons/core-free-icons\"\nimport { CardBrandPlate } from \"#orck/components/card-brands\"\n\nimport { Label } from \"#orck/components/ui/label\"\nimport { RadioGroup, RadioGroupItem } from \"#orck/components/ui/radio-group\"\nimport { cn } from \"cn\"\nimport type { SavedPaymentMethod } from \"#orck/types\"\n\nexport const NEW_CARD_VALUE = \"new\"\n\n// Brand plates carry the network's own wordmark treatment at small size:\n// recognizable at a glance without shipping licensed logo art.\nconst BRAND_PLATE: Record<string, string> = {\n visa: \"VISA\",\n mastercard: \"MC\",\n amex: \"AMEX\",\n discover: \"DISC\",\n jcb: \"JCB\",\n diners: \"DINERS\",\n}\n\nfunction brandPlate(brand?: string | null): string {\n const key = brand?.trim().toLowerCase() ?? \"\"\n return BRAND_PLATE[key] ?? \"CARD\"\n}\n\n// The plate is decorative; assistive tech gets the spoken brand instead.\nfunction brandName(brand?: string | null): string {\n const value = brand?.trim()\n if (!value) return \"Card\"\n return value[0].toUpperCase() + value.slice(1)\n}\n\nfunction expiryLabel(method: SavedPaymentMethod): string | undefined {\n const card = method.card\n if (!card?.exp_month || !card.exp_year) return undefined\n const month = String(card.exp_month).padStart(2, \"0\")\n return `${month}/${String(card.exp_year).slice(-2)}`\n}\n\nexport function SavedMethods({\n methods,\n value,\n onChange,\n disabled,\n idPrefix,\n}: {\n methods: SavedPaymentMethod[]\n value: string\n onChange: (value: string) => void\n disabled?: boolean\n idPrefix: string\n}) {\n return (\n <RadioGroup\n value={value}\n onValueChange={(next) => {\n if (typeof next === \"string\" && next) onChange(next)\n }}\n disabled={disabled}\n aria-label=\"Saved cards\"\n className=\"grid gap-0\"\n >\n {methods.map((method) => {\n const id = `${idPrefix}-${method.id}`\n const active = value === method.id\n const expires = expiryLabel(method)\n const brand = method.card?.brand\n const last4 = method.card?.last4\n return (\n <Label\n key={method.id}\n htmlFor={id}\n className={cn(\n \"flex cursor-pointer items-center gap-3 py-1.5 select-none\",\n disabled && \"cursor-default\"\n )}\n >\n <RadioGroupItem id={id} value={method.id} />\n <CardBrandPlate\n brand={brand ?? undefined}\n fallback={brandPlate(brand)}\n />\n <span\n className={cn(\n \"min-w-0 flex-1 truncate text-sm font-medium text-muted-foreground tabular-nums transition-colors\",\n active && \"font-semibold text-foreground\"\n )}\n >\n <span className=\"sr-only\">\n {brandName(brand)} card ending {last4}\n {expires ? `, expires ${expires}` : \"\"}\n </span>\n <span aria-hidden>\n {brandName(brand)} •••• {last4 ?? \"····\"}\n {expires ? (\n <span className=\"font-normal text-muted-foreground\">\n {\" \"}\n · {expires}\n </span>\n ) : null}\n </span>\n </span>\n </Label>\n )\n })}\n <Label\n htmlFor={`${idPrefix}-new`}\n className={cn(\n \"flex cursor-pointer items-center gap-3 py-1.5 text-sm font-medium text-muted-foreground select-none\",\n value === NEW_CARD_VALUE && \"font-semibold text-foreground\",\n disabled && \"cursor-default\"\n )}\n >\n <RadioGroupItem id={`${idPrefix}-new`} value={NEW_CARD_VALUE} />\n <span\n aria-hidden\n className={cn(\n \"grid h-7 w-11 shrink-0 place-items-center rounded-md border border-dashed border-border text-muted-foreground transition-colors\",\n value === NEW_CARD_VALUE &&\n \"border-solid border-transparent bg-foreground text-background\"\n )}\n >\n <HugeiconsIcon icon={Add01Icon} className=\"size-3.5\" />\n </span>\n Use a new card\n </Label>\n </RadioGroup>\n )\n}\n","// Order summary: the money story. Full variant (wide containers) is the\n// receipt — line items, tax, a single emphasized rule above \"Due today\".\n// Compact variant (narrow containers) is one line: who + what left, how much\n// right.\nimport { cn } from \"cn\"\nimport { useMessages } from \"#orck/i18n/context\"\nimport type { Translator } from \"#orck/i18n/messages\"\nimport { addAmounts, formatAmount, type Amount } from \"#orck/lib/money\"\nimport { accessLabel, everyLabel, perLabel } from \"#orck/lib/period\"\nimport type { CheckoutLineItem, CheckoutSession } from \"#orck/types\"\n\nfunction renewsLabel(session: CheckoutSession, m: Translator) {\n const every = session.plan.auto_renew\n ? everyLabel(session.plan.billing_interval_hours, m)\n : null\n const access = !session.plan.auto_renew || session.plan.access_duration_hours !== session.plan.billing_interval_hours\n ? accessLabel(session.plan.access_duration_hours, m) ?? m.t(\"interval.permanent\")\n : undefined\n return [every ? m.t(\"checkout.renews\", { period: every }) : undefined, access]\n .filter(Boolean).join(\" · \") || undefined\n}\n\nfunction lineItems(\n session: CheckoutSession,\n m: Translator\n): CheckoutLineItem[] {\n if (session.line_items && session.line_items.length > 0) {\n return session.line_items\n }\n return [\n {\n label: session.plan.display_name,\n sublabel: renewsLabel(session, m),\n amount: session.plan.unit_amount,\n },\n ]\n}\n\n// dueToday is the host's figure when it sends one; otherwise the exact sum of\n// the line items and tax. An int64 overflow (null) is refused by the\n// formatter, never rounded.\nfunction dueToday(session: CheckoutSession, m: Translator): Amount | null {\n if (session.due_today !== undefined) return session.due_today\n return addAmounts(\n ...lineItems(session, m).map((item) => item.amount),\n session.tax ?? \"0\"\n )\n}\n\nexport function Eyebrow({\n children,\n className,\n}: {\n children: React.ReactNode\n className?: string\n}) {\n return (\n <div\n className={cn(\n \"text-[11px] font-semibold tracking-[0.09em] text-muted-foreground uppercase\",\n className\n )}\n >\n {children}\n </div>\n )\n}\n\nfunction Row({\n label,\n sublabel,\n amount,\n quiet,\n}: {\n label: string\n sublabel?: string\n amount: string\n quiet?: boolean\n}) {\n return (\n <div\n className={cn(\n \"flex items-start justify-between gap-4 border-b border-[color:var(--orck-hairline)] py-[11px] text-[13.5px]\",\n quiet && \"text-muted-foreground\"\n )}\n >\n <span>\n {label}\n {sublabel ? (\n <span className=\"block text-xs text-muted-foreground\">\n {sublabel}\n </span>\n ) : null}\n </span>\n <span className=\"whitespace-nowrap tabular-nums\">{amount}</span>\n </div>\n )\n}\n\nexport function OrderSummary({ session }: { session: CheckoutSession }) {\n const m = useMessages()\n const { currency, unit_decimals: decimals } = session.plan\n const money = (amount: Amount | null) =>\n formatAmount(amount, currency, decimals)\n return (\n <div className=\"grid content-start gap-5\">\n <Eyebrow>{session.merchant.display_name}</Eyebrow>\n <div className=\"text-[38px] leading-[1.05] font-semibold tracking-[-0.02em] tabular-nums\">\n {money(session.plan.unit_amount)}\n <span className=\"ml-1 text-[15px] font-normal tracking-normal text-muted-foreground\">\n {session.plan.auto_renew ? perLabel(session.plan.billing_interval_hours, m) : null}\n </span>\n </div>\n <div className=\"grid\">\n {lineItems(session, m).map((item) => (\n <Row\n key={item.label}\n label={item.label}\n sublabel={item.sublabel}\n amount={money(item.amount)}\n />\n ))}\n {session.tax !== undefined ? (\n <Row label=\"Tax\" amount={money(session.tax)} quiet />\n ) : null}\n <div className=\"-mt-px flex items-start justify-between gap-4 border-t border-border pt-[13px] text-[13.5px] font-semibold\">\n <span>Due today</span>\n <span className=\"whitespace-nowrap tabular-nums\">\n {money(dueToday(session, m))}\n </span>\n </div>\n </div>\n </div>\n )\n}\n\nexport function CompactSummary({\n session,\n className,\n}: {\n session: CheckoutSession\n className?: string\n}) {\n const m = useMessages()\n const renews = renewsLabel(session, m)\n const per = session.plan.auto_renew ? perLabel(session.plan.billing_interval_hours, m) : null\n return (\n <div\n className={cn(\n \"flex items-baseline justify-between gap-3 border-b border-[color:var(--orck-hairline)] pb-3.5\",\n className\n )}\n >\n <div className=\"grid gap-0.5\">\n <Eyebrow>{session.merchant.display_name}</Eyebrow>\n <div className=\"text-[12.5px] text-muted-foreground\">\n {session.plan.display_name}\n {renews ? ` · ${renews}` : \"\"}\n </div>\n </div>\n <div className=\"text-[22px] font-semibold tracking-[-0.01em] whitespace-nowrap tabular-nums\">\n {formatAmount(\n session.plan.unit_amount,\n session.plan.currency,\n session.plan.unit_decimals\n )}\n {per ? (\n <span className=\"text-xs font-normal text-muted-foreground\">\n {\" \"}\n {per.replace(\"/ \", \"/\")}\n </span>\n ) : null}\n </div>\n </div>\n )\n}\n","// Terminal and transitional views. Each is quiet: one fact, one instruction,\n// no dead controls.\nimport { Skeleton } from \"#orck/components/ui/skeleton\"\nimport { Eyebrow } from \"#orck/components/summary\"\n\nexport function LoadingSkeleton() {\n return (\n <div className=\"grid gap-4\" aria-hidden>\n <Skeleton className=\"h-3 w-24\" />\n <Skeleton className=\"h-6 w-52\" />\n <Skeleton className=\"mt-1.5 h-11 w-full\" />\n <Skeleton className=\"h-28 w-full\" />\n <Skeleton className=\"h-11 w-full\" />\n <Skeleton className=\"mt-1 h-[42px] w-full\" />\n </div>\n )\n}\n\nexport function SucceededView({\n merchantName,\n embedded,\n}: {\n merchantName: string\n embedded: boolean\n}) {\n return (\n <div className=\"grid gap-4\">\n <Eyebrow>{merchantName}</Eyebrow>\n <div className=\"grid justify-items-center gap-2.5 px-2 py-7 text-center\">\n <div className=\"grid size-11 place-items-center rounded-full bg-[color:var(--orck-success)]/12 text-[color:var(--orck-success)]\">\n <svg\n width=\"20\"\n height=\"20\"\n viewBox=\"0 0 20 20\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2.2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden\n >\n <path d=\"M4 10.5l4 4 8-9\" />\n </svg>\n </div>\n <div className=\"text-[15px] font-semibold\">Payment complete</div>\n <div className=\"text-[13px] text-muted-foreground\">\n {embedded ? \"You're all set.\" : `Returning to ${merchantName}…`}\n </div>\n </div>\n </div>\n )\n}\n\nexport function TerminalView({\n merchantName,\n headline,\n sub,\n}: {\n merchantName: string\n headline: string\n sub?: string\n}) {\n return (\n <div className=\"grid gap-4\">\n <Eyebrow>{merchantName}</Eyebrow>\n <div className=\"grid justify-items-center gap-2 px-2 py-7 text-center\">\n <div className=\"text-[15px] font-semibold\">{headline}</div>\n {sub ? (\n <div className=\"text-[13px] text-muted-foreground\">{sub}</div>\n ) : null}\n </div>\n </div>\n )\n}\n","/** The https URL a redirect rail may navigate to, or null. */\nexport function safeRedirectURL(raw: string): string | null {\n try {\n const url = new URL(raw)\n if (url.protocol !== \"https:\" || url.username || url.password) return null\n return url.href\n } catch {\n return null\n }\n}\n","// Checkout — the entire flow as one self-contained component. Hosts render\n// it inline on any page; CheckoutModal wraps it in a dialog; the hosted page\n// is another thin host. Its only inputs are a CheckoutSource (data), an\n// appearance (theming), and lifecycle callbacks. The container query is the\n// mode switch: wide containers get the split layout, narrow ones the compact\n// stack.\n//\n// Cards are one panel: the saved cards for the checkout PSP, an inline new\n// card, and one button that is the payer's explicit confirmation of the\n// displayed terms. With a BillingProvider, a new card is saved to the\n// customer's account first and the payment charges it by id; a decline keeps\n// the buyer on the panel to pick another card and retry. A rail whose driver\n// is card takes the card in plain inputs and posts it to OpenRails: no\n// gateway script is loaded.\nimport * as React from \"react\"\n\nimport {\n appearanceStyle,\n appearanceTheme,\n type CheckoutAppearance,\n} from \"#orck/appearance\"\nimport { authenticatePayment } from \"#orck/authenticate\"\nimport { isBillingError, isServerError } from \"#orck/client/errors\"\nimport type { PaymentMethod } from \"#orck/client/types\"\nimport { CardBillingFields } from \"#orck/components/billing-fields\"\nimport { CardFields, NativeCardFields } from \"#orck/components/card-fields\"\nimport { CCBillFields } from \"#orck/components/ccbill-fields\"\nimport {\n ccbillBillingSchema,\n emptyCCBillBilling,\n type CCBillBilling,\n} from \"#orck/lib/ccbill\"\nimport { MethodBody, MethodList } from \"#orck/components/methods\"\nimport { solanaToken, supportedOptions } from \"#orck/lib/rail-meta\"\nimport { PayButton, TrustLine } from \"#orck/components/pay-button\"\nimport { SolanaBody } from \"#orck/components/qr\"\nimport { NEW_CARD_VALUE, SavedMethods } from \"#orck/components/saved-methods\"\nimport {\n LoadingSkeleton,\n SucceededView,\n TerminalView,\n} from \"#orck/components/states\"\nimport {\n StripeCardEntry,\n type StripeCardHandle,\n} from \"#orck/components/stripe-card\"\nimport { CompactSummary, OrderSummary } from \"#orck/components/summary\"\nimport { useMessages } from \"#orck/i18n/context\"\nimport {\n collectCardDisplay,\n useCollectJS,\n type CollectFieldErrors,\n} from \"#orck/lib/collect\"\nimport {\n billingDetailsOf,\n emptyNMIBilling,\n initialCountry,\n nmiBillingSchema,\n type NMIBilling,\n} from \"#orck/lib/billing\"\nimport { cardEntryDisplay, useCardEntry } from \"#orck/lib/card-entry\"\nimport { amountToDecimal, formatAmount } from \"#orck/lib/money\"\nimport { safeRedirectURL } from \"#orck/lib/redirect\"\nimport { everyLabel } from \"#orck/lib/period\"\nimport { isCardRail, railPsp } from \"#orck/psp\"\nimport { useOptionalBillingContext } from \"#orck/react/context\"\nimport { cn } from \"cn\"\nimport type { CheckoutSource } from \"#orck/source\"\nimport type {\n CheckoutPhase,\n CheckoutSession,\n NextAction,\n PaymentFailure,\n PaymentOption,\n PayRequest,\n PayResult,\n SavedPaymentMethod,\n} from \"#orck/types\"\n\n// Layout preference. Responsiveness always wins: the split layout only ever\n// renders when the container is genuinely wide enough for it.\n// - \"auto\": split on comfortably wide containers (≥48rem)\n// - \"wide\": prefer the split — it engages earlier (≥36rem); pairs with the\n// wide CheckoutModal\n// - \"compact\": always the stacked view, no matter how wide the container\nexport type CheckoutLayout = \"auto\" | \"wide\" | \"compact\"\n\nexport interface CheckoutProps {\n source: CheckoutSource\n appearance?: CheckoutAppearance\n layout?: CheckoutLayout\n /** Billing country to preselect; default: the browser locale's region. */\n defaultCountry?: string\n /** Return target after an off-page card verification (Stripe setup). */\n cardSetupReturnURL?: (setupId: string) => string\n // Embedded hosts get the result via callback; page hosts also redirect.\n onComplete?: (result: PayResult) => void\n /**\n * Leaves for a redirect rail's page. Default: navigate the top window,\n * which a nested frame may not do; <CheckoutPage> asks its app instead.\n */\n onRedirect?: (url: string) => void\n onPhaseChange?: (phase: CheckoutPhase) => void\n // Redirect hosts can announce the short return transition after success;\n // embedded/modal hosts stay put and use the settled confirmation copy.\n completionMode?: \"embedded\" | \"redirect\"\n className?: string\n}\n\nconst POLL_INTERVAL_MS = 3_000\nconst DECLINED = \"Your card was declined. Try another card.\"\n// A 5xx is shown at once. Hosts replay a retried payment under the same\n// idempotency identity, so trying again cannot charge twice.\nconst SERVER_FAILED =\n \"Payment service error. The payment was not confirmed. Try again in a moment.\"\nconst STATUS_UNAVAILABLE =\n \"Payment status is unavailable right now (service error). Still checking.\"\n\nfunction navigateTop(redirectURL: string): void {\n const href = safeRedirectURL(redirectURL)\n if (!href)\n throw new Error(\"The payment provider returned an invalid redirect\")\n // Cross-origin frames may navigate their top-level browsing context, but\n // cannot read methods such as Location.assign from the top window.\n const target = window.top ?? window\n target.location.href = href\n}\n\nfunction solanaAmountLabel(\n session: CheckoutSession,\n tokenSymbol: string,\n transactionURL?: string\n): string {\n if (transactionURL) {\n try {\n const amount = new URL(transactionURL).searchParams.get(\"amount\")\n if (amount && /^\\d+(?:\\.\\d+)?$/.test(amount))\n return `${amount} ${tokenSymbol}`.trim()\n } catch {\n // The wire schema already requires solana:, so retain the plan fallback.\n }\n }\n const { unit_amount, unit_decimals } = session.plan\n return `${amountToDecimal(unit_amount, unit_decimals) ?? unit_amount} ${tokenSymbol}`.trim()\n}\n\nfunction savedFrom(\n method: PaymentMethod,\n rail: PaymentOption\n): SavedPaymentMethod {\n return {\n id: method.id,\n option_id: rail.id,\n rail: rail.rail,\n card: method.card ?? null,\n }\n}\n\n// A card just saved, labelled from what the buyer typed until the PSP's own\n// facts arrive with the next read.\nfunction savedWithDisplay(\n saved: SavedPaymentMethod,\n display: { last_four?: string; card_type?: string }\n): SavedPaymentMethod {\n return {\n ...saved,\n card: saved.card ?? {\n brand: display.card_type ?? null,\n last4: display.last_four ?? null,\n },\n }\n}\n\n// Provider SDK errors carry customer-facing text (\"Your card was declined.\").\nfunction describe(cause: unknown, fallback: string): string {\n if (isBillingError(cause)) return cause.message || fallback\n return cause instanceof Error && cause.message ? cause.message : fallback\n}\n\n// solanaLink is the Solana Pay link a payment awaits, if any.\nconst solanaLink = (next?: NextAction | null) =>\n next?.type === \"solana_pay\" ? next.url : undefined\n\nconst awaitingPayment = (session: CheckoutSession | null) =>\n session?.status === \"processing\" ||\n (session?.status === \"requires_action\" && !!session.operation)\n\nexport function Checkout({\n source,\n appearance,\n layout = \"auto\",\n defaultCountry,\n cardSetupReturnURL,\n onComplete,\n onRedirect,\n onPhaseChange,\n completionMode = \"embedded\",\n className,\n}: CheckoutProps) {\n const m = useMessages()\n const billingContext = useOptionalBillingContext()\n const client = billingContext?.client\n const uid = React.useId().replace(/[^a-zA-Z0-9-]/g, \"\")\n const [phase, setPhase] = React.useState<CheckoutPhase>(\"loading\")\n const [session, setSession] = React.useState<CheckoutSession | null>(null)\n const [selected, setSelected] = React.useState<string>(\"\")\n const [payError, setPayError] = React.useState<string>()\n const [failure, setFailure] = React.useState<PaymentFailure>()\n const [billing, setBilling] =\n React.useState<CCBillBilling>(emptyCCBillBilling)\n const [cardBilling, setCardBilling] = React.useState<NMIBilling>(() => ({\n ...emptyNMIBilling,\n country: initialCountry(defaultCountry),\n }))\n const [solanaURL, setSolanaURL] = React.useState<string>()\n // Cards saved during this checkout, most recent first.\n const [addedCards, setAddedCards] = React.useState<SavedPaymentMethod[]>([])\n const [stripeComplete, setStripeComplete] = React.useState(false)\n const [stripeKey, setStripeKey] = React.useState(0)\n const [authenticating, setAuthenticating] = React.useState(false)\n const stripeCard = React.useRef<StripeCardHandle>(null)\n // Set once this component submitted a payment: a later definite decline\n // returns to the panel instead of a terminal page.\n const attempted = React.useRef(false)\n const mounted = React.useRef(true)\n const sourceRef = React.useRef(source)\n React.useEffect(() => {\n sourceRef.current = source\n }, [source])\n const phaseRef = React.useRef(phase)\n const solanaStartedFor = React.useRef<string | undefined>(undefined)\n\n // onPhaseChange rides a ref so changePhase stays referentially stable —\n // hosts pass inline callbacks (CheckoutModal does), and a changing identity\n // here would re-fire the load effect on every render.\n const onPhaseChangeRef = React.useRef(onPhaseChange)\n React.useEffect(() => {\n onPhaseChangeRef.current = onPhaseChange\n })\n const onCompleteRef = React.useRef(onComplete)\n React.useEffect(() => {\n onCompleteRef.current = onComplete\n })\n const onRedirectRef = React.useRef(onRedirect)\n React.useEffect(() => {\n onRedirectRef.current = onRedirect\n })\n const changePhase = React.useCallback((next: CheckoutPhase) => {\n phaseRef.current = next\n setPhase(next)\n onPhaseChangeRef.current?.(next)\n }, [])\n\n React.useEffect(() => {\n mounted.current = true\n return () => {\n mounted.current = false\n }\n }, [])\n\n // Card rails that save a card in the page need the customer's billing\n // client; without one (a hosted page) only token rails are offered.\n const usable = React.useCallback(\n (rails: PaymentOption[]) =>\n supportedOptions(rails).filter(\n (option) => option.driver !== \"stripe_elements\" || !!client\n ),\n [client]\n )\n\n // Load the session once per source; map its status straight to a phase.\n React.useEffect(() => {\n let canceled = false\n solanaStartedFor.current = undefined\n attempted.current = false\n // eslint-disable-next-line react-hooks/set-state-in-effect -- deliberate: a new source restarts the flow from loading\n changePhase(\"loading\")\n setSolanaURL(undefined)\n source\n .getSession()\n .then((loaded) => {\n if (canceled || !mounted.current) return\n setSession(loaded)\n setSolanaURL(solanaLink(loaded.next_action))\n const options = usable(loaded.options)\n if (loaded.status === \"succeeded\") {\n changePhase(\"succeeded\")\n onCompleteRef.current?.({\n status: \"succeeded\",\n payment_id: loaded.payment_id,\n subscription_id: loaded.subscription_id,\n })\n return\n }\n if (loaded.status === \"expired\" || loaded.status === \"canceled\") {\n changePhase(\"expired\")\n return\n }\n if (loaded.status === \"failed\") {\n changePhase(\"failed\")\n return\n }\n if (loaded.status === \"blocked\") {\n changePhase(\"blocked\")\n return\n }\n if (awaitingPayment(loaded)) {\n const card = options.find(isCardRail)\n if (card) setSelected(card.id)\n changePhase(\"processing\")\n return\n }\n if (options.length === 0) {\n changePhase(\"unavailable\")\n return\n }\n setSelected((current) =>\n options.some((option) => option.id === current)\n ? current\n : options[0].id\n )\n changePhase(\"ready\")\n })\n .catch(() => {\n if (!canceled && mounted.current) changePhase(\"error\")\n })\n return () => {\n canceled = true\n }\n }, [source, changePhase, usable])\n\n // Expiry is enforced client-side too, so the page never invites a payment\n // the backend will refuse.\n React.useEffect(() => {\n if (!session?.expires_at) return\n const expiresAt = session.expires_at\n const remaining = Date.parse(expiresAt) - Date.now()\n if (Number.isNaN(remaining)) return\n // setTimeout overflows past 2^31-1ms and fires immediately, so clamp and\n // re-check the wall clock on fire instead of trusting the timer.\n const delay = Math.min(Math.max(0, remaining), 2 ** 31 - 1)\n const timer = window.setTimeout(() => {\n if (phaseRef.current !== \"ready\") return\n if (Date.parse(expiresAt) - Date.now() <= 0) {\n changePhase(\"expired\")\n }\n }, delay)\n return () => window.clearTimeout(timer)\n }, [session, changePhase])\n\n const options = React.useMemo(\n () => (session ? usable(session.options) : []),\n [session, usable]\n )\n const active = options.find((option) => option.id === selected)\n const nmiOption = options.find((option) => option.driver === \"collect_js\")\n const savedMethods = React.useMemo(() => {\n if (!active || !isCardRail(active)) return []\n const seen = new Set<string>()\n return [...addedCards, ...(session?.saved_methods ?? [])].filter(\n (method) => {\n if (method.option_id !== active.id || seen.has(method.id)) return false\n seen.add(method.id)\n return true\n }\n )\n }, [active, addedCards, session])\n // Until the customer chooses, the most recent card stands pre-selected. Paying always sends the selected card's id; nothing\n // is implied server-side. Derived so it applies when the session arrives\n // after first render.\n const [savedChoice, setSavedChoice] = React.useState<string>()\n const savedMethodID =\n savedChoice &&\n (savedChoice === NEW_CARD_VALUE ||\n savedMethods.some((method) => method.id === savedChoice))\n ? savedChoice\n : (savedMethods[0]?.id ?? NEW_CARD_VALUE)\n const usingSavedMethod =\n savedMethodID !== NEW_CARD_VALUE &&\n savedMethods.some((method) => method.id === savedMethodID)\n const cardIds = React.useMemo(\n () => ({\n number: `orck-${uid}-cc-number`,\n expiry: `orck-${uid}-cc-expiry`,\n cvv: `orck-${uid}-cc-cvv`,\n }),\n [uid]\n )\n // Native card entry for a PSP that takes cards on OpenRails (driver card).\n const nativeCard = useCardEntry()\n const nativeCardRef = React.useRef(nativeCard)\n React.useEffect(() => {\n nativeCardRef.current = nativeCard\n })\n const nativeIds = React.useMemo(\n () => ({\n number: `orck-${uid}-card-number`,\n expiry: `orck-${uid}-card-expiry`,\n cvv: `orck-${uid}-card-cvc`,\n }),\n [uid]\n )\n const collect = useCollectJS({\n enabled:\n Boolean(nmiOption) &&\n (phase === \"ready\" ||\n (phase === \"processing\" && !awaitingPayment(session))),\n active: selected === nmiOption?.id,\n tokenizationKey: nmiOption?.public_config?.tokenization_key ?? \"\",\n scriptURL: nmiOption?.public_config?.tokenization_url ?? \"\",\n selectors: {\n number: `#${cardIds.number}`,\n expiry: `#${cardIds.expiry}`,\n cvv: `#${cardIds.cvv}`,\n },\n })\n\n const clearFailure = () => {\n setPayError(undefined)\n setFailure(undefined)\n }\n\n const showFailure = React.useCallback(\n (result: { failure?: PaymentFailure | null; failure_message?: string }) => {\n const next = result.failure ?? undefined\n setFailure(next)\n setPayError(next?.message || result.failure_message || DECLINED)\n },\n []\n )\n\n // Saves a newly entered card to the customer's account and selects it, so\n // a retry after a decline never enters or saves the card again.\n const saveNewCard = React.useCallback(\n async (rail: PaymentOption): Promise<PayRequest | null> => {\n if (rail.driver === \"stripe_elements\") {\n if (!client || !stripeCard.current) return null\n const id = await stripeCard.current.save()\n let saved: SavedPaymentMethod = {\n id,\n option_id: rail.id,\n rail: rail.rail,\n }\n try {\n const page = await client.listPaymentMethods({ limit: 100 })\n const method = page.data.find((item) => item.id === id)\n if (method) saved = savedFrom(method, rail)\n } catch {\n // The card is saved; its label arrives with the next session read.\n }\n billingContext?.notify({\n type: \"payment_method.added\",\n paymentMethodId: id,\n })\n setAddedCards((current) => [saved, ...current])\n setSavedChoice(id)\n setStripeKey((key) => key + 1)\n return { option_id: rail.id, payment_method_id: id }\n }\n const parsed = nmiBillingSchema.safeParse(cardBilling)\n if (!parsed.success) {\n setPayError(\n parsed.error.issues[0]?.message ?? \"Check the billing details\"\n )\n return null\n }\n if (rail.driver === \"card\") {\n // The card leaves the form here and goes to OpenRails only.\n const card = nativeCardRef.current.take()\n if (!card) return null\n if (!client)\n return {\n option_id: rail.id,\n card,\n billing_details: billingDetailsOf(parsed.data),\n }\n const display = cardEntryDisplay(card)\n const method = await client.addPaymentMethod({\n psp_id: rail.id,\n card,\n billing_details: billingDetailsOf(parsed.data),\n })\n billingContext?.notify({\n type: \"payment_method.added\",\n paymentMethodId: method.id,\n })\n setAddedCards((current) => [\n savedWithDisplay(savedFrom(method, rail), display),\n ...current,\n ])\n setSavedChoice(method.id)\n return { option_id: rail.id, payment_method_id: method.id }\n }\n const tokenized = await collect.tokenize()\n const display = collectCardDisplay(tokenized.card)\n if (!client) {\n return {\n option_id: rail.id,\n payment_token: tokenized.token,\n billing_details: billingDetailsOf(parsed.data),\n }\n }\n const method = await client.addPaymentMethod({\n psp_id: rail.id,\n payment_token: tokenized.token,\n billing_details: billingDetailsOf(parsed.data),\n })\n billingContext?.notify({\n type: \"payment_method.added\",\n paymentMethodId: method.id,\n })\n setAddedCards((current) => [\n savedWithDisplay(savedFrom(method, rail), display),\n ...current,\n ])\n setSavedChoice(method.id)\n return { option_id: rail.id, payment_method_id: method.id }\n },\n [billingContext, cardBilling, client, collect]\n )\n\n const authenticate = React.useCallback(\n async (operationID: string) => {\n if (!client || !active) return\n setAuthenticating(true)\n setPayError(undefined)\n try {\n await authenticatePayment(client, operationID, railPsp(active))\n } catch (cause) {\n if (mounted.current)\n setPayError(describe(cause, \"Card authentication was not completed.\"))\n } finally {\n if (mounted.current) setAuthenticating(false)\n }\n },\n [active, client]\n )\n\n const pay = React.useCallback(async () => {\n if (!session || !active || phase !== \"ready\") return\n clearFailure()\n changePhase(\"processing\")\n let submitted = false\n try {\n let request: PayRequest = { option_id: active.id }\n if (active.driver === \"redirect\" && active.rail === \"ccbill\") {\n const parsed = ccbillBillingSchema.safeParse(billing)\n if (!parsed.success) {\n setPayError(\n parsed.error.issues[0]?.message ?? \"Check the billing details\"\n )\n changePhase(\"ready\")\n return\n }\n request = {\n option_id: active.id,\n billing_details: billingDetailsOf(parsed.data),\n }\n }\n if (isCardRail(active) && usingSavedMethod) {\n request = { option_id: active.id, payment_method_id: savedMethodID }\n } else if (isCardRail(active)) {\n let saved: PayRequest | null\n try {\n saved = await saveNewCard(active)\n } catch (cause) {\n if (!mounted.current || sourceRef.current !== source) return\n setPayError(describe(cause, \"Card entry could not be completed.\"))\n changePhase(\"ready\")\n return\n }\n if (!mounted.current || sourceRef.current !== source) return\n if (!saved) {\n changePhase(\"ready\")\n return\n }\n request = saved\n }\n if (active.driver === \"solana_pay\") {\n // supportedOptions only offers Solana options with a bound token, so\n // the symbol the host bound is the one we pay with — never a default.\n request = {\n option_id: active.id,\n token_symbol: solanaToken(active)?.symbol,\n }\n }\n submitted = true\n attempted.current = true\n const result = await source.pay(request)\n if (!mounted.current || sourceRef.current !== source) return\n const next = result.next_action\n if (active.driver === \"redirect\" && next?.type === \"redirect_to_url\") {\n onCompleteRef.current?.(result)\n if (onRedirectRef.current) onRedirectRef.current(next.url)\n else navigateTop(next.url)\n return\n }\n if (\n active.driver === \"solana_pay\" &&\n result.status === \"requires_action\" &&\n next?.type === \"solana_pay\"\n ) {\n setSession((current) =>\n current\n ? { ...current, status: \"requires_action\", next_action: next }\n : current\n )\n setSolanaURL(next.url)\n changePhase(\"ready\")\n return\n }\n if (result.status === \"succeeded\") {\n changePhase(\"succeeded\")\n onCompleteRef.current?.(result)\n return\n }\n if (result.status === \"failed\") {\n showFailure(result)\n changePhase(\"ready\")\n return\n }\n if (result.status === \"blocked\") {\n setSession((current) =>\n current\n ? {\n ...current,\n status: \"blocked\",\n failure_message: result.failure_message,\n }\n : current\n )\n changePhase(\"blocked\")\n return\n }\n if (result.status === \"expired\" || result.status === \"canceled\") {\n setSession((current) =>\n current ? { ...current, status: result.status } : current\n )\n changePhase(\"expired\")\n return\n }\n if (result.status === \"requires_action\" && result.operation) {\n const operation = result.operation\n setSession((current) =>\n current\n ? { ...current, status: \"requires_action\", operation }\n : current\n )\n changePhase(\"processing\")\n await authenticate(operation.id)\n return\n }\n setSession((current) =>\n current ? { ...current, status: \"processing\" } : current\n )\n changePhase(\"processing\")\n } catch (err) {\n if (!mounted.current || sourceRef.current !== source) return\n if (submitted && isServerError(err)) {\n setPayError(SERVER_FAILED)\n changePhase(\"ready\")\n } else if (submitted) {\n setPayError(\n \"The payment result is not confirmed yet. Keep this window open while we check its status.\"\n )\n setSession((current) =>\n current ? { ...current, status: \"processing\" } : current\n )\n changePhase(\"processing\")\n } else {\n setPayError(describe(err, \"Card entry could not be completed.\"))\n changePhase(\"ready\")\n }\n }\n }, [\n active,\n authenticate,\n billing,\n changePhase,\n phase,\n saveNewCard,\n savedMethodID,\n session,\n showFailure,\n source,\n usingSavedMethod,\n ])\n\n // Solana has no submit button: selecting it creates one transfer request,\n // then the QR remains stable while the server watches its unique reference.\n React.useEffect(() => {\n if (\n !session ||\n active?.driver !== \"solana_pay\" ||\n phase !== \"ready\" ||\n solanaURL ||\n solanaStartedFor.current === session.id\n ) {\n return\n }\n solanaStartedFor.current = session.id\n void pay()\n }, [active?.driver, pay, phase, session, solanaURL])\n\n React.useEffect(() => {\n if (\n !session ||\n (!(phase === \"processing\" && awaitingPayment(session)) &&\n !(active?.driver === \"solana_pay\" && phase === \"ready\" && solanaURL))\n )\n return\n\n let canceled = false\n let timer: number | undefined\n const schedule = () => {\n timer = window.setTimeout(() => void poll(), POLL_INTERVAL_MS)\n }\n const poll = async () => {\n try {\n const loaded = await source.getSession()\n if (canceled || !mounted.current) return\n switch (loaded.status) {\n case \"succeeded\":\n setSession(loaded)\n changePhase(\"succeeded\")\n onCompleteRef.current?.({\n status: \"succeeded\",\n payment_id: loaded.payment_id,\n subscription_id: loaded.subscription_id,\n })\n return\n case \"failed\":\n if (attempted.current) {\n // A definite decline of this panel's attempt: back to the\n // cards, with the reason, for another card and a new attempt.\n setSession({ ...loaded, status: \"created\", operation: null })\n showFailure(loaded)\n changePhase(\"ready\")\n return\n }\n setSession(loaded)\n changePhase(\"failed\")\n return\n case \"blocked\":\n setSession(loaded)\n changePhase(\"blocked\")\n return\n case \"expired\":\n case \"canceled\":\n setSession(loaded)\n changePhase(\"expired\")\n return\n case \"requires_action\":\n if (loaded.operation) {\n setSession(loaded)\n schedule()\n return\n }\n schedule()\n return\n default:\n // Ready-looking reads can race an accepted write. Keep the local\n // pending presentation and poll; never re-enable card entry.\n schedule()\n }\n } catch (err) {\n if (canceled || !mounted.current) return\n if (isServerError(err)) setPayError(STATUS_UNAVAILABLE)\n schedule()\n }\n }\n\n schedule()\n return () => {\n canceled = true\n if (timer !== undefined) window.clearTimeout(timer)\n }\n }, [\n active?.driver,\n changePhase,\n phase,\n session,\n showFailure,\n solanaURL,\n source,\n ])\n\n const merchantName = session?.merchant.display_name ?? \"\"\n const solanaTokenSymbol =\n active?.rail === \"solana\" ? (solanaToken(active)?.symbol ?? \"\") : \"\"\n const processing = phase === \"processing\"\n const amount = session\n ? formatAmount(\n session.plan.unit_amount,\n session.plan.currency,\n session.plan.unit_decimals\n )\n : \"\"\n const renews = session?.plan.auto_renew\n ? everyLabel(session.plan.billing_interval_hours, m)\n : null\n const payLabel =\n active && session\n ? active.driver === \"redirect\"\n ? `Continue to ${active.rail === \"stripe\" ? \"Stripe\" : \"CCBill\"}`\n : renews\n ? `Subscribe for ${amount} ${renews}`\n : `Pay ${amount}`\n : \"\"\n\n // A decline about a specific field is shown next to it while the new card\n // entry is open; otherwise under the card choice.\n const newCardOpen = !!active && isCardRail(active) && !usingSavedMethod\n const collectErrors: CollectFieldErrors = { ...collect.fieldErrors }\n let postalError: string | undefined\n let inlineFailure = false\n if (\n failure?.field &&\n newCardOpen &&\n (active?.driver === \"collect_js\" || active?.driver === \"card\")\n ) {\n inlineFailure = true\n if (failure.field === \"number\") collectErrors.number = failure.message\n else if (failure.field === \"expiry\") collectErrors.expiry = failure.message\n else if (failure.field === \"cvc\") collectErrors.cvv = failure.message\n else if (failure.field === \"postal_code\") postalError = failure.message\n else inlineFailure = false\n }\n\n // Card errors sit with the cards; other rails keep the form-level line.\n const cardError =\n payError && active && isCardRail(active) && !inlineFailure\n ? payError\n : undefined\n const cardBody = (option: PaymentOption, isActive: boolean) => {\n const stripe = option.driver === \"stripe_elements\"\n const native = option.driver === \"card\"\n const entryOpen = isActive && !usingSavedMethod\n return (\n <MethodBody hidden={!isActive}>\n {savedMethods.length > 0 ? (\n <SavedMethods\n methods={savedMethods}\n value={savedMethodID}\n onChange={(next) => {\n setSavedChoice(next)\n clearFailure()\n }}\n disabled={processing}\n idPrefix={`orck-${uid}-saved`}\n />\n ) : null}\n {stripe ? (\n entryOpen && client ? (\n <StripeCardEntry\n key={stripeKey}\n ref={stripeCard}\n psp={railPsp(option)}\n client={client}\n returnURL={cardSetupReturnURL}\n defaultCountry={cardBilling.country || undefined}\n onCompleteChange={setStripeComplete}\n unavailableMessage={m.t(\"paymentMethods.unavailable\")}\n verificationPendingMessage={m.t(\n \"paymentMethods.verificationPending\"\n )}\n />\n ) : null\n ) : (\n // Card fields stay mounted once created so the Collect.js iframes\n // survive rail and card switches; hidden handles visibility.\n <div\n className={cn(\"grid gap-3\", usingSavedMethod && \"hidden\")}\n aria-hidden={usingSavedMethod || undefined}\n >\n <CardBillingFields\n idPrefix={`orck-${uid}-card`}\n value={cardBilling}\n onChange={(next) => {\n setCardBilling(next)\n clearFailure()\n }}\n disabled={processing || !isActive || usingSavedMethod}\n postalError={isActive ? postalError : undefined}\n />\n {native ? (\n <NativeCardFields\n ids={nativeIds}\n card={nativeCard}\n fieldErrors={isActive ? collectErrors : undefined}\n disabled={processing || !isActive || usingSavedMethod}\n />\n ) : (\n <CardFields\n ids={cardIds}\n preview={collect.preview}\n error={isActive ? collect.loadError : undefined}\n fieldErrors={isActive ? collectErrors : undefined}\n />\n )}\n </div>\n )}\n {isActive && cardError ? (\n <p className=\"text-[13px] text-destructive\" role=\"alert\">\n {cardError}\n </p>\n ) : null}\n {newCardOpen && isActive && client ? (\n <p className=\"text-xs text-muted-foreground\">\n {m.t(\"paymentMethods.saveNotice\")}\n </p>\n ) : null}\n </MethodBody>\n )\n }\n\n const paymentColumn = session ? (\n <form\n id={`orck-${uid}-payment-form`}\n name=\"openrails-checkout\"\n aria-label=\"Secure payment\"\n autoComplete=\"on\"\n noValidate\n className=\"grid content-start gap-4\"\n onSubmit={(event) => {\n event.preventDefault()\n void pay()\n }}\n >\n <CompactSummary\n session={session}\n className={cn(\n layout === \"auto\" && \"@3xl/orck:hidden\",\n layout === \"wide\" && \"@xl/orck:hidden\"\n )}\n />\n <MethodList\n rails={options}\n selected={selected}\n onSelect={(optionID) => {\n const next = options.find((option) => option.id === optionID)\n if (next?.driver === \"solana_pay\" && !solanaURL) {\n // A failed request may be retried by returning to Solana.\n solanaStartedFor.current = undefined\n }\n setSelected(optionID)\n clearFailure()\n }}\n disabled={processing}\n idPrefix={`orck-${uid}`}\n renderBody={(option, isActive) => {\n if (isCardRail(option)) return cardBody(option, isActive)\n if (!isActive) return null\n if (option.driver === \"solana_pay\") {\n return (\n <MethodBody>\n <SolanaBody\n amountLabel={solanaAmountLabel(\n session,\n solanaTokenSymbol,\n solanaURL\n )}\n payload={solanaURL}\n statusLine={\n solanaURL\n ? \"Watching for payment…\"\n : payError\n ? \"Payment request unavailable\"\n : \"Preparing payment…\"\n }\n />\n </MethodBody>\n )\n }\n if (option.driver === \"redirect\" && option.rail === \"ccbill\") {\n return (\n <MethodBody>\n <CCBillFields\n idPrefix={`orck-${uid}-ccbill`}\n value={billing}\n onChange={(next) => {\n setBilling(next)\n setPayError(undefined)\n }}\n disabled={processing}\n error={payError}\n />\n <p className=\"text-[13px] text-muted-foreground\">\n You’ll finish payment on CCBill’s secure page.\n </p>\n </MethodBody>\n )\n }\n return (\n <MethodBody>\n <p className=\"text-[13px] text-muted-foreground\">\n You’ll finish payment on Stripe’s secure page.\n </p>\n </MethodBody>\n )\n }}\n />\n {payError && active && active.rail !== \"ccbill\" && !isCardRail(active) ? (\n <p className=\"text-[13px] text-destructive\" role=\"alert\">\n {payError}\n </p>\n ) : null}\n {active && (active.driver !== \"solana_pay\" || Boolean(payError)) ? (\n <PayButton\n label={active.driver === \"solana_pay\" ? \"Try again\" : payLabel}\n processing={processing}\n disabled={\n isCardRail(active) &&\n !usingSavedMethod &&\n (active.driver === \"collect_js\"\n ? !collect.ready || !collect.valid || Boolean(collect.loadError)\n : active.driver === \"card\"\n ? !nativeCard.valid\n : !stripeComplete)\n }\n />\n ) : null}\n {renews && active && isCardRail(active) ? (\n <p className=\"-mt-1 text-center text-xs text-muted-foreground\">\n {`You agree to pay ${amount} ${renews} until you cancel. First charge today; cancel anytime.`}\n </p>\n ) : null}\n <TrustLine />\n </form>\n ) : null\n\n const pendingOperation =\n session?.status === \"requires_action\" ? session.operation : null\n\n return (\n <div\n className={cn(\"orck w-full text-sm leading-normal\", className)}\n data-orck-theme={appearanceTheme(appearance)}\n style={appearanceStyle(appearance)}\n >\n <span aria-live=\"polite\" className=\"sr-only\">\n {phase === \"loading\"\n ? \"Loading checkout\"\n : phase === \"processing\"\n ? \"Processing payment\"\n : phase === \"succeeded\"\n ? \"Payment complete\"\n : \"\"}\n </span>\n {phase === \"loading\" ? (\n <LoadingSkeleton />\n ) : phase === \"error\" ? (\n <TerminalView\n merchantName={merchantName || \"Checkout\"}\n headline=\"Checkout couldn’t load\"\n sub=\"Reload the page to try again.\"\n />\n ) : phase === \"expired\" ? (\n <TerminalView\n merchantName={merchantName}\n headline=\"This checkout link has expired\"\n sub={merchantName ? `Ask ${merchantName} for a new link.` : undefined}\n />\n ) : phase === \"failed\" ? (\n <TerminalView\n merchantName={merchantName}\n headline=\"Payment failed\"\n sub=\"No payment was completed. Start a new checkout to try again.\"\n />\n ) : phase === \"blocked\" ? (\n <TerminalView\n merchantName={merchantName}\n headline=\"This purchase isn’t available\"\n sub={session?.failure_message}\n />\n ) : phase === \"unavailable\" ? (\n <TerminalView\n merchantName={merchantName}\n headline=\"Checkout isn’t available right now\"\n />\n ) : phase === \"processing\" && awaitingPayment(session) ? (\n <div role=\"status\" className=\"grid gap-3 py-6 text-center\">\n <div className=\"font-semibold\">\n {pendingOperation\n ? \"Confirm with your bank\"\n : \"Confirming payment…\"}\n </div>\n <p className=\"text-muted-foreground\">\n {pendingOperation\n ? \"Your bank needs to confirm this payment.\"\n : \"We’re checking the payment status. Don’t start another payment.\"}\n </p>\n {pendingOperation && client && active && isCardRail(active) ? (\n <button\n type=\"button\"\n className=\"mx-auto h-9 rounded-[9px] bg-primary px-4 text-sm font-semibold text-primary-foreground disabled:opacity-60\"\n disabled={authenticating}\n onClick={() => void authenticate(pendingOperation.id)}\n >\n {authenticating ? \"Waiting for your bank…\" : \"Confirm payment\"}\n </button>\n ) : null}\n {payError ? (\n <p className=\"text-xs text-muted-foreground\">{payError}</p>\n ) : null}\n </div>\n ) : phase === \"succeeded\" ? (\n <SucceededView\n merchantName={merchantName}\n embedded={completionMode === \"embedded\"}\n />\n ) : session ? (\n <div\n className={cn(\n \"grid gap-10\",\n layout === \"auto\" &&\n \"@3xl/orck:grid-cols-[minmax(0,1fr)_minmax(0,1fr)] @3xl/orck:gap-16\",\n layout === \"wide\" &&\n \"@xl/orck:grid-cols-[minmax(0,1fr)_minmax(0,1fr)] @xl/orck:gap-12\"\n )}\n >\n {layout !== \"compact\" ? (\n <div\n className={cn(\n \"hidden\",\n layout === \"auto\" && \"@3xl/orck:block\",\n layout === \"wide\" && \"@xl/orck:block\"\n )}\n >\n <OrderSummary session={session} />\n </div>\n ) : null}\n <div>{paymentColumn}</div>\n </div>\n ) : null}\n </div>\n )\n}\n","// CheckoutModal — a host, not a flow. It supplies the one surface (the\n// Dialog) and renders the same Checkout inside. Closing is always possible:\n// an accepted payment settles on the server whether or not the modal stays\n// open. A successful payment closes on the host's terms via onComplete.\nimport * as React from \"react\"\n\nimport { appearanceStyle, appearanceTheme } from \"#orck/appearance\"\nimport { Checkout, type CheckoutProps } from \"#orck/checkout\"\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogTitle,\n} from \"#orck/components/ui/dialog\"\n\nexport interface CheckoutModalProps extends CheckoutProps {\n open: boolean\n onOpenChange: (open: boolean) => void\n /**\n * Rendered instead of the checkout while set, e.g. the host's sign-in.\n * Clear it to continue to payment in the same modal.\n */\n gate?: React.ReactNode\n}\n\nexport function CheckoutModal({\n open,\n onOpenChange,\n onPhaseChange,\n gate,\n ...checkoutProps\n}: CheckoutModalProps) {\n const compact = checkoutProps.layout === \"compact\"\n return (\n <Dialog open={open} onOpenChange={onOpenChange}>\n <DialogContent\n className={`orck max-h-[calc(100dvh-2rem)] max-w-[calc(100vw-2rem)] gap-0 overflow-hidden bg-background text-foreground ring-0 [&>[data-slot=dialog-close]]:top-5 [&>[data-slot=dialog-close]]:right-5 [&>[data-slot=dialog-close]]:text-foreground ${compact ? \"w-[420px] p-6\" : \"w-[860px] p-8 sm:max-w-[calc(100vw-2rem)]\"}`}\n data-orck-theme={appearanceTheme(checkoutProps.appearance)}\n style={appearanceStyle(checkoutProps.appearance)}\n showCloseButton\n >\n <DialogTitle className=\"sr-only\">Checkout</DialogTitle>\n <DialogDescription className=\"sr-only\">\n Complete your payment\n </DialogDescription>\n <div\n className={`min-h-0 touch-pan-y [scrollbar-width:none] overflow-y-auto overscroll-contain pr-6 [-webkit-overflow-scrolling:touch] [&::-webkit-scrollbar]:hidden ${compact ? \"max-h-[calc(100dvh-5rem)] pt-7\" : \"max-h-[calc(100dvh-6rem)]\"}`}\n >\n {gate ?? (\n <Checkout {...checkoutProps} onPhaseChange={onPhaseChange} />\n )}\n </div>\n </DialogContent>\n </Dialog>\n )\n}\n","// The frame protocol between an app's <CheckoutFrame> and the payment page's\n// <CheckoutPage>. Both sides check the other's window and origin on every\n// message; the page posts only to the origin recorded on its session.\nimport { z } from \"zod\"\n\nimport { checkoutSessionStatusSchema } from \"./types\"\n\nconst SOURCE = \"openrails-checkout\"\n\n/** The page's color scheme, chosen by the framing app. */\nexport type CheckoutFrameTheme = \"light\" | \"dark\" | \"auto\"\n\nconst pageMessageSchema = z.discriminatedUnion(\"type\", [\n z.object({ source: z.literal(SOURCE), type: z.literal(\"ready\") }),\n z.object({\n source: z.literal(SOURCE),\n type: z.literal(\"resize\"),\n height: z.number().finite().nonnegative(),\n }),\n z.object({\n source: z.literal(SOURCE),\n type: z.literal(\"complete\"),\n status: checkoutSessionStatusSchema,\n }),\n z.object({\n source: z.literal(SOURCE),\n type: z.literal(\"redirect\"),\n url: z.string(),\n }),\n])\nexport type PageMessage = z.infer<typeof pageMessageSchema>\n\nconst appMessageSchema = z.object({\n source: z.literal(SOURCE),\n type: z.literal(\"init\"),\n theme: z.enum([\"light\", \"dark\", \"auto\"]),\n})\nexport type AppMessage = z.infer<typeof appMessageSchema>\n\ntype Body<M> = M extends unknown ? Omit<M, \"source\"> : never\n\nexport const pageMessage = (body: Body<PageMessage>): PageMessage =>\n ({ source: SOURCE, ...body }) as PageMessage\n\nexport const appMessage = (body: Body<AppMessage>): AppMessage =>\n ({ source: SOURCE, ...body }) as AppMessage\n\nexport function parsePageMessage(data: unknown): PageMessage | null {\n const parsed = pageMessageSchema.safeParse(data)\n return parsed.success ? parsed.data : null\n}\n\nexport function parseAppMessage(data: unknown): AppMessage | null {\n const parsed = appMessageSchema.safeParse(data)\n return parsed.success ? parsed.data : null\n}\n\n/** The origin of a payment page URL, or null when it is not one. */\nexport function pageOrigin(url: string): string | null {\n try {\n const parsed = new URL(url)\n if (\n (parsed.protocol !== \"https:\" && parsed.protocol !== \"http:\") ||\n parsed.username ||\n parsed.password\n )\n return null\n return parsed.origin\n } catch {\n return null\n }\n}\n","// CheckoutPage — the shared payment page. A host serves it from one HTML entry\n// at Config.Checkout.PageURL behind the adapter's CheckoutFramePolicy.\n// The session id arrives in the URL fragment; the page reads and pays the\n// session with it and, when framed by the app that minted it, speaks the\n// frame protocol with that app only.\nimport * as React from \"react\"\n\nimport type { CheckoutAppearance } from \"#orck/appearance\"\nimport { Checkout, type CheckoutLayout } from \"#orck/checkout\"\nimport { createBillingClient, type BillingClient } from \"#orck/client/client\"\nimport { TerminalView } from \"#orck/components/states\"\nimport {\n pageMessage,\n parseAppMessage,\n type CheckoutFrameTheme,\n type PageMessage,\n} from \"#orck/frame\"\nimport { BillingUiRoot } from \"#orck/scope\"\nimport type { CheckoutSource } from \"#orck/source\"\nimport type { PayResult } from \"#orck/types\"\n\nexport interface CheckoutPageProps {\n /** OpenRails mount on this host. Default \"/billing/v1\". */\n baseUrl?: string\n /** Replaces the client built from `baseUrl`. */\n client?: BillingClient\n /**\n * Pay as the signed-in customer on this customer surface (its `/me`\n * prefix) instead of with the session id alone; see `checkoutSource`.\n */\n customerBase?: string\n /** This host's branding; the framing app chooses the theme. */\n appearance?: CheckoutAppearance\n layout?: CheckoutLayout\n defaultCountry?: string\n className?: string\n}\n\nconst sessionIdFromHash = () => window.location.hash.replace(/^#/, \"\").trim()\n\nexport function CheckoutPage({\n baseUrl,\n client,\n customerBase,\n appearance,\n layout = \"auto\",\n defaultCountry,\n className,\n}: CheckoutPageProps) {\n const [sessionId, setSessionId] = React.useState(sessionIdFromHash)\n React.useEffect(() => {\n const onHash = () => setSessionId(sessionIdFromHash())\n window.addEventListener(\"hashchange\", onHash)\n return () => window.removeEventListener(\"hashchange\", onHash)\n }, [])\n\n const billing = React.useMemo(\n () => client ?? createBillingClient({ baseUrl }),\n [client, baseUrl]\n )\n const framed = window.parent !== window\n // The app that minted the session, as the server recorded it.\n const [appOrigin, setAppOrigin] = React.useState<string>()\n const [theme, setTheme] = React.useState<CheckoutFrameTheme>()\n\n const source = React.useMemo<CheckoutSource | null>(() => {\n if (!sessionId) return null\n const inner = billing.checkoutSource(sessionId, { customerBase })\n return {\n async getSession() {\n const session = await inner.getSession()\n if (session.embed_origin) setAppOrigin(session.embed_origin)\n return session\n },\n pay: inner.pay,\n }\n }, [billing, sessionId, customerBase])\n\n const post = React.useCallback(\n (message: PageMessage) => {\n if (framed && appOrigin) window.parent.postMessage(message, appOrigin)\n },\n [framed, appOrigin]\n )\n\n React.useEffect(() => {\n if (!framed || !appOrigin) return\n const onMessage = (event: MessageEvent) => {\n if (event.source !== window.parent || event.origin !== appOrigin) return\n const message = parseAppMessage(event.data)\n if (message) setTheme(message.theme)\n }\n window.addEventListener(\"message\", onMessage)\n window.parent.postMessage(pageMessage({ type: \"ready\" }), appOrigin)\n return () => window.removeEventListener(\"message\", onMessage)\n }, [framed, appOrigin])\n\n const root = React.useRef<HTMLDivElement>(null)\n React.useEffect(() => {\n const element = root.current\n if (!element || !framed || !appOrigin) return\n const report = () =>\n post(\n pageMessage({\n type: \"resize\",\n height: Math.ceil(element.getBoundingClientRect().height),\n })\n )\n const observer = new ResizeObserver(report)\n observer.observe(element)\n report()\n return () => observer.disconnect()\n }, [framed, appOrigin, post])\n\n const onComplete = React.useCallback(\n (result: PayResult) => {\n if (result.status === \"succeeded\")\n post(pageMessage({ type: \"complete\", status: result.status }))\n },\n [post]\n )\n // A nested frame may not navigate the top window: its app does.\n const onRedirect = React.useCallback(\n (url: string) => post(pageMessage({ type: \"redirect\", url })),\n [post]\n )\n\n const pageAppearance: CheckoutAppearance = {\n ...appearance,\n theme: theme ?? appearance?.theme,\n }\n return (\n <div ref={root} className={className}>\n {source ? (\n <Checkout\n source={source}\n appearance={pageAppearance}\n layout={layout}\n defaultCountry={defaultCountry}\n completionMode=\"embedded\"\n onComplete={onComplete}\n onRedirect={framed && appOrigin ? onRedirect : undefined}\n />\n ) : (\n <BillingUiRoot appearance={pageAppearance}>\n <TerminalView\n merchantName=\"\"\n headline=\"This checkout link is incomplete\"\n sub=\"Start checkout again from the site you were buying on.\"\n />\n </BillingUiRoot>\n )}\n </div>\n )\n}\n","// CheckoutFrame — an app's view of the shared payment page. It frames the\n// minted session's url, sizes itself to the page, gives it the app's theme and\n// navigates the app for redirect rails. It exchanges messages with the page's\n// origin only. `onComplete` is a hint: confirm access from your own API.\nimport * as React from \"react\"\n\nimport {\n appMessage,\n pageOrigin,\n parsePageMessage,\n type CheckoutFrameTheme,\n} from \"#orck/frame\"\nimport { safeRedirectURL } from \"#orck/lib/redirect\"\nimport type { CheckoutSessionStatus } from \"#orck/types\"\n\nexport interface CheckoutFrameProps {\n /** The minted session's `url` (createCheckoutSession). */\n url: string\n onComplete?: (status: CheckoutSessionStatus) => void\n /** Default \"auto\": the buyer's system preference. */\n theme?: CheckoutFrameTheme\n /** Accessible name of the frame. */\n title?: string\n /** Height before the page reports its own, in pixels. Default 480. */\n minHeight?: number\n className?: string\n style?: React.CSSProperties\n}\n\nexport function CheckoutFrame({\n url,\n onComplete,\n theme = \"auto\",\n title = \"Secure checkout\",\n minHeight = 480,\n className,\n style,\n}: CheckoutFrameProps) {\n const frame = React.useRef<HTMLIFrameElement>(null)\n const origin = React.useMemo(() => pageOrigin(url), [url])\n const [height, setHeight] = React.useState<number>()\n const ready = React.useRef(false)\n const themeRef = React.useRef(theme)\n const onCompleteRef = React.useRef(onComplete)\n React.useEffect(() => {\n onCompleteRef.current = onComplete\n })\n\n React.useEffect(() => {\n ready.current = false\n if (!origin) return\n const onMessage = (event: MessageEvent) => {\n const page = frame.current?.contentWindow\n if (!page || event.source !== page || event.origin !== origin) return\n const message = parsePageMessage(event.data)\n if (!message) return\n switch (message.type) {\n case \"ready\":\n ready.current = true\n page.postMessage(\n appMessage({ type: \"init\", theme: themeRef.current }),\n origin\n )\n return\n case \"resize\":\n setHeight(Math.ceil(message.height))\n return\n case \"complete\":\n onCompleteRef.current?.(message.status)\n return\n case \"redirect\": {\n const href = safeRedirectURL(message.url)\n if (href) (window.top ?? window).location.href = href\n return\n }\n }\n }\n window.addEventListener(\"message\", onMessage)\n return () => window.removeEventListener(\"message\", onMessage)\n }, [origin, url])\n\n React.useEffect(() => {\n themeRef.current = theme\n const page = frame.current?.contentWindow\n if (ready.current && page && origin)\n page.postMessage(appMessage({ type: \"init\", theme }), origin)\n }, [theme, origin])\n\n if (!origin) return null\n return (\n <iframe\n ref={frame}\n src={url}\n title={title}\n allow=\"payment\"\n className={className}\n style={{\n width: \"100%\",\n border: 0,\n display: \"block\",\n ...style,\n height: Math.max(minHeight, height ?? 0),\n }}\n />\n )\n}\n","// Fixture sources: drive every UI state without a backend or gateway. Used\n// by previews and tests; the \"preview_\" tokenization key makes CardFields\n// render inert placeholders instead of live Collect.js iframes.\nimport type { CheckoutSource } from \"./source\"\nimport type { CheckoutSession, PayResult } from \"./types\"\n\nexport function fixtureSession(\n overrides?: Partial<CheckoutSession>\n): CheckoutSession {\n return {\n id: \"ocs_preview\",\n status: \"created\",\n merchant: { display_name: \"Acme Demo\" },\n plan: {\n display_name: \"Premium Membership\",\n unit_amount: \"99000000\",\n currency: \"USD\",\n unit_decimals: 6,\n billing_interval_hours: 720,\n auto_renew: true,\n access_duration_hours: 720,\n },\n tax: \"0\",\n options: [\n {\n id: \"option_1\",\n rail: \"nmi\",\n mode: \"subscription\",\n driver: \"collect_js\",\n public_config: {\n tokenization_key: \"preview_tokenization_key\",\n tokenization_url: \"preview://collect\",\n },\n },\n {\n id: \"option_2\",\n rail: \"stripe\",\n mode: \"subscription\",\n driver: \"redirect\",\n },\n {\n id: \"option_3\",\n rail: \"ccbill\",\n mode: \"subscription\",\n driver: \"redirect\",\n },\n {\n id: \"option_4\",\n rail: \"solana\",\n mode: \"one_off\",\n driver: \"solana_pay\",\n public_config: { token_symbol: \"USDC\", token_name: \"USD Coin\" },\n },\n ],\n saved_methods: [\n {\n id: \"pm_preview_visa\",\n option_id: \"option_1\",\n rail: \"nmi\",\n card: { brand: \"visa\", last4: \"4242\", exp_month: 12, exp_year: 2030 },\n },\n {\n id: \"pm_preview_mc\",\n option_id: \"option_1\",\n rail: \"nmi\",\n card: {\n brand: \"mastercard\",\n last4: \"5454\",\n exp_month: 3,\n exp_year: 2029,\n },\n },\n ],\n expires_at: new Date(Date.now() + 30 * 60 * 1000).toISOString(),\n ...overrides,\n }\n}\n\nexport function createFixtureSource(options?: {\n session?: Partial<CheckoutSession>\n payResult?: PayResult\n payDelayMs?: number\n loadDelayMs?: number\n}): CheckoutSource {\n return {\n async getSession() {\n if (options?.loadDelayMs) {\n await new Promise((resolve) => setTimeout(resolve, options.loadDelayMs))\n }\n return fixtureSession(options?.session)\n },\n async pay() {\n await new Promise((resolve) =>\n setTim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