@aglyn/plugins-commerce 1.14.0 → 1.15.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (214) hide show
  1. package/package.json +13 -13
  2. package/src/lib/components/account-subscriptions.d.ts +51 -0
  3. package/src/lib/components/account-subscriptions.js +168 -0
  4. package/src/lib/components/account-subscriptions.js.map +1 -0
  5. package/src/lib/components/account.js +12 -48
  6. package/src/lib/components/account.js.map +1 -1
  7. package/src/lib/components/cart.js +38 -9
  8. package/src/lib/components/cart.js.map +1 -1
  9. package/src/lib/components/commerce-console-page.js +6 -0
  10. package/src/lib/components/commerce-console-page.js.map +1 -1
  11. package/src/lib/components/commerce-console-sections.d.ts +1 -1
  12. package/src/lib/components/commerce-console-sections.js +5 -0
  13. package/src/lib/components/commerce-console-sections.js.map +1 -1
  14. package/src/lib/components/console/paid-media.d.ts +1 -0
  15. package/src/lib/components/console/paid-media.js +15 -4
  16. package/src/lib/components/console/paid-media.js.map +1 -1
  17. package/src/lib/components/console/payments-settings-card.component.js +1 -1
  18. package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
  19. package/src/lib/components/console/pos/pos-hardware-api.d.ts +10 -1
  20. package/src/lib/components/console/pos/pos-hardware-api.js.map +1 -1
  21. package/src/lib/components/console/pos/pos-hardware-buyer.component.js +2 -2
  22. package/src/lib/components/console/pos/pos-hardware-buyer.component.js.map +1 -1
  23. package/src/lib/components/console/pos/pos-hardware-sale-api.d.ts +2 -0
  24. package/src/lib/components/console/pos/pos-hardware-sale-api.js.map +1 -1
  25. package/src/lib/components/console/pos-cellular-control.component.d.ts +1 -1
  26. package/src/lib/components/console/pos-cellular-control.component.js +5 -5
  27. package/src/lib/components/console/pos-cellular-control.component.js.map +1 -1
  28. package/src/lib/components/console/pos-devices-card.component.js +2 -2
  29. package/src/lib/components/console/pos-devices-card.component.js.map +1 -1
  30. package/src/lib/components/console/pos-hardware-card.component.d.ts +5 -0
  31. package/src/lib/components/console/pos-hardware-card.component.js +77 -8
  32. package/src/lib/components/console/pos-hardware-card.component.js.map +1 -1
  33. package/src/lib/components/console/pos-hardware-orders-staff-page.component.js +137 -19
  34. package/src/lib/components/console/pos-hardware-orders-staff-page.component.js.map +1 -1
  35. package/src/lib/components/console/pos-page.component.js +19 -2
  36. package/src/lib/components/console/pos-page.component.js.map +1 -1
  37. package/src/lib/components/console/product-editor-dialog.component.js +21 -2
  38. package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
  39. package/src/lib/components/console/subscription-detail-dialog.component.d.ts +58 -0
  40. package/src/lib/components/console/subscription-detail-dialog.component.js +201 -0
  41. package/src/lib/components/console/subscription-detail-dialog.component.js.map +1 -0
  42. package/src/lib/components/console/subscriptions-card.component.d.ts +60 -0
  43. package/src/lib/components/console/subscriptions-card.component.js +282 -0
  44. package/src/lib/components/console/subscriptions-card.component.js.map +1 -0
  45. package/src/lib/components/hardware-terms-consent.d.ts +22 -0
  46. package/src/lib/components/hardware-terms-consent.js +85 -0
  47. package/src/lib/components/hardware-terms-consent.js.map +1 -0
  48. package/src/lib/components/product-detail.js +32 -8
  49. package/src/lib/components/product-detail.js.map +1 -1
  50. package/src/lib/components/quote-page-body.js +7 -3
  51. package/src/lib/components/quote-page-body.js.map +1 -1
  52. package/src/lib/components/related-products.js +6 -3
  53. package/src/lib/components/related-products.js.map +1 -1
  54. package/src/lib/components/storefront-payment-element.d.ts +7 -1
  55. package/src/lib/components/storefront-payment-element.js +11 -7
  56. package/src/lib/components/storefront-payment-element.js.map +1 -1
  57. package/src/lib/constants/operator-alerts.d.ts +1 -1
  58. package/src/lib/constants/operator-alerts.js +4 -4
  59. package/src/lib/constants/operator-alerts.js.map +1 -1
  60. package/src/lib/model/commerce-orders.d.ts +6 -2
  61. package/src/lib/model/commerce-orders.js.map +1 -1
  62. package/src/lib/model/commerce-payment-methods.d.ts +27 -16
  63. package/src/lib/model/commerce-payment-methods.js +11 -83
  64. package/src/lib/model/commerce-payment-methods.js.map +1 -1
  65. package/src/lib/model/commerce.d.ts +6 -0
  66. package/src/lib/model/commerce.js.map +1 -1
  67. package/src/lib/model/index.d.ts +1 -0
  68. package/src/lib/model/index.js +1 -0
  69. package/src/lib/model/index.js.map +1 -1
  70. package/src/lib/model/paid-media.d.ts +8 -0
  71. package/src/lib/model/paid-media.js +13 -0
  72. package/src/lib/model/paid-media.js.map +1 -1
  73. package/src/lib/model/pos-hardware-in-person.d.ts +23 -2
  74. package/src/lib/model/pos-hardware-in-person.js +52 -20
  75. package/src/lib/model/pos-hardware-in-person.js.map +1 -1
  76. package/src/lib/model/pos-hardware-tax-summary.d.ts +5 -1
  77. package/src/lib/model/pos-hardware-tax-summary.js +2 -1
  78. package/src/lib/model/pos-hardware-tax-summary.js.map +1 -1
  79. package/src/lib/model/pos-hardware-terms.d.ts +37 -2
  80. package/src/lib/model/pos-hardware-terms.js +68 -3
  81. package/src/lib/model/pos-hardware-terms.js.map +1 -1
  82. package/src/lib/model/pos-hardware.d.ts +101 -15
  83. package/src/lib/model/pos-hardware.js +128 -18
  84. package/src/lib/model/pos-hardware.js.map +1 -1
  85. package/src/lib/model/pos-reader-splash.js +2 -2
  86. package/src/lib/model/pos-reader-splash.js.map +1 -1
  87. package/src/lib/model/product-write.d.ts +3 -0
  88. package/src/lib/model/subscription-view.d.ts +90 -0
  89. package/src/lib/model/subscription-view.js +176 -0
  90. package/src/lib/model/subscription-view.js.map +1 -0
  91. package/src/lib/server/billing-webhook.d.ts +27 -6
  92. package/src/lib/server/billing-webhook.js +271 -81
  93. package/src/lib/server/billing-webhook.js.map +1 -1
  94. package/src/lib/server/cancel-order.js +4 -3
  95. package/src/lib/server/cancel-order.js.map +1 -1
  96. package/src/lib/server/cart-checkout.js +105 -23
  97. package/src/lib/server/cart-checkout.js.map +1 -1
  98. package/src/lib/server/cart.js +15 -3
  99. package/src/lib/server/cart.js.map +1 -1
  100. package/src/lib/server/catalog.js +58 -22
  101. package/src/lib/server/catalog.js.map +1 -1
  102. package/src/lib/server/checkout-session-expiry.d.ts +1 -1
  103. package/src/lib/server/checkout-session-expiry.js +19 -5
  104. package/src/lib/server/checkout-session-expiry.js.map +1 -1
  105. package/src/lib/server/checkout-status.js +4 -3
  106. package/src/lib/server/checkout-status.js.map +1 -1
  107. package/src/lib/server/checkout.js +98 -26
  108. package/src/lib/server/checkout.js.map +1 -1
  109. package/src/lib/server/connect.js +42 -11
  110. package/src/lib/server/connect.js.map +1 -1
  111. package/src/lib/server/draft-order.js +36 -7
  112. package/src/lib/server/draft-order.js.map +1 -1
  113. package/src/lib/server/manual-tax-rate.d.ts +11 -3
  114. package/src/lib/server/manual-tax-rate.js +10 -6
  115. package/src/lib/server/manual-tax-rate.js.map +1 -1
  116. package/src/lib/server/membership-account.d.ts +22 -0
  117. package/src/lib/server/membership-account.js +52 -8
  118. package/src/lib/server/membership-account.js.map +1 -1
  119. package/src/lib/server/native-checkout.d.ts +10 -3
  120. package/src/lib/server/native-checkout.js +8 -3
  121. package/src/lib/server/native-checkout.js.map +1 -1
  122. package/src/lib/server/payment-method-domains.d.ts +50 -9
  123. package/src/lib/server/payment-method-domains.js +150 -51
  124. package/src/lib/server/payment-method-domains.js.map +1 -1
  125. package/src/lib/server/payment-methods.js +3 -2
  126. package/src/lib/server/payment-methods.js.map +1 -1
  127. package/src/lib/server/pos-auth.d.ts +3 -3
  128. package/src/lib/server/pos-auth.js +3 -3
  129. package/src/lib/server/pos-auth.js.map +1 -1
  130. package/src/lib/server/pos-cellular-billing.js +1 -1
  131. package/src/lib/server/pos-cellular-billing.js.map +1 -1
  132. package/src/lib/server/pos-cellular-notify.js +1 -1
  133. package/src/lib/server/pos-cellular-notify.js.map +1 -1
  134. package/src/lib/server/pos-cellular.js +1 -1
  135. package/src/lib/server/pos-cellular.js.map +1 -1
  136. package/src/lib/server/pos-hardware-admin.js +86 -13
  137. package/src/lib/server/pos-hardware-admin.js.map +1 -1
  138. package/src/lib/server/pos-hardware-attach.js +5 -5
  139. package/src/lib/server/pos-hardware-attach.js.map +1 -1
  140. package/src/lib/server/pos-hardware-cancel.js +65 -0
  141. package/src/lib/server/pos-hardware-cancel.js.map +1 -1
  142. package/src/lib/server/pos-hardware-closure-notices.js +2 -5
  143. package/src/lib/server/pos-hardware-closure-notices.js.map +1 -1
  144. package/src/lib/server/pos-hardware-closure.js +5 -8
  145. package/src/lib/server/pos-hardware-closure.js.map +1 -1
  146. package/src/lib/server/pos-hardware-in-person.d.ts +2 -1
  147. package/src/lib/server/pos-hardware-in-person.js +72 -17
  148. package/src/lib/server/pos-hardware-in-person.js.map +1 -1
  149. package/src/lib/server/pos-hardware-notify.d.ts +2 -0
  150. package/src/lib/server/pos-hardware-notify.js +30 -5
  151. package/src/lib/server/pos-hardware-notify.js.map +1 -1
  152. package/src/lib/server/pos-hardware-readers.d.ts +25 -0
  153. package/src/lib/server/pos-hardware-readers.js +206 -85
  154. package/src/lib/server/pos-hardware-readers.js.map +1 -1
  155. package/src/lib/server/pos-hardware-returns.d.ts +8 -3
  156. package/src/lib/server/pos-hardware-returns.js +39 -7
  157. package/src/lib/server/pos-hardware-returns.js.map +1 -1
  158. package/src/lib/server/pos-hardware-sale-fields.d.ts +76 -0
  159. package/src/lib/server/pos-hardware-sale-fields.js +114 -1
  160. package/src/lib/server/pos-hardware-sale-fields.js.map +1 -1
  161. package/src/lib/server/pos-hardware-sale.d.ts +2 -0
  162. package/src/lib/server/pos-hardware-sale.js +1 -0
  163. package/src/lib/server/pos-hardware-sale.js.map +1 -1
  164. package/src/lib/server/pos-hardware-tax-return-source.js +7 -4
  165. package/src/lib/server/pos-hardware-tax-return-source.js.map +1 -1
  166. package/src/lib/server/pos-hardware-webhook.js +16 -3
  167. package/src/lib/server/pos-hardware-webhook.js.map +1 -1
  168. package/src/lib/server/pos-hardware.d.ts +14 -3
  169. package/src/lib/server/pos-hardware.js +83 -18
  170. package/src/lib/server/pos-hardware.js.map +1 -1
  171. package/src/lib/server/pos-ops-routes.js +2 -10
  172. package/src/lib/server/pos-ops-routes.js.map +1 -1
  173. package/src/lib/server/pos-order.js +5 -1
  174. package/src/lib/server/pos-order.js.map +1 -1
  175. package/src/lib/server/pos-stripe.d.ts +7 -7
  176. package/src/lib/server/pos-stripe.js +15 -13
  177. package/src/lib/server/pos-stripe.js.map +1 -1
  178. package/src/lib/server/pos-terminal.js +11 -3
  179. package/src/lib/server/pos-terminal.js.map +1 -1
  180. package/src/lib/server/quote-pay.d.ts +23 -1
  181. package/src/lib/server/quote-pay.js +111 -27
  182. package/src/lib/server/quote-pay.js.map +1 -1
  183. package/src/lib/server/quote.d.ts +2 -1
  184. package/src/lib/server/quote.js +12 -11
  185. package/src/lib/server/quote.js.map +1 -1
  186. package/src/lib/server/refund.js +13 -6
  187. package/src/lib/server/refund.js.map +1 -1
  188. package/src/lib/server/related.js +10 -3
  189. package/src/lib/server/related.js.map +1 -1
  190. package/src/lib/server/reserve.js +19 -6
  191. package/src/lib/server/reserve.js.map +1 -1
  192. package/src/lib/server/revenue-source.d.ts +6 -0
  193. package/src/lib/server/revenue-source.js +25 -9
  194. package/src/lib/server/revenue-source.js.map +1 -1
  195. package/src/lib/server/seller-stripe-account.d.ts +45 -0
  196. package/src/lib/server/seller-stripe-account.js +99 -0
  197. package/src/lib/server/seller-stripe-account.js.map +1 -0
  198. package/src/lib/server/storefront-tax-record.js +6 -1
  199. package/src/lib/server/storefront-tax-record.js.map +1 -1
  200. package/src/lib/server/storefront-tax.d.ts +33 -2
  201. package/src/lib/server/storefront-tax.js +39 -3
  202. package/src/lib/server/storefront-tax.js.map +1 -1
  203. package/src/lib/server/stream.d.ts +2 -0
  204. package/src/lib/server/stream.js +22 -2
  205. package/src/lib/server/stream.js.map +1 -1
  206. package/src/lib/server/stripe-refund.d.ts +15 -0
  207. package/src/lib/server/stripe-refund.js +54 -26
  208. package/src/lib/server/stripe-refund.js.map +1 -1
  209. package/src/lib/server/subscription-portal.js +8 -3
  210. package/src/lib/server/subscription-portal.js.map +1 -1
  211. package/src/lib/server/tax-return-source.js +5 -1
  212. package/src/lib/server/tax-return-source.js.map +1 -1
  213. package/src/lib/server.js +2 -2
  214. package/src/lib/server.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/components/quote-page-body.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as Aglyn from '@aglyn/aglyn'\nimport Alert from '@mui/material/Alert'\nimport Box from '@mui/material/Box'\nimport Button from '@mui/material/Button'\nimport Chip from '@mui/material/Chip'\nimport CircularProgress from '@mui/material/CircularProgress'\nimport Divider from '@mui/material/Divider'\nimport Paper from '@mui/material/Paper'\nimport Stack from '@mui/material/Stack'\nimport Typography from '@mui/material/Typography'\nimport type { StripeCheckoutContact } from '@stripe/stripe-js'\nimport { forwardRef, lazy, Suspense, useCallback, useEffect, useRef, useState } from 'react'\nimport {\n formatOrderMoney,\n readStorefrontCheckoutWallets,\n type QuotePageAddress,\n type QuotePageView,\n type StorefrontCheckoutWallets,\n} from '../model'\nimport type { QuotePageProps } from './quote-page'\nimport { QuoteProofPanel } from './quote-proof-panel'\nimport { StorefrontPaymentElementFallback } from './storefront-payment-element-fallback'\n\n/** The Payment Element, lazily: Stripe.js loads only when a customer presses Pay. */\nconst StorefrontPaymentElement = lazy(() =>\n import('./storefront-payment-element').then((module) => ({\n default: module.StorefrontPaymentElement,\n })),\n)\n\ntype LoadState =\n | { kind: 'loading' }\n | { kind: 'missing'; message: string }\n | { kind: 'replaced'; storeName: string; noun: string }\n | { kind: 'ready'; view: QuotePageView }\n\n/** `quote` or `invoice`, as the page says it (AGL-4099). */\nconst nounOf = (kind: unknown) => (kind === 'invoice' ? 'invoice' : 'quote')\n\n/** What is added when the customer pays: `shipping`, `tax`, `shipping and tax`, or nothing. */\nfunction addedAtPayment(view: Pick<QuotePageView, 'shippingAtPayment' | 'taxAtPayment'>): string {\n if (view.shippingAtPayment && view.taxAtPayment) return 'shipping and tax'\n if (view.shippingAtPayment) return 'shipping'\n return view.taxAtPayment ? 'tax' : ''\n}\n\n/** After a payment returns here, how often and how long the page asks whether it landed. */\nconst CONFIRM_POLL_MS = 2_000\nconst CONFIRM_POLLS = 15\n\nfunction dateLabel(atMs: number | null): string {\n if (!atMs) return ''\n return new Date(atMs).toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' })\n}\n\nfunction addressLines(address: QuotePageAddress): string[] {\n const cityLine = [address.city, [address.state, address.postalCode].filter(Boolean).join(' ')]\n .filter(Boolean)\n .join(', ')\n return [address.name, address.line1, address.line2, cityLine, address.country].filter(\n (line): line is string => Boolean(line),\n )\n}\n\nfunction stripeContact(address: QuotePageAddress | null): StripeCheckoutContact | undefined {\n if (!address?.country) return undefined\n return {\n name: address.name,\n address: {\n country: address.country,\n line1: address.line1,\n line2: address.line2,\n city: address.city,\n state: address.state,\n postal_code: address.postalCode,\n },\n }\n}\n\nfunction AddressBlock({ label, lines }: { label: string; lines: string[] }) {\n return (\n <Stack spacing={0.25} sx={{ minWidth: 0, flex: 1 }}>\n <Typography variant=\"overline\" color=\"text.secondary\">\n {label}\n </Typography>\n {lines.map((line, index) => (\n <Typography key={index} variant=\"body2\">\n {line}\n </Typography>\n ))}\n </Stack>\n )\n}\n\nfunction TotalRow({ label, value, strong }: { label: string; value: string; strong?: boolean }) {\n return (\n <Stack direction=\"row\" spacing={2} sx={{ justifyContent: 'space-between' }}>\n <Typography variant={strong ? 'subtitle1' : 'body2'} color={strong ? 'text.primary' : 'text.secondary'}>\n {label}\n </Typography>\n <Typography variant={strong ? 'subtitle1' : 'body2'} color={strong ? 'text.primary' : 'text.secondary'}>\n {value}\n </Typography>\n </Stack>\n )\n}\n\n/**\n * The customer's quote page (AGL-4094), loaded when the page draws it (see\n * `quote-page.tsx`): what a customer sees when they open\n * the pay link a business sent them. The commerce page resolver serves it at\n * `/pay-quote` inside the site's own header and footer; a business can also\n * place it on a page of their own design at that address.\n *\n * The quote is read AFTER hydration from `?q=&t=`, so the page itself is the\n * same for every customer and may be cached, and the quote never is. Pay asks\n * the server for a fresh payment for the quote as the page shows it: Stripe's\n * own page, or the payment form here when in-page payments are on. Nothing\n * here decides a quote is paid; after paying, the page reads that from the\n * server like any other visit.\n */\nconst QuotePageBody = forwardRef<HTMLDivElement, QuotePageProps>((props, ref) => {\n const { heading, ...rest } = props\n const nodeSx = Array.isArray(props['sx']) ? props['sx'] : [props['sx']]\n const { hostId } = Aglyn.useSite()\n const siteFetch = Aglyn.useSiteFetch()\n const [state, setState] = useState<LoadState>({ kind: 'loading' })\n const [paying, setPaying] = useState(false)\n const [payError, setPayError] = useState('')\n const [nativeCheckout, setNativeCheckout] = useState<{\n clientSecret: string\n publishableKey: string\n wallets?: StorefrontCheckoutWallets\n } | null>(null)\n /** What a return from paying turned out to be: still being confirmed, or not paid. */\n const [returned, setReturned] = useState<'confirming' | 'unconfirmed' | 'failed' | null>(null)\n const link = useRef({ quoteId: '', token: '', sessionId: '' })\n\n const load = useCallback(async (): Promise<LoadState> => {\n const { quoteId, token } = link.current\n try {\n const response = await siteFetch(\n `/api/commerce/quote-view?hostId=${encodeURIComponent(hostId ?? '')}` +\n `&q=${encodeURIComponent(quoteId)}&t=${encodeURIComponent(token)}`,\n )\n const payload = await response.json().catch(() => ({}))\n if (!response.ok) {\n return { kind: 'missing', message: String(payload?.error ?? 'We could not find that quote or invoice.') }\n }\n if (payload?.state === 'replaced') {\n return { kind: 'replaced', storeName: String(payload.storeName ?? ''), noun: String(payload.noun ?? nounOf(payload.kind)) }\n }\n return { kind: 'ready', view: payload as QuotePageView }\n } catch {\n return { kind: 'missing', message: 'This page could not be loaded. Check your connection and try again.' }\n }\n }, [hostId, siteFetch])\n\n useEffect(() => {\n if (!hostId) return\n const params = new URLSearchParams(window.location.search)\n link.current = {\n quoteId: params.get('q') ?? '',\n token: params.get('t') ?? '',\n sessionId: params.get('session_id') ?? '',\n }\n if (!link.current.quoteId || !link.current.token) {\n setState({ kind: 'missing', message: 'Open this page from the link you were sent with your quote or invoice.' })\n return\n }\n let live = true\n void (async () => {\n const first = await load()\n if (!live) return\n setState(first)\n const sessionId = link.current.sessionId\n if (first.kind !== 'ready' || first.view.status !== 'unpaid' || !sessionId) return\n // Back from paying: the payment may have landed before the record of it.\n const status = await siteFetch(\n `/api/commerce/checkout-status?hostId=${encodeURIComponent(hostId)}` +\n `&sessionId=${encodeURIComponent(sessionId)}`,\n )\n .then((response) => (response.ok ? response.json() : null))\n .catch(() => null)\n if (!live) return\n if (status?.status === 'open') {\n setReturned('failed')\n return\n }\n if (status?.status !== 'complete') return\n setReturned('confirming')\n for (let poll = 0; poll < CONFIRM_POLLS && live; poll++) {\n await new Promise((resolve) => setTimeout(resolve, CONFIRM_POLL_MS))\n if (!live) return\n const next = await load()\n if (!live) return\n if (next.kind === 'ready' && next.view.status !== 'unpaid') {\n setState(next)\n setReturned(null)\n return\n }\n }\n if (live) setReturned('unconfirmed')\n })()\n return () => {\n live = false\n }\n }, [hostId, load, siteFetch])\n\n const view = state.kind === 'ready' ? state.view : null\n\n const pay = useCallback(async () => {\n if (!view || paying) return\n setPaying(true)\n setPayError('')\n setReturned(null)\n // One key per press: a press is one attempt, and a retry after a failure is a new one.\n const attemptKey =\n globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`\n try {\n const response = await siteFetch('/api/commerce/quote-pay', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', 'Idempotency-Key': attemptKey },\n body: JSON.stringify({\n hostId,\n q: link.current.quoteId,\n t: link.current.token,\n v: view.version,\n // The tax the page priced it under; a quote whose tax moved since is shown again.\n ...(view.taxKey ? { tax: view.taxKey } : {}),\n }),\n })\n const payload = await response.json().catch(() => ({}))\n // A session with a client secret is the in-page form; checked before the\n // redirect, so a form is never navigated away from.\n if (response.ok && payload?.clientSecret && payload?.publishableKey) {\n setNativeCheckout({\n clientSecret: String(payload.clientSecret),\n publishableKey: String(payload.publishableKey),\n wallets: readStorefrontCheckoutWallets(payload.wallets),\n })\n setPaying(false)\n return\n }\n if (response.ok && payload?.url) {\n window.location.assign(String(payload.url))\n return\n }\n if (payload?.replaced) {\n setState({ kind: 'replaced', storeName: view.storeName, noun: nounOf(view.kind) })\n return\n }\n if (payload?.reason === 'paid' || payload?.reason === 'updated') {\n const next = await load()\n setState(next)\n }\n setPayError(String(payload?.error ?? 'Your payment could not be set up. Try again.'))\n setPaying(false)\n } catch {\n setPayError('Your payment could not be set up. Check your connection and try again.')\n setPaying(false)\n }\n }, [view, paying, siteFetch, hostId, load])\n\n if (!hostId) {\n return (\n <Box\n ref={ref}\n {...rest}\n sx={[{ p: 3, border: '1px dashed', borderColor: 'divider', borderRadius: 1 }, ...nodeSx]}\n >\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Quote — a customer’s quote and its Pay button render here'}\n </Typography>\n </Box>\n )\n }\n\n if (state.kind === 'loading') {\n return (\n <Box ref={ref} {...rest} sx={[{ py: 6, textAlign: 'center' }, ...nodeSx]}>\n <CircularProgress size={28} aria-label=\"Loading\" />\n </Box>\n )\n }\n\n if (state.kind === 'missing') {\n return (\n <Box ref={ref} {...rest} sx={nodeSx}>\n <Stack spacing={2}>\n <Typography variant=\"h4\" component=\"h1\">\n {heading || 'Your quote or invoice'}\n </Typography>\n <Alert severity=\"info\">{state.message}</Alert>\n </Stack>\n </Box>\n )\n }\n\n if (state.kind === 'replaced') {\n const business = state.storeName || 'The business'\n return (\n <Box ref={ref} {...rest} sx={nodeSx}>\n <Stack spacing={2}>\n {state.storeName ? (\n <Typography variant=\"overline\" color=\"text.secondary\">\n {state.storeName}\n </Typography>\n ) : null}\n <Typography variant=\"h4\" component=\"h1\">\n {`This ${state.noun} was updated`}\n </Typography>\n <Typography variant=\"body1\" color=\"text.secondary\">\n {`${business} updated this ${state.noun} and sent you a newer link. Open their most recent message to see it.`}\n </Typography>\n </Stack>\n </Box>\n )\n }\n\n const quote = state.view\n const money = (cents: number) => formatOrderMoney(cents, quote.currency)\n // The same signed link as the page's data; the server makes the PDF from the same view.\n const pdfHref =\n `/api/commerce/quote-pdf?hostId=${encodeURIComponent(hostId)}` +\n `&q=${encodeURIComponent(link.current.quoteId)}&t=${encodeURIComponent(link.current.token)}`\n const unpaid = quote.status === 'unpaid'\n // A proof with no price yet (AGL-4184): the proof and its answer, and nothing about money.\n const proofOnly = quote.proofOnly === true\n const noun = proofOnly ? 'proof' : nounOf(quote.kind)\n const later = addedAtPayment(quote)\n const addresses = [\n quote.customerName || quote.company\n ? { label: 'Prepared for', lines: [quote.customerName, quote.company].filter((line): line is string => Boolean(line)) }\n : null,\n quote.billTo ? { label: 'Bill to', lines: addressLines(quote.billTo) } : null,\n quote.shipTo ? { label: 'Ship to', lines: addressLines(quote.shipTo) } : null,\n ].filter((block): block is { label: string; lines: string[] } => Boolean(block && block.lines.length))\n const totalRows = (\n [\n ['Subtotal', money(quote.totals.itemsCents), true],\n [\n quote.discountLabel ? `Discount (${quote.discountLabel})` : 'Discount',\n `−${money(quote.totals.discountCents)}`,\n quote.totals.discountCents > 0,\n ],\n ['Shipping', money(quote.totals.shippingCents), quote.totals.shippingCents > 0],\n [quote.taxLabel, money(quote.totals.taxCents), quote.totals.taxCents > 0],\n // The rate an invoiced draft's customer picks when they pay (AGL-4099).\n ['Shipping is chosen when you pay', '', quote.shippingAtPayment === true],\n // `Tax is added at payment`, with no figure: Stripe works it out from the address.\n [quote.taxLabel, '', quote.taxAtPayment],\n ] as Array<[string, string, boolean]>\n ).filter(([, , shown]) => shown)\n\n return (\n <Box ref={ref} {...rest} sx={nodeSx}>\n <Stack spacing={3}>\n <Stack spacing={1}>\n {quote.storeName ? (\n <Typography variant=\"overline\" color=\"text.secondary\">\n {quote.storeName}\n </Typography>\n ) : null}\n <Stack direction=\"row\" spacing={1.5} sx={{ alignItems: 'center', flexWrap: 'wrap', rowGap: 1 }}>\n <Typography variant=\"h4\" component=\"h1\">\n {/* The element's own heading is a quote's; an invoice or a proof always says its number. */}\n {(quote.kind !== 'invoice' && !proofOnly && heading) || quote.number}\n </Typography>\n {proofOnly ? null : (\n <Chip\n label={quote.statusLabel}\n color={quote.status === 'paid' ? 'success' : unpaid ? 'primary' : 'default'}\n size=\"small\"\n />\n )}\n </Stack>\n {quote.dateMs ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {`Dated ${dateLabel(quote.dateMs)}`}\n </Typography>\n ) : null}\n {proofOnly ? null : (\n <Box>\n <Button variant=\"outlined\" size=\"small\" href={pdfHref} download>\n {'Download PDF'}\n </Button>\n </Box>\n )}\n </Stack>\n\n {addresses.length ? (\n <Stack direction={{ xs: 'column', sm: 'row' }} spacing={{ xs: 2, sm: 3 }}>\n {addresses.map((block) => (\n <AddressBlock key={block.label} label={block.label} lines={block.lines} />\n ))}\n </Stack>\n ) : null}\n\n {proofOnly ? null : (\n <Stack spacing={1.5}>\n <Typography variant=\"h6\" component=\"h2\">\n {'Items'}\n </Typography>\n {quote.lines.map((line, index) => (\n <Stack key={index} direction=\"row\" spacing={2} sx={{ justifyContent: 'space-between' }}>\n <Stack spacing={0.25} sx={{ minWidth: 0 }}>\n <Typography variant=\"body2\">\n {line.name}\n {line.variantLabel ? ` (${line.variantLabel})` : ''}\n </Typography>\n {line.description ? (\n <Typography variant=\"body2\" color=\"text.secondary\" sx={{ whiteSpace: 'pre-line' }}>\n {line.description}\n </Typography>\n ) : null}\n <Typography variant=\"caption\" color=\"text.secondary\">\n {[\n line.included ? `${line.quantity} included` : `${line.quantity} × ${money(line.unitAmountCents)}`,\n line.sku ? `SKU ${line.sku}` : '',\n ]\n .filter(Boolean)\n .join(' · ')}\n </Typography>\n </Stack>\n <Typography variant=\"body2\" sx={{ flexShrink: 0 }}>\n {line.included ? 'Included' : money(line.amountCents)}\n </Typography>\n </Stack>\n ))}\n <Divider />\n {totalRows.map(([label, value]) => (\n <TotalRow key={`${label}-${value}`} label={label} value={value} />\n ))}\n <TotalRow label=\"Total\" value={money(quote.totals.totalCents)} strong />\n </Stack>\n )}\n\n {quote.notes ? (\n <Stack spacing={0.5}>\n <Typography variant=\"h6\" component=\"h2\">\n {'Notes'}\n </Typography>\n <Typography variant=\"body2\" sx={{ whiteSpace: 'pre-line' }}>\n {quote.notes}\n </Typography>\n </Stack>\n ) : null}\n {quote.terms ? (\n <Stack spacing={0.5}>\n <Typography variant=\"h6\" component=\"h2\">\n {'Terms'}\n </Typography>\n <Typography variant=\"body2\" color=\"text.secondary\" sx={{ whiteSpace: 'pre-line' }}>\n {quote.terms}\n </Typography>\n </Stack>\n ) : null}\n\n {proofOnly && !quote.proofs.length ? (\n <Alert severity=\"info\">\n {`${quote.storeName || 'The business'} is working on the next version of your proof, and will send it when it’s ready.`}\n </Alert>\n ) : null}\n\n <QuoteProofPanel\n view={quote}\n hostId={hostId}\n quoteId={link.current.quoteId}\n token={link.current.token}\n siteFetch={siteFetch}\n onView={(next) => setState({ kind: 'ready', view: next })}\n onReload={() => void load().then(setState)}\n onReplaced={() => setState({ kind: 'replaced', storeName: quote.storeName, noun })}\n />\n\n {proofOnly ? null : unpaid ? (\n <Paper variant=\"outlined\" sx={{ p: { xs: 2, sm: 3 } }}>\n <Stack spacing={2}>\n {returned === 'confirming' ? (\n <Alert severity=\"info\" icon={<CircularProgress size={20} />}>\n {'Thank you. We’re confirming your payment.'}\n </Alert>\n ) : returned === 'unconfirmed' ? (\n <Alert severity=\"info\">\n {'Your payment is still being confirmed. Your receipt will arrive by email.'}\n </Alert>\n ) : quote.approvalRequired ? (\n <Alert severity=\"info\">\n {`${quote.storeName || 'The business'} asks you to approve the proof before you pay.`}\n </Alert>\n ) : quote.payable ? (\n <>\n {returned === 'failed' ? (\n <Alert severity=\"warning\">{'Your payment did not go through. Nothing was charged.'}</Alert>\n ) : null}\n {nativeCheckout ? (\n <Suspense fallback={<StorefrontPaymentElementFallback />}>\n <StorefrontPaymentElement\n clientSecret={nativeCheckout.clientSecret}\n publishableKey={nativeCheckout.publishableKey}\n wallets={nativeCheckout.wallets}\n payLabel={later ? 'Pay now' : `Pay ${money(quote.totals.totalCents)}`}\n defaultShippingAddress={stripeContact(quote.shipTo)}\n // An expired or unloadable session is replaced by a new press.\n onRestart={() => {\n setNativeCheckout(null)\n void pay()\n }}\n onCancel={() => setNativeCheckout(null)}\n />\n </Suspense>\n ) : (\n <Button\n variant=\"contained\"\n size=\"large\"\n onClick={() => void pay()}\n disabled={paying}\n sx={{ alignSelf: { xs: 'stretch', sm: 'flex-start' } }}\n >\n {paying\n ? 'Opening…'\n : later\n ? `Pay ${money(quote.totals.totalCents)} plus ${later}`\n : `Pay ${money(quote.totals.totalCents)}`}\n </Button>\n )}\n {payError ? <Alert severity=\"error\">{payError}</Alert> : null}\n </>\n ) : (\n <Alert severity=\"info\">\n {quote.notPayableMessage || `Contact ${quote.storeName || 'the business'} to pay this ${noun}.`}\n </Alert>\n )}\n </Stack>\n </Paper>\n ) : (\n <Paper variant=\"outlined\" sx={{ p: { xs: 2, sm: 3 } }}>\n <Stack spacing={1.5} sx={{ alignItems: 'flex-start' }}>\n <Typography variant=\"body1\">\n {quote.status === 'paid'\n ? quote.paidAtMs\n ? `Paid ${dateLabel(quote.paidAtMs)}. Thank you.`\n : 'Paid. Thank you.'\n : `This ${noun} is ${quote.statusLabel.toLowerCase()}.`}\n </Typography>\n {quote.receiptUrl ? (\n <Button variant=\"outlined\" href={quote.receiptUrl}>\n {'View your order'}\n </Button>\n ) : null}\n </Stack>\n </Paper>\n )}\n\n <Typography variant=\"body2\" color=\"text.secondary\">\n {`Questions about this ${noun}? Contact ${quote.storeName || 'the business'}.`}\n </Typography>\n </Stack>\n </Box>\n )\n})\nQuotePageBody.displayName = 'QuotePageBody'\n\nexport default QuotePageBody\n\n"],"names":["Aglyn","Alert","Box","Button","Chip","CircularProgress","Divider","Paper","Stack","Typography","forwardRef","lazy","Suspense","useCallback","useEffect","useRef","useState","formatOrderMoney","readStorefrontCheckoutWallets","QuoteProofPanel","StorefrontPaymentElementFallback","StorefrontPaymentElement","then","module","default","nounOf","kind","addedAtPayment","view","shippingAtPayment","taxAtPayment","CONFIRM_POLL_MS","CONFIRM_POLLS","dateLabel","atMs","Date","toLocaleDateString","undefined","month","day","year","addressLines","address","cityLine","city","state","postalCode","filter","Boolean","join","name","line1","line2","country","line","stripeContact","postal_code","AddressBlock","label","lines","spacing","sx","minWidth","flex","variant","color","map","index","TotalRow","value","strong","direction","justifyContent","QuotePageBody","props","ref","heading","rest","nodeSx","Array","isArray","hostId","useSite","siteFetch","useSiteFetch","setState","paying","setPaying","payError","setPayError","nativeCheckout","setNativeCheckout","returned","setReturned","link","quoteId","token","sessionId","load","current","response","encodeURIComponent","payload","json","catch","ok","message","String","error","storeName","noun","params","URLSearchParams","window","location","search","get","live","first","status","poll","Promise","resolve","setTimeout","next","pay","globalThis","attemptKey","crypto","randomUUID","now","Math","random","toString","slice","method","headers","body","JSON","stringify","q","t","v","version","taxKey","tax","clientSecret","publishableKey","wallets","url","assign","replaced","reason","p","border","borderColor","borderRadius","py","textAlign","size","aria-label","component","severity","business","quote","money","cents","currency","pdfHref","unpaid","proofOnly","later","addresses","customerName","company","billTo","shipTo","block","length","totalRows","totals","itemsCents","discountLabel","discountCents","shippingCents","taxLabel","taxCents","shown","alignItems","flexWrap","rowGap","number","statusLabel","dateMs","href","download","xs","sm","variantLabel","description","whiteSpace","included","quantity","unitAmountCents","sku","flexShrink","amountCents","totalCents","notes","terms","proofs","onView","onReload","onReplaced","icon","approvalRequired","payable","fallback","payLabel","defaultShippingAddress","onRestart","onCancel","onClick","disabled","alignSelf","notPayableMessage","paidAtMs","toLowerCase","receiptUrl","displayName"],"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Ac4J,WAAW,GAAG;AAE5B,eAAe5J,cAAa"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/components/quote-page-body.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as Aglyn from '@aglyn/aglyn'\nimport Alert from '@mui/material/Alert'\nimport Box from '@mui/material/Box'\nimport Button from '@mui/material/Button'\nimport Chip from '@mui/material/Chip'\nimport CircularProgress from '@mui/material/CircularProgress'\nimport Divider from '@mui/material/Divider'\nimport Paper from '@mui/material/Paper'\nimport Stack from '@mui/material/Stack'\nimport Typography from '@mui/material/Typography'\nimport type { StripeCheckoutContact } from '@stripe/stripe-js'\nimport { forwardRef, lazy, Suspense, useCallback, useEffect, useRef, useState } from 'react'\nimport {\n formatOrderMoney,\n readStorefrontCheckoutWallets,\n type QuotePageAddress,\n type QuotePageView,\n type StorefrontCheckoutWallets,\n} from '../model'\nimport type { QuotePageProps } from './quote-page'\nimport { QuoteProofPanel } from './quote-proof-panel'\nimport { StorefrontPaymentElementFallback } from './storefront-payment-element-fallback'\n\n/** The Payment Element, lazily: Stripe.js loads only when a customer presses Pay. */\nconst StorefrontPaymentElement = lazy(() =>\n import('./storefront-payment-element').then((module) => ({\n default: module.StorefrontPaymentElement,\n })),\n)\n\ntype LoadState =\n | { kind: 'loading' }\n | { kind: 'missing'; message: string }\n | { kind: 'replaced'; storeName: string; noun: string }\n | { kind: 'ready'; view: QuotePageView }\n\n/** `quote` or `invoice`, as the page says it (AGL-4099). */\nconst nounOf = (kind: unknown) => (kind === 'invoice' ? 'invoice' : 'quote')\n\n/** What is added when the customer pays: `shipping`, `tax`, `shipping and tax`, or nothing. */\nfunction addedAtPayment(view: Pick<QuotePageView, 'shippingAtPayment' | 'taxAtPayment'>): string {\n if (view.shippingAtPayment && view.taxAtPayment) return 'shipping and tax'\n if (view.shippingAtPayment) return 'shipping'\n return view.taxAtPayment ? 'tax' : ''\n}\n\n/** After a payment returns here, how often and how long the page asks whether it landed. */\nconst CONFIRM_POLL_MS = 2_000\nconst CONFIRM_POLLS = 15\n\nfunction dateLabel(atMs: number | null): string {\n if (!atMs) return ''\n return new Date(atMs).toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' })\n}\n\nfunction addressLines(address: QuotePageAddress): string[] {\n const cityLine = [address.city, [address.state, address.postalCode].filter(Boolean).join(' ')]\n .filter(Boolean)\n .join(', ')\n return [address.name, address.line1, address.line2, cityLine, address.country].filter(\n (line): line is string => Boolean(line),\n )\n}\n\nfunction stripeContact(address: QuotePageAddress | null): StripeCheckoutContact | undefined {\n if (!address?.country) return undefined\n return {\n name: address.name,\n address: {\n country: address.country,\n line1: address.line1,\n line2: address.line2,\n city: address.city,\n state: address.state,\n postal_code: address.postalCode,\n },\n }\n}\n\nfunction AddressBlock({ label, lines }: { label: string; lines: string[] }) {\n return (\n <Stack spacing={0.25} sx={{ minWidth: 0, flex: 1 }}>\n <Typography variant=\"overline\" color=\"text.secondary\">\n {label}\n </Typography>\n {lines.map((line, index) => (\n <Typography key={index} variant=\"body2\">\n {line}\n </Typography>\n ))}\n </Stack>\n )\n}\n\nfunction TotalRow({ label, value, strong }: { label: string; value: string; strong?: boolean }) {\n return (\n <Stack direction=\"row\" spacing={2} sx={{ justifyContent: 'space-between' }}>\n <Typography variant={strong ? 'subtitle1' : 'body2'} color={strong ? 'text.primary' : 'text.secondary'}>\n {label}\n </Typography>\n <Typography variant={strong ? 'subtitle1' : 'body2'} color={strong ? 'text.primary' : 'text.secondary'}>\n {value}\n </Typography>\n </Stack>\n )\n}\n\n/**\n * The customer's quote page (AGL-4094), loaded when the page draws it (see\n * `quote-page.tsx`): what a customer sees when they open\n * the pay link a business sent them. The commerce page resolver serves it at\n * `/pay-quote` inside the site's own header and footer; a business can also\n * place it on a page of their own design at that address.\n *\n * The quote is read AFTER hydration from `?q=&t=`, so the page itself is the\n * same for every customer and may be cached, and the quote never is. Pay asks\n * the server for a fresh payment for the quote as the page shows it: Stripe's\n * own page, or the payment form here when in-page payments are on. Nothing\n * here decides a quote is paid; after paying, the page reads that from the\n * server like any other visit.\n */\nconst QuotePageBody = forwardRef<HTMLDivElement, QuotePageProps>((props, ref) => {\n const { heading, ...rest } = props\n const nodeSx = Array.isArray(props['sx']) ? props['sx'] : [props['sx']]\n const { hostId } = Aglyn.useSite()\n const siteFetch = Aglyn.useSiteFetch()\n const [state, setState] = useState<LoadState>({ kind: 'loading' })\n const [paying, setPaying] = useState(false)\n const [payError, setPayError] = useState('')\n const [nativeCheckout, setNativeCheckout] = useState<{\n clientSecret: string\n publishableKey: string\n /** The seller's account for a direct-charge session. */\n stripeAccount?: string\n wallets?: StorefrontCheckoutWallets\n } | null>(null)\n /** What a return from paying turned out to be: still being confirmed, or not paid. */\n const [returned, setReturned] = useState<'confirming' | 'unconfirmed' | 'failed' | null>(null)\n const link = useRef({ quoteId: '', token: '', sessionId: '' })\n\n const load = useCallback(async (): Promise<LoadState> => {\n const { quoteId, token } = link.current\n try {\n const response = await siteFetch(\n `/api/commerce/quote-view?hostId=${encodeURIComponent(hostId ?? '')}` +\n `&q=${encodeURIComponent(quoteId)}&t=${encodeURIComponent(token)}`,\n )\n const payload = await response.json().catch(() => ({}))\n if (!response.ok) {\n return { kind: 'missing', message: String(payload?.error ?? 'We could not find that quote or invoice.') }\n }\n if (payload?.state === 'replaced') {\n return { kind: 'replaced', storeName: String(payload.storeName ?? ''), noun: String(payload.noun ?? nounOf(payload.kind)) }\n }\n return { kind: 'ready', view: payload as QuotePageView }\n } catch {\n return { kind: 'missing', message: 'This page could not be loaded. Check your connection and try again.' }\n }\n }, [hostId, siteFetch])\n\n useEffect(() => {\n if (!hostId) return\n const params = new URLSearchParams(window.location.search)\n link.current = {\n quoteId: params.get('q') ?? '',\n token: params.get('t') ?? '',\n sessionId: params.get('session_id') ?? '',\n }\n if (!link.current.quoteId || !link.current.token) {\n setState({ kind: 'missing', message: 'Open this page from the link you were sent with your quote or invoice.' })\n return\n }\n let live = true\n void (async () => {\n const first = await load()\n if (!live) return\n setState(first)\n const sessionId = link.current.sessionId\n if (first.kind !== 'ready' || first.view.status !== 'unpaid' || !sessionId) return\n // Back from paying: the payment may have landed before the record of it.\n const status = await siteFetch(\n `/api/commerce/checkout-status?hostId=${encodeURIComponent(hostId)}` +\n `&sessionId=${encodeURIComponent(sessionId)}`,\n )\n .then((response) => (response.ok ? response.json() : null))\n .catch(() => null)\n if (!live) return\n if (status?.status === 'open') {\n setReturned('failed')\n return\n }\n if (status?.status !== 'complete') return\n setReturned('confirming')\n for (let poll = 0; poll < CONFIRM_POLLS && live; poll++) {\n await new Promise((resolve) => setTimeout(resolve, CONFIRM_POLL_MS))\n if (!live) return\n const next = await load()\n if (!live) return\n if (next.kind === 'ready' && next.view.status !== 'unpaid') {\n setState(next)\n setReturned(null)\n return\n }\n }\n if (live) setReturned('unconfirmed')\n })()\n return () => {\n live = false\n }\n }, [hostId, load, siteFetch])\n\n const view = state.kind === 'ready' ? state.view : null\n\n const pay = useCallback(async () => {\n if (!view || paying) return\n setPaying(true)\n setPayError('')\n setReturned(null)\n // One key per press: a press is one attempt, and a retry after a failure is a new one.\n const attemptKey =\n globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`\n try {\n const response = await siteFetch('/api/commerce/quote-pay', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', 'Idempotency-Key': attemptKey },\n body: JSON.stringify({\n hostId,\n q: link.current.quoteId,\n t: link.current.token,\n v: view.version,\n // The tax the page priced it under; a quote whose tax moved since is shown again.\n ...(view.taxKey ? { tax: view.taxKey } : {}),\n }),\n })\n const payload = await response.json().catch(() => ({}))\n // A session with a client secret is the in-page form; checked before the\n // redirect, so a form is never navigated away from.\n if (response.ok && payload?.clientSecret && payload?.publishableKey) {\n setNativeCheckout({\n clientSecret: String(payload.clientSecret),\n publishableKey: String(payload.publishableKey),\n ...(payload.stripeAccount\n ? { stripeAccount: String(payload.stripeAccount) }\n : {}),\n wallets: readStorefrontCheckoutWallets(payload.wallets),\n })\n setPaying(false)\n return\n }\n if (response.ok && payload?.url) {\n window.location.assign(String(payload.url))\n return\n }\n if (payload?.replaced) {\n setState({ kind: 'replaced', storeName: view.storeName, noun: nounOf(view.kind) })\n return\n }\n if (payload?.reason === 'paid' || payload?.reason === 'updated') {\n const next = await load()\n setState(next)\n }\n setPayError(String(payload?.error ?? 'Your payment could not be set up. Try again.'))\n setPaying(false)\n } catch {\n setPayError('Your payment could not be set up. Check your connection and try again.')\n setPaying(false)\n }\n }, [view, paying, siteFetch, hostId, load])\n\n if (!hostId) {\n return (\n <Box\n ref={ref}\n {...rest}\n sx={[{ p: 3, border: '1px dashed', borderColor: 'divider', borderRadius: 1 }, ...nodeSx]}\n >\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Quote — a customer’s quote and its Pay button render here'}\n </Typography>\n </Box>\n )\n }\n\n if (state.kind === 'loading') {\n return (\n <Box ref={ref} {...rest} sx={[{ py: 6, textAlign: 'center' }, ...nodeSx]}>\n <CircularProgress size={28} aria-label=\"Loading\" />\n </Box>\n )\n }\n\n if (state.kind === 'missing') {\n return (\n <Box ref={ref} {...rest} sx={nodeSx}>\n <Stack spacing={2}>\n <Typography variant=\"h4\" component=\"h1\">\n {heading || 'Your quote or invoice'}\n </Typography>\n <Alert severity=\"info\">{state.message}</Alert>\n </Stack>\n </Box>\n )\n }\n\n if (state.kind === 'replaced') {\n const business = state.storeName || 'The business'\n return (\n <Box ref={ref} {...rest} sx={nodeSx}>\n <Stack spacing={2}>\n {state.storeName ? (\n <Typography variant=\"overline\" color=\"text.secondary\">\n {state.storeName}\n </Typography>\n ) : null}\n <Typography variant=\"h4\" component=\"h1\">\n {`This ${state.noun} was updated`}\n </Typography>\n <Typography variant=\"body1\" color=\"text.secondary\">\n {`${business} updated this ${state.noun} and sent you a newer link. Open their most recent message to see it.`}\n </Typography>\n </Stack>\n </Box>\n )\n }\n\n const quote = state.view\n const money = (cents: number) => formatOrderMoney(cents, quote.currency)\n // The same signed link as the page's data; the server makes the PDF from the same view.\n const pdfHref =\n `/api/commerce/quote-pdf?hostId=${encodeURIComponent(hostId)}` +\n `&q=${encodeURIComponent(link.current.quoteId)}&t=${encodeURIComponent(link.current.token)}`\n const unpaid = quote.status === 'unpaid'\n // A proof with no price yet (AGL-4184): the proof and its answer, and nothing about money.\n const proofOnly = quote.proofOnly === true\n const noun = proofOnly ? 'proof' : nounOf(quote.kind)\n const later = addedAtPayment(quote)\n const addresses = [\n quote.customerName || quote.company\n ? { label: 'Prepared for', lines: [quote.customerName, quote.company].filter((line): line is string => Boolean(line)) }\n : null,\n quote.billTo ? { label: 'Bill to', lines: addressLines(quote.billTo) } : null,\n quote.shipTo ? { label: 'Ship to', lines: addressLines(quote.shipTo) } : null,\n ].filter((block): block is { label: string; lines: string[] } => Boolean(block && block.lines.length))\n const totalRows = (\n [\n ['Subtotal', money(quote.totals.itemsCents), true],\n [\n quote.discountLabel ? `Discount (${quote.discountLabel})` : 'Discount',\n `−${money(quote.totals.discountCents)}`,\n quote.totals.discountCents > 0,\n ],\n ['Shipping', money(quote.totals.shippingCents), quote.totals.shippingCents > 0],\n [quote.taxLabel, money(quote.totals.taxCents), quote.totals.taxCents > 0],\n // The rate an invoiced draft's customer picks when they pay (AGL-4099).\n ['Shipping is chosen when you pay', '', quote.shippingAtPayment === true],\n // `Tax is added at payment`, with no figure: Stripe works it out from the address.\n [quote.taxLabel, '', quote.taxAtPayment],\n ] as Array<[string, string, boolean]>\n ).filter(([, , shown]) => shown)\n\n return (\n <Box ref={ref} {...rest} sx={nodeSx}>\n <Stack spacing={3}>\n <Stack spacing={1}>\n {quote.storeName ? (\n <Typography variant=\"overline\" color=\"text.secondary\">\n {quote.storeName}\n </Typography>\n ) : null}\n <Stack direction=\"row\" spacing={1.5} sx={{ alignItems: 'center', flexWrap: 'wrap', rowGap: 1 }}>\n <Typography variant=\"h4\" component=\"h1\">\n {/* The element's own heading is a quote's; an invoice or a proof always says its number. */}\n {(quote.kind !== 'invoice' && !proofOnly && heading) || quote.number}\n </Typography>\n {proofOnly ? null : (\n <Chip\n label={quote.statusLabel}\n color={quote.status === 'paid' ? 'success' : unpaid ? 'primary' : 'default'}\n size=\"small\"\n />\n )}\n </Stack>\n {quote.dateMs ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {`Dated ${dateLabel(quote.dateMs)}`}\n </Typography>\n ) : null}\n {proofOnly ? null : (\n <Box>\n <Button variant=\"outlined\" size=\"small\" href={pdfHref} download>\n {'Download PDF'}\n </Button>\n </Box>\n )}\n </Stack>\n\n {addresses.length ? (\n <Stack direction={{ xs: 'column', sm: 'row' }} spacing={{ xs: 2, sm: 3 }}>\n {addresses.map((block) => (\n <AddressBlock key={block.label} label={block.label} lines={block.lines} />\n ))}\n </Stack>\n ) : null}\n\n {proofOnly ? null : (\n <Stack spacing={1.5}>\n <Typography variant=\"h6\" component=\"h2\">\n {'Items'}\n </Typography>\n {quote.lines.map((line, index) => (\n <Stack key={index} direction=\"row\" spacing={2} sx={{ justifyContent: 'space-between' }}>\n <Stack spacing={0.25} sx={{ minWidth: 0 }}>\n <Typography variant=\"body2\">\n {line.name}\n {line.variantLabel ? ` (${line.variantLabel})` : ''}\n </Typography>\n {line.description ? (\n <Typography variant=\"body2\" color=\"text.secondary\" sx={{ whiteSpace: 'pre-line' }}>\n {line.description}\n </Typography>\n ) : null}\n <Typography variant=\"caption\" color=\"text.secondary\">\n {[\n line.included ? `${line.quantity} included` : `${line.quantity} × ${money(line.unitAmountCents)}`,\n line.sku ? `SKU ${line.sku}` : '',\n ]\n .filter(Boolean)\n .join(' · ')}\n </Typography>\n </Stack>\n <Typography variant=\"body2\" sx={{ flexShrink: 0 }}>\n {line.included ? 'Included' : money(line.amountCents)}\n </Typography>\n </Stack>\n ))}\n <Divider />\n {totalRows.map(([label, value]) => (\n <TotalRow key={`${label}-${value}`} label={label} value={value} />\n ))}\n <TotalRow label=\"Total\" value={money(quote.totals.totalCents)} strong />\n </Stack>\n )}\n\n {quote.notes ? (\n <Stack spacing={0.5}>\n <Typography variant=\"h6\" component=\"h2\">\n {'Notes'}\n </Typography>\n <Typography variant=\"body2\" sx={{ whiteSpace: 'pre-line' }}>\n {quote.notes}\n </Typography>\n </Stack>\n ) : null}\n {quote.terms ? (\n <Stack spacing={0.5}>\n <Typography variant=\"h6\" component=\"h2\">\n {'Terms'}\n </Typography>\n <Typography variant=\"body2\" color=\"text.secondary\" sx={{ whiteSpace: 'pre-line' }}>\n {quote.terms}\n </Typography>\n </Stack>\n ) : null}\n\n {proofOnly && !quote.proofs.length ? (\n <Alert severity=\"info\">\n {`${quote.storeName || 'The business'} is working on the next version of your proof, and will send it when it’s ready.`}\n </Alert>\n ) : null}\n\n <QuoteProofPanel\n view={quote}\n hostId={hostId}\n quoteId={link.current.quoteId}\n token={link.current.token}\n siteFetch={siteFetch}\n onView={(next) => setState({ kind: 'ready', view: next })}\n onReload={() => void load().then(setState)}\n onReplaced={() => setState({ kind: 'replaced', storeName: quote.storeName, noun })}\n />\n\n {proofOnly ? null : unpaid ? (\n <Paper variant=\"outlined\" sx={{ p: { xs: 2, sm: 3 } }}>\n <Stack spacing={2}>\n {returned === 'confirming' ? (\n <Alert severity=\"info\" icon={<CircularProgress size={20} />}>\n {'Thank you. We’re confirming your payment.'}\n </Alert>\n ) : returned === 'unconfirmed' ? (\n <Alert severity=\"info\">\n {'Your payment is still being confirmed. Your receipt will arrive by email.'}\n </Alert>\n ) : quote.approvalRequired ? (\n <Alert severity=\"info\">\n {`${quote.storeName || 'The business'} asks you to approve the proof before you pay.`}\n </Alert>\n ) : quote.payable ? (\n <>\n {returned === 'failed' ? (\n <Alert severity=\"warning\">{'Your payment did not go through. Nothing was charged.'}</Alert>\n ) : null}\n {nativeCheckout ? (\n <Suspense fallback={<StorefrontPaymentElementFallback />}>\n <StorefrontPaymentElement\n clientSecret={nativeCheckout.clientSecret}\n publishableKey={nativeCheckout.publishableKey}\n stripeAccount={nativeCheckout.stripeAccount}\n wallets={nativeCheckout.wallets}\n payLabel={later ? 'Pay now' : `Pay ${money(quote.totals.totalCents)}`}\n defaultShippingAddress={stripeContact(quote.shipTo)}\n // An expired or unloadable session is replaced by a new press.\n onRestart={() => {\n setNativeCheckout(null)\n void pay()\n }}\n onCancel={() => setNativeCheckout(null)}\n />\n </Suspense>\n ) : (\n <Button\n variant=\"contained\"\n size=\"large\"\n onClick={() => void pay()}\n disabled={paying}\n sx={{ alignSelf: { xs: 'stretch', sm: 'flex-start' } }}\n >\n {paying\n ? 'Opening…'\n : later\n ? `Pay ${money(quote.totals.totalCents)} plus ${later}`\n : `Pay ${money(quote.totals.totalCents)}`}\n </Button>\n )}\n {payError ? <Alert severity=\"error\">{payError}</Alert> : null}\n </>\n ) : (\n <Alert severity=\"info\">\n {quote.notPayableMessage || `Contact ${quote.storeName || 'the business'} to pay this ${noun}.`}\n </Alert>\n )}\n </Stack>\n </Paper>\n ) : (\n <Paper variant=\"outlined\" sx={{ p: { xs: 2, sm: 3 } }}>\n <Stack spacing={1.5} sx={{ alignItems: 'flex-start' }}>\n <Typography variant=\"body1\">\n {quote.status === 'paid'\n ? quote.paidAtMs\n ? `Paid ${dateLabel(quote.paidAtMs)}. Thank you.`\n : 'Paid. Thank you.'\n : `This ${noun} is ${quote.statusLabel.toLowerCase()}.`}\n </Typography>\n {quote.receiptUrl ? (\n <Button variant=\"outlined\" href={quote.receiptUrl}>\n {'View your order'}\n </Button>\n ) : null}\n </Stack>\n </Paper>\n )}\n\n <Typography variant=\"body2\" color=\"text.secondary\">\n {`Questions about this ${noun}? Contact ${quote.storeName || 'the business'}.`}\n </Typography>\n </Stack>\n </Box>\n )\n})\nQuotePageBody.displayName = 'QuotePageBody'\n\nexport default QuotePageBody\n\n"],"names":["Aglyn","Alert","Box","Button","Chip","CircularProgress","Divider","Paper","Stack","Typography","forwardRef","lazy","Suspense","useCallback","useEffect","useRef","useState","formatOrderMoney","readStorefrontCheckoutWallets","QuoteProofPanel","StorefrontPaymentElementFallback","StorefrontPaymentElement","then","module","default","nounOf","kind","addedAtPayment","view","shippingAtPayment","taxAtPayment","CONFIRM_POLL_MS","CONFIRM_POLLS","dateLabel","atMs","Date","toLocaleDateString","undefined","month","day","year","addressLines","address","cityLine","city","state","postalCode","filter","Boolean","join","name","line1","line2","country","line","stripeContact","postal_code","AddressBlock","label","lines","spacing","sx","minWidth","flex","variant","color","map","index","TotalRow","value","strong","direction","justifyContent","QuotePageBody","props","ref","heading","rest","nodeSx","Array","isArray","hostId","useSite","siteFetch","useSiteFetch","setState","paying","setPaying","payError","setPayError","nativeCheckout","setNativeCheckout","returned","setReturned","link","quoteId","token","sessionId","load","current","response","encodeURIComponent","payload","json","catch","ok","message","String","error","storeName","noun","params","URLSearchParams","window","location","search","get","live","first","status","poll","Promise","resolve","setTimeout","next","pay","globalThis","attemptKey","crypto","randomUUID","now","Math","random","toString","slice","method","headers","body","JSON","stringify","q","t","v","version","taxKey","tax","clientSecret","publishableKey","stripeAccount","wallets","url","assign","replaced","reason","p","border","borderColor","borderRadius","py","textAlign","size","aria-label","component","severity","business","quote","money","cents","currency","pdfHref","unpaid","proofOnly","later","addresses","customerName","company","billTo","shipTo","block","length","totalRows","totals","itemsCents","discountLabel","discountCents","shippingCents","taxLabel","taxCents","shown","alignItems","flexWrap","rowGap","number","statusLabel","dateMs","href","download","xs","sm","variantLabel","description","whiteSpace","included","quantity","unitAmountCents","sku","flexShrink","amountCents","totalCents","notes","terms","proofs","onView","onReload","onReplaced","icon","approvalRequired","payable","fallback","payLabel","defaultShippingAddress","onRestart","onCancel","on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C;iCAED;;;;8BAKV,KAAC5N;oBAAWuD,SAAQ;oBAAQC,OAAM;8BAC/B,CAAC,qBAAqB,EAAE6C,KAAK,UAAU,EAAEuD,MAAMxD,SAAS,IAAI,eAAe,CAAC,CAAC;;;;;AAKxF;AACApC,cAAc6J,WAAW,GAAG;AAE5B,eAAe7J,cAAa"}
@@ -53,6 +53,8 @@ export const ID = 'related-products';
53
53
  // anchor, so the rail skips a product lookup the page already made.
54
54
  const seededProductId = (_site_pageData = site.pageData) == null ? void 0 : (_site_pageData_commerce = _site_pageData.commerce) == null ? void 0 : (_site_pageData_commerce_product = _site_pageData_commerce.product) == null ? void 0 : _site_pageData_commerce_product.id;
55
55
  const [items, setItems] = useState(null);
56
+ // The catalog counts the cap over products on sale (AGL-4038).
57
+ const cap = Number(maxItems) > 0 ? Math.floor(Number(maxItems)) : 6;
56
58
  useEffect(()=>{
57
59
  if (!hostId) return;
58
60
  let active = true;
@@ -73,7 +75,7 @@ export const ID = 'related-products';
73
75
  const related = await (relatedResponse == null ? void 0 : relatedResponse.json().catch(()=>({})));
74
76
  const ids = (_ref = related == null ? void 0 : related.productIds) != null ? _ref : [];
75
77
  if (!active || ids.length === 0) return setItems([]);
76
- const catalogResponse = await fetch(`/api/commerce/catalog?hostId=${encodeURIComponent(hostId)}` + `&ids=${encodeURIComponent(ids.join(','))}`).catch(()=>null);
78
+ const catalogResponse = await fetch(`/api/commerce/catalog?hostId=${encodeURIComponent(hostId)}` + `&ids=${encodeURIComponent(ids.join(','))}&limit=${cap}`).catch(()=>null);
77
79
  const catalog = await (catalogResponse == null ? void 0 : catalogResponse.json().catch(()=>({})));
78
80
  if (active) setItems((_ref1 = catalog == null ? void 0 : catalog.items) != null ? _ref1 : []);
79
81
  })();
@@ -83,7 +85,8 @@ export const ID = 'related-products';
83
85
  }, [
84
86
  hostId,
85
87
  productIdProp,
86
- seededProductId
88
+ seededProductId,
89
+ cap
87
90
  ]);
88
91
  if (!hostId) {
89
92
  return /*#__PURE__*/ _jsx(Box, _extends({
@@ -135,7 +138,7 @@ export const ID = 'related-products';
135
138
  overflowX: 'auto',
136
139
  pb: 1
137
140
  },
138
- children: items.slice(0, maxItems && maxItems > 0 ? maxItems : 6).map((item)=>{
141
+ children: items.slice(0, cap).map((item)=>{
139
142
  // AGL-1726: resolved BEFORE the guard — see the note in
140
143
  // `product-detail.tsx`.
141
144
  const imageUrl = Aglyn.siteRelativeMediaSrc(item.imageUrl, {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/components/related-products.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as Aglyn from '@aglyn/aglyn'\nimport { mdiShapePlus } from '@aglyn/shared-data-mdi'\nimport Box from '@mui/material/Box'\nimport Card from '@mui/material/Card'\nimport CardActionArea from '@mui/material/CardActionArea'\nimport CardContent from '@mui/material/CardContent'\nimport CardMedia from '@mui/material/CardMedia'\nimport Typography from '@mui/material/Typography'\nimport { forwardRef, useEffect, useState } from 'react'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport { generatePresetId } from '../utils/generate-preset-id'\nimport { formatOrderMoney } from '../model/buyer-notifications'\nimport { ProductImagePlaceholder } from './product-image-placeholder'\n\n// Component ids are persisted in screen documents; never rename.\nexport const ID: Aglyn.ComponentId = 'related-products'\n\nexport interface RelatedProductsProps {\n /** Anchor product id; blank follows the /products/{slug} page. */\n productId?: string\n heading?: string\n maxItems?: number\n /**\n * How the items are drawn: `strip`, the default, a scrolling row of small\n * cards; `grid`, tall photo cards (4:5) with the name and price under\n * them in a grid of up to four across — the product grid's photo look.\n */\n layout?: 'strip' | 'grid'\n}\n\ninterface CatalogItem {\n id: string\n name: string\n slug: string\n priceUsd: number\n imageUrl?: string\n /** Listed before it has a price (AGL-3676). */\n priceComingSoon?: boolean\n}\n\n/**\n * Related products / upsell strip (AGL-325): the product's manual list,\n * else \"frequently bought together\" from recent orders, else tag and\n * category neighbors — resolved server-side, rendered as cards.\n */\nconst RelatedProducts = forwardRef<HTMLDivElement, RelatedProductsProps>(\n (props, ref) => {\n const { productId: productIdProp, heading, maxItems, layout, ...rest } = props\n // Node styles ride the renderer-merged sx; recompose (stack.ts pattern).\n const nodeSx = Array.isArray(props['sx']) ? props['sx'] : [props['sx']]\n const site = Aglyn.useSite()\n const { hostId } = site\n // The page's product, when the server seeded it (AGL-659): its id is the\n // anchor, so the rail skips a product lookup the page already made.\n const seededProductId = (\n site.pageData as { commerce?: { product?: { id?: string } } } | undefined\n )?.commerce?.product?.id\n const [items, setItems] = useState<CatalogItem[] | null>(null)\n\n useEffect(() => {\n if (!hostId) return\n let active = true\n void (async () => {\n let anchor = productIdProp || seededProductId || ''\n if (!anchor) {\n const match = window.location.pathname.match(/\\/products\\/([^/?#]+)/)\n if (!match) return\n const response = await fetch(\n `/api/commerce/product?hostId=${encodeURIComponent(hostId)}` +\n `&slug=${encodeURIComponent(decodeURIComponent(match[1]))}`,\n ).catch(() => null)\n const payload = await response?.json().catch(() => ({}))\n anchor = String(payload?.product?.id ?? '')\n }\n if (!active || !anchor) return\n const relatedResponse = await fetch(\n `/api/commerce/related?hostId=${encodeURIComponent(hostId)}` +\n `&productId=${encodeURIComponent(anchor)}`,\n ).catch(() => null)\n const related = await relatedResponse?.json().catch(() => ({}))\n const ids: string[] = related?.productIds ?? []\n if (!active || ids.length === 0) return setItems([])\n const catalogResponse = await fetch(\n `/api/commerce/catalog?hostId=${encodeURIComponent(hostId)}` +\n `&ids=${encodeURIComponent(ids.join(','))}`,\n ).catch(() => null)\n const catalog = await catalogResponse?.json().catch(() => ({}))\n if (active) setItems(catalog?.items ?? [])\n })()\n return () => {\n active = false\n }\n }, [hostId, productIdProp, seededProductId])\n\n if (!hostId) {\n return (\n <Box\n ref={ref}\n {...rest}\n sx={[\n {\n p: 3,\n border: '1px dashed',\n borderColor: 'divider',\n borderRadius: 1,\n color: 'text.secondary',\n fontSize: 13,\n fontFamily: 'system-ui, sans-serif',\n },\n ...nodeSx,\n ]}\n >\n {'Related products render here'}\n </Box>\n )\n }\n if (!items || items.length === 0) return <Box ref={ref} {...rest} />\n\n const grid = layout === 'grid'\n return (\n <Box ref={ref} {...rest}>\n <Typography variant={grid ? 'h5' : 'h6'} component=\"h2\" gutterBottom sx={grid ? { mb: 2 } : undefined}>\n {heading || 'You may also like'}\n </Typography>\n <Box\n sx={\n grid\n ? {\n display: 'grid',\n gap: 2,\n gridTemplateColumns: { xs: 'repeat(2, minmax(0, 1fr))', md: 'repeat(4, minmax(0, 1fr))' },\n }\n : { display: 'flex', gap: 1.5, overflowX: 'auto', pb: 1 }\n }\n >\n {items\n .slice(0, maxItems && maxItems > 0 ? maxItems : 6)\n .map((item) => {\n // AGL-1726: resolved BEFORE the guard — see the note in\n // `product-detail.tsx`.\n const imageUrl = Aglyn.siteRelativeMediaSrc(item.imageUrl, {\n hostId,\n })\n const mediaSx = grid\n ? { aspectRatio: '4 / 5', borderRadius: 2 }\n : { height: 110 }\n return (\n <Card\n key={item.id}\n variant={grid ? 'elevation' : 'outlined'}\n elevation={0}\n sx={grid ? { bgcolor: 'transparent', overflow: 'visible', minWidth: 0 } : { minWidth: 160 }}\n >\n <CardActionArea\n href={`/products/${item.slug}`}\n sx={grid ? { borderRadius: 2 } : undefined}\n >\n {imageUrl ? (\n <CardMedia\n component=\"img\"\n image={imageUrl}\n alt={item.name}\n sx={{ ...mediaSx, objectFit: 'cover' }}\n // Deferred (AGL-2486). A related-products rail sits at\n // the BOTTOM of a product page by construction, and it\n // was fetching eagerly against the gallery hero above\n // it — the one image on that page that is the LCP.\n {...Aglyn.DEFERRED_IMAGE_ATTRIBUTES}\n />\n ) : (\n // Never a blank tile: a product with no photo yet says\n // so, in the theme's colours (AGL-3676 follow-up).\n <ProductImagePlaceholder name={item.name} sx={mediaSx} />\n )}\n <CardContent sx={grid ? { px: 0.5, pt: 1.5, pb: 1 } : { py: 1 }}>\n <Typography variant={grid ? 'subtitle1' : 'body2'} noWrap>\n {item.name}\n </Typography>\n <Typography variant={grid ? 'body2' : 'caption'} color=\"text.secondary\">\n {item.priceComingSoon\n ? 'Price coming soon'\n : formatOrderMoney(Math.round(item.priceUsd * 100))}\n </Typography>\n </CardContent>\n </CardActionArea>\n </Card>\n )\n })}\n </Box>\n </Box>\n )\n },\n)\nRelatedProducts.displayName = 'AglynRelatedProducts'\n\nexport const schema: Aglyn.ComponentSchema<RelatedProductsProps> = {\n $id: ID,\n pluginId: BUNDLE_ID,\n displayName: 'Related products',\n description:\n 'An upsell strip — your manual picks, or what people buy together.',\n category: Aglyn.ComponentCategory.COMMERCE,\n icon: { path: mdiShapePlus.path, sx: { color: '#2e7d32' } },\n flags: { selfClosing: Aglyn.FEATURE_FLAG.ENABLED },\n attributes: [\n {\n name: 'productId',\n label: 'Product id',\n description:\n 'The product to find relatives OF. Blank reads it from the URL, so ' +\n 'a product template shows each product’s own related items; naming ' +\n 'one pins the rail to that product’s relatives everywhere.',\n component: Aglyn.FieldComponentType.PRODUCT_SELECT,\n },\n {\n name: 'heading',\n label: 'Heading',\n description: 'Defaults to \"You may also like\".',\n component: Aglyn.FieldComponentType.TEXT_FIELD,\n },\n {\n name: 'maxItems',\n label: 'Max items',\n description: 'Cap the strip (default 6).',\n component: Aglyn.FieldComponentType.TEXT_FIELD,\n type: 'number',\n },\n {\n // Default `strip`, so a page that already places this block keeps it.\n name: 'layout',\n label: 'Layout',\n description: 'A scrolling strip of small cards, or a grid of tall photo cards.',\n component: Aglyn.FieldComponentType.SELECT,\n options: [\n { label: 'Strip', value: 'strip' },\n { label: 'Photo grid', value: 'grid' },\n ],\n },\n ],\n}\n\nexport const presets: Aglyn.PresetSchema[] = [\n {\n $id: generatePresetId(ID),\n type: Aglyn.NodeType.PRESET,\n displayName: 'Related products',\n pluginId: BUNDLE_ID,\n description: 'Manual picks or frequently-bought-together',\n category: Aglyn.ComponentCategory.COMMERCE,\n icon: { path: mdiShapePlus.path, sx: { color: '#2e7d32' } },\n data: {\n $id: null,\n componentId: ID,\n pluginId: BUNDLE_ID,\n props: {},\n },\n },\n]\n\nexport default RelatedProducts\n"],"names":["Aglyn","mdiShapePlus","Box","Card","CardActionArea","CardContent","CardMedia","Typography","forwardRef","useEffect","useState","BUNDLE_ID","generatePresetId","formatOrderMoney","ProductImagePlaceholder","ID","RelatedProducts","props","ref","site","productId","productIdProp","heading","maxItems","layout","rest","nodeSx","Array","isArray","useSite","hostId","seededProductId","pageData","commerce","product","id","items","setItems","active","anchor","payload","match","window","location","pathname","response","fetch","encodeURIComponent","decodeURIComponent","catch","json","String","relatedResponse","related","ids","productIds","length","catalogResponse","join","catalog","sx","p","border","borderColor","borderRadius","color","fontSize","fontFamily","grid","variant","component","gutterBottom","mb","undefined","display","gap","gridTemplateColumns","xs","md","overflowX","pb","slice","map","item","imageUrl","siteRelativeMediaSrc","mediaSx","aspectRatio","height","elevation","bgcolor","overflow","minWidth","href","slug","image","alt","name","objectFit","DEFERRED_IMAGE_ATTRIBUTES","px","pt","py","noWrap","priceComingSoon","Math","round","priceUsd","displayName","schema","$id","pluginId","description","category","ComponentCategory","COMMERCE","icon","path","flags","selfClosing","FEATURE_FLAG","ENABLED","attributes","label","FieldComponentType","PRODUCT_SELECT","TEXT_FIELD","type","SELECT","options","value","presets","NodeType","PRESET","data","componentId"],"mappings":";;;AAAA;;;;;;;;;;;;;;;CAeC,GAED,YAAYA,WAAW,eAAc;AACrC,SAASC,YAAY,QAAQ,yBAAwB;AACrD,OAAOC,SAAS,oBAAmB;AACnC,OAAOC,UAAU,qBAAoB;AACrC,OAAOC,oBAAoB,+B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QACR;QACA;YACE,sEAAsE;YACtE9B,MAAM;YACN0B,OAAO;YACPX,aAAa;YACb1C,WAAWtE,MAAM4H,kBAAkB,CAACI,MAAM;YAC1CC,SAAS;gBACP;oBAAEN,OAAO;oBAASO,OAAO;gBAAQ;gBACjC;oBAAEP,OAAO;oBAAcO,OAAO;gBAAO;aACtC;QACH;KACD;AACH,EAAC;AAED,OAAO,MAAMC,UAAgC;IAC3C;QACErB,KAAKlG,iBAAiBG;QACtBgH,MAAM/H,MAAMoI,QAAQ,CAACC,MAAM;QAC3BzB,aAAa;QACbG,UAAUpG;QACVqG,aAAa;QACbC,UAAUjH,MAAMkH,iBAAiB,CAACC,QAAQ;QAC1CC,MAAM;YAAEC,MAAMpH,aAAaoH,IAAI;YAAEzD,IAAI;gBAAEK,OAAO;YAAU;QAAE;QAC1DqE,MAAM;YACJxB,KAAK;YACLyB,aAAaxH;YACbgG,UAAUpG;YACVM,OAAO,CAAC;QACV;IACF;CACD,CAAA;AAED,eAAeD,gBAAe"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/components/related-products.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as Aglyn from '@aglyn/aglyn'\nimport { mdiShapePlus } from '@aglyn/shared-data-mdi'\nimport Box from '@mui/material/Box'\nimport Card from '@mui/material/Card'\nimport CardActionArea from '@mui/material/CardActionArea'\nimport CardContent from '@mui/material/CardContent'\nimport CardMedia from '@mui/material/CardMedia'\nimport Typography from '@mui/material/Typography'\nimport { forwardRef, useEffect, useState } from 'react'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport { generatePresetId } from '../utils/generate-preset-id'\nimport { formatOrderMoney } from '../model/buyer-notifications'\nimport { ProductImagePlaceholder } from './product-image-placeholder'\n\n// Component ids are persisted in screen documents; never rename.\nexport const ID: Aglyn.ComponentId = 'related-products'\n\nexport interface RelatedProductsProps {\n /** Anchor product id; blank follows the /products/{slug} page. */\n productId?: string\n heading?: string\n maxItems?: number\n /**\n * How the items are drawn: `strip`, the default, a scrolling row of small\n * cards; `grid`, tall photo cards (4:5) with the name and price under\n * them in a grid of up to four across — the product grid's photo look.\n */\n layout?: 'strip' | 'grid'\n}\n\ninterface CatalogItem {\n id: string\n name: string\n slug: string\n priceUsd: number\n imageUrl?: string\n /** Listed before it has a price (AGL-3676). */\n priceComingSoon?: boolean\n}\n\n/**\n * Related products / upsell strip (AGL-325): the product's manual list,\n * else \"frequently bought together\" from recent orders, else tag and\n * category neighbors — resolved server-side, rendered as cards.\n */\nconst RelatedProducts = forwardRef<HTMLDivElement, RelatedProductsProps>(\n (props, ref) => {\n const { productId: productIdProp, heading, maxItems, layout, ...rest } = props\n // Node styles ride the renderer-merged sx; recompose (stack.ts pattern).\n const nodeSx = Array.isArray(props['sx']) ? props['sx'] : [props['sx']]\n const site = Aglyn.useSite()\n const { hostId } = site\n // The page's product, when the server seeded it (AGL-659): its id is the\n // anchor, so the rail skips a product lookup the page already made.\n const seededProductId = (\n site.pageData as { commerce?: { product?: { id?: string } } } | undefined\n )?.commerce?.product?.id\n const [items, setItems] = useState<CatalogItem[] | null>(null)\n // The catalog counts the cap over products on sale (AGL-4038).\n const cap = Number(maxItems) > 0 ? Math.floor(Number(maxItems)) : 6\n\n useEffect(() => {\n if (!hostId) return\n let active = true\n void (async () => {\n let anchor = productIdProp || seededProductId || ''\n if (!anchor) {\n const match = window.location.pathname.match(/\\/products\\/([^/?#]+)/)\n if (!match) return\n const response = await fetch(\n `/api/commerce/product?hostId=${encodeURIComponent(hostId)}` +\n `&slug=${encodeURIComponent(decodeURIComponent(match[1]))}`,\n ).catch(() => null)\n const payload = await response?.json().catch(() => ({}))\n anchor = String(payload?.product?.id ?? '')\n }\n if (!active || !anchor) return\n const relatedResponse = await fetch(\n `/api/commerce/related?hostId=${encodeURIComponent(hostId)}` +\n `&productId=${encodeURIComponent(anchor)}`,\n ).catch(() => null)\n const related = await relatedResponse?.json().catch(() => ({}))\n const ids: string[] = related?.productIds ?? []\n if (!active || ids.length === 0) return setItems([])\n const catalogResponse = await fetch(\n `/api/commerce/catalog?hostId=${encodeURIComponent(hostId)}` +\n `&ids=${encodeURIComponent(ids.join(','))}&limit=${cap}`,\n ).catch(() => null)\n const catalog = await catalogResponse?.json().catch(() => ({}))\n if (active) setItems(catalog?.items ?? [])\n })()\n return () => {\n active = false\n }\n }, [hostId, productIdProp, seededProductId, cap])\n\n if (!hostId) {\n return (\n <Box\n ref={ref}\n {...rest}\n sx={[\n {\n p: 3,\n border: '1px dashed',\n borderColor: 'divider',\n borderRadius: 1,\n color: 'text.secondary',\n fontSize: 13,\n fontFamily: 'system-ui, sans-serif',\n },\n ...nodeSx,\n ]}\n >\n {'Related products render here'}\n </Box>\n )\n }\n if (!items || items.length === 0) return <Box ref={ref} {...rest} />\n\n const grid = layout === 'grid'\n return (\n <Box ref={ref} {...rest}>\n <Typography variant={grid ? 'h5' : 'h6'} component=\"h2\" gutterBottom sx={grid ? { mb: 2 } : undefined}>\n {heading || 'You may also like'}\n </Typography>\n <Box\n sx={\n grid\n ? {\n display: 'grid',\n gap: 2,\n gridTemplateColumns: { xs: 'repeat(2, minmax(0, 1fr))', md: 'repeat(4, minmax(0, 1fr))' },\n }\n : { display: 'flex', gap: 1.5, overflowX: 'auto', pb: 1 }\n }\n >\n {items\n .slice(0, cap)\n .map((item) => {\n // AGL-1726: resolved BEFORE the guard — see the note in\n // `product-detail.tsx`.\n const imageUrl = Aglyn.siteRelativeMediaSrc(item.imageUrl, {\n hostId,\n })\n const mediaSx = grid\n ? { aspectRatio: '4 / 5', borderRadius: 2 }\n : { height: 110 }\n return (\n <Card\n key={item.id}\n variant={grid ? 'elevation' : 'outlined'}\n elevation={0}\n sx={grid ? { bgcolor: 'transparent', overflow: 'visible', minWidth: 0 } : { minWidth: 160 }}\n >\n <CardActionArea\n href={`/products/${item.slug}`}\n sx={grid ? { borderRadius: 2 } : undefined}\n >\n {imageUrl ? (\n <CardMedia\n component=\"img\"\n image={imageUrl}\n alt={item.name}\n sx={{ ...mediaSx, objectFit: 'cover' }}\n // Deferred (AGL-2486). A related-products rail sits at\n // the BOTTOM of a product page by construction, and it\n // was fetching eagerly against the gallery hero above\n // it — the one image on that page that is the LCP.\n {...Aglyn.DEFERRED_IMAGE_ATTRIBUTES}\n />\n ) : (\n // Never a blank tile: a product with no photo yet says\n // so, in the theme's colours (AGL-3676 follow-up).\n <ProductImagePlaceholder name={item.name} sx={mediaSx} />\n )}\n <CardContent sx={grid ? { px: 0.5, pt: 1.5, pb: 1 } : { py: 1 }}>\n <Typography variant={grid ? 'subtitle1' : 'body2'} noWrap>\n {item.name}\n </Typography>\n <Typography variant={grid ? 'body2' : 'caption'} color=\"text.secondary\">\n {item.priceComingSoon\n ? 'Price coming soon'\n : formatOrderMoney(Math.round(item.priceUsd * 100))}\n </Typography>\n </CardContent>\n </CardActionArea>\n </Card>\n )\n })}\n </Box>\n </Box>\n )\n },\n)\nRelatedProducts.displayName = 'AglynRelatedProducts'\n\nexport const schema: Aglyn.ComponentSchema<RelatedProductsProps> = {\n $id: ID,\n pluginId: BUNDLE_ID,\n displayName: 'Related products',\n description:\n 'An upsell strip — your manual picks, or what people buy together.',\n category: Aglyn.ComponentCategory.COMMERCE,\n icon: { path: mdiShapePlus.path, sx: { color: '#2e7d32' } },\n flags: { selfClosing: Aglyn.FEATURE_FLAG.ENABLED },\n attributes: [\n {\n name: 'productId',\n label: 'Product id',\n description:\n 'The product to find relatives OF. Blank reads it from the URL, so ' +\n 'a product template shows each product’s own related items; naming ' +\n 'one pins the rail to that product’s relatives everywhere.',\n component: Aglyn.FieldComponentType.PRODUCT_SELECT,\n },\n {\n name: 'heading',\n label: 'Heading',\n description: 'Defaults to \"You may also like\".',\n component: Aglyn.FieldComponentType.TEXT_FIELD,\n },\n {\n name: 'maxItems',\n label: 'Max items',\n description: 'Cap the strip (default 6).',\n component: Aglyn.FieldComponentType.TEXT_FIELD,\n type: 'number',\n },\n {\n // Default `strip`, so a page that already places this block keeps it.\n name: 'layout',\n label: 'Layout',\n description: 'A scrolling strip of small cards, or a grid of tall photo cards.',\n component: Aglyn.FieldComponentType.SELECT,\n options: [\n { label: 'Strip', value: 'strip' },\n { label: 'Photo grid', value: 'grid' },\n ],\n },\n ],\n}\n\nexport const presets: Aglyn.PresetSchema[] = [\n {\n $id: generatePresetId(ID),\n type: Aglyn.NodeType.PRESET,\n displayName: 'Related products',\n pluginId: BUNDLE_ID,\n description: 'Manual picks or frequently-bought-together',\n category: Aglyn.ComponentCategory.COMMERCE,\n icon: { path: mdiShapePlus.path, sx: { color: '#2e7d32' } },\n data: {\n $id: null,\n componentId: ID,\n pluginId: BUNDLE_ID,\n props: {},\n },\n },\n]\n\nexport default RelatedProducts\n"],"names":["Aglyn","mdiShapePlus","Box","Card","CardActionArea","CardContent","CardMedia","Typography","forwardRef","useEffect","useState","BUNDLE_ID","generatePresetId","formatOrderMoney","ProductImagePlaceholder","ID","RelatedProducts","props","ref","site","productId","productIdProp","heading","maxItems","layout","rest","nodeSx","Array","isArray","useSite","hostId","seededProductId","pageData","commerce","product","id","items","setItems","cap","Number","Math","floor","active","anchor","payload","match","window","location","pathname","response","fetch","encodeURIComponent","decodeURIComponent","catch","json","String","relatedResponse","related","ids","productIds","length","catalogResponse","join","catalog","sx","p","border","borderColor","borderRadius","color","fontSize","fontFamily","grid","variant","component","gutterBottom","mb","undefined","display","gap","gridTemplateColumns","xs","md","overflowX","pb","slice","map","item","imageUrl","siteRelativeMediaSrc","mediaSx","aspectRatio","height","elevation","bgcolor","overflow","minWidth","href","slug","image","alt","name","objectFit","DEFERRED_IMAGE_ATTRIBUTES","px","pt","py","noWrap","priceComingSoon","round","priceUsd","displayName","schema","$id","pluginId","description","category","ComponentCategory","COMMERCE","icon","path","flags","selfClosing","FEATURE_FLAG","ENABLED","attributes","label","FieldComponentType","PRODUCT_SELECT","TEXT_FIELD","type","SELECT","options","value","presets","NodeType","PRESET","data","componentId"],"mappings":";;;AAAA;;;;;;;;;;;;;;;CAeC,GAED,YAAYA,WAAW,eAAc;AACrC,SAASC,YAAY,QAAQ,yBAAwB;AACrD,OAAOC,SAAS,oBAAmB;AACnC,OAAOC,UAAU,qBAAoB;AACrC,OAAOC,oBAAoB,+BAA8B;AACzD,OAAOC,iBAAiB,4BAA2B;AACnD,OAAOC,eAAe,0BAAyB;AAC/C,OAAOC,gBAAgB,2BAA0B;AACjD,SAASC,UAAU,EAAEC,SAAS,EAAEC,QAAQ,QAAQ,QAAO;AACvD,SAASC,SAAS,QAAQ,gCAA4B;AACtD,SAASC,gBAAgB,QAAQ,iCAA6B;AAC9D,SAASC,gBAAgB,QAAQ,kCAA8B;AAC/D,SAASC,uBAAuB,QAAQ,iCAA6B;AAErE,iEAAiE;AACjE,OAAO,MAAMC,KAAwB,mBAAkB;AAyBvD;;;;CAIC,GACD,MAAMC,gCAAkBR,WACtB,CAACS,OAAOC;QAQkB,iCAAA,yBACtBC;IARF,MAAM,EAAEC,WAAWC,aAAa,EAAEC,OAAO,EAAEC,QAAQ,EAAEC,MAAM,EAAW,GAAGP,OAATQ,wCAASR;;;;;;IACzE,yEAAyE;IACzE,MAAMS,SAASC,MAAMC,OAAO,CAACX,KAAK,CAAC,KAAK,IAAIA,KAAK,CAAC,KAAK,GAAG;QAACA,KAAK,CAAC,KAAK;KAAC;IACvE,MAAME,OAAOnB,MAAM6B,OAAO;IAC1B,MAAM,EAAEC,MAAM,EAAE,GAAGX;IACnB,yEAAyE;IACzE,oEAAoE;IACpE,MAAMY,mBACJZ,iBAAAA,KAAKa,QAAQ,sBADS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ACFC,UAAUpH,MAAMqH,iBAAiB,CAACC,QAAQ;IAC1CC,MAAM;QAAEC,MAAMvH,aAAauH,IAAI;QAAExD,IAAI;YAAEK,OAAO;QAAU;IAAE;IAC1DoD,OAAO;QAAEC,aAAa1H,MAAM2H,YAAY,CAACC,OAAO;IAAC;IACjDC,YAAY;QACV;YACExB,MAAM;YACNyB,OAAO;YACPX,aACE,uEACA,uEACA;YACFzC,WAAW1E,MAAM+H,kBAAkB,CAACC,cAAc;QACpD;QACA;YACE3B,MAAM;YACNyB,OAAO;YACPX,aAAa;YACbzC,WAAW1E,MAAM+H,kBAAkB,CAACE,UAAU;QAChD;QACA;YACE5B,MAAM;YACNyB,OAAO;YACPX,aAAa;YACbzC,WAAW1E,MAAM+H,kBAAkB,CAACE,UAAU;YAC9CC,MAAM;QACR;QACA;YACE,sEAAsE;YACtE7B,MAAM;YACNyB,OAAO;YACPX,aAAa;YACbzC,WAAW1E,MAAM+H,kBAAkB,CAACI,MAAM;YAC1CC,SAAS;gBACP;oBAAEN,OAAO;oBAASO,OAAO;gBAAQ;gBACjC;oBAAEP,OAAO;oBAAcO,OAAO;gBAAO;aACtC;QACH;KACD;AACH,EAAC;AAED,OAAO,MAAMC,UAAgC;IAC3C;QACErB,KAAKrG,iBAAiBG;QACtBmH,MAAMlI,MAAMuI,QAAQ,CAACC,MAAM;QAC3BzB,aAAa;QACbG,UAAUvG;QACVwG,aAAa;QACbC,UAAUpH,MAAMqH,iBAAiB,CAACC,QAAQ;QAC1CC,MAAM;YAAEC,MAAMvH,aAAauH,IAAI;YAAExD,IAAI;gBAAEK,OAAO;YAAU;QAAE;QAC1DoE,MAAM;YACJxB,KAAK;YACLyB,aAAa3H;YACbmG,UAAUvG;YACVM,OAAO,CAAC;QACV;IACF;CACD,CAAA;AAED,eAAeD,gBAAe"}
@@ -97,6 +97,12 @@ export interface StorefrontPaymentElementProps {
97
97
  /** Stripe's instruction to the browser. Not a claim that money moved. */
98
98
  clientSecret: string;
99
99
  publishableKey: string;
100
+ /**
101
+ * The seller's connected account when the session is a DIRECT charge: the
102
+ * session lives on that account, so Stripe.js has to be opened for it or the
103
+ * client secret will not resolve.
104
+ */
105
+ stripeAccount?: string;
100
106
  /** Shown on the pay button, so the merchant's own total reads through. */
101
107
  payLabel?: string;
102
108
  /**
@@ -127,7 +133,7 @@ export interface StorefrontPaymentElementProps {
127
133
  }
128
134
  /** Test seam: `loadStripe` caches per key across a file's tests otherwise. */
129
135
  export declare function __resetStripePromises(): void;
130
- export declare function StorefrontPaymentElement({ clientSecret, publishableKey, payLabel, defaultEmail, onCancel, onRestart, wallets, defaultShippingAddress, }: StorefrontPaymentElementProps): import("react").JSX.Element;
136
+ export declare function StorefrontPaymentElement({ clientSecret, publishableKey, stripeAccount, payLabel, defaultEmail, onCancel, onRestart, wallets, defaultShippingAddress, }: StorefrontPaymentElementProps): import("react").JSX.Element;
131
137
  /**
132
138
  * Re-exported so the old import path still resolves, but the definition now
133
139
  * lives in its own module (AGL-2486): a fallback imported FROM the lazily
@@ -46,12 +46,15 @@ import { storefrontPaymentAppearance, storefrontPaymentFonts } from "./storefron
46
46
  * called per render. Keyed because a page could in principle mount this for
47
47
  * two different merchants; in practice it is one, and the map costs nothing.
48
48
  */ const stripePromises = new Map();
49
- function getStripe(publishableKey) {
49
+ function getStripe(publishableKey, stripeAccount) {
50
50
  if (!publishableKey) return null;
51
- let promise = stripePromises.get(publishableKey);
51
+ const key = stripeAccount ? `${publishableKey}:${stripeAccount}` : publishableKey;
52
+ let promise = stripePromises.get(key);
52
53
  if (!promise) {
53
- promise = loadStripe(publishableKey);
54
- stripePromises.set(publishableKey, promise);
54
+ promise = stripeAccount ? loadStripe(publishableKey, {
55
+ stripeAccount
56
+ }) : loadStripe(publishableKey);
57
+ stripePromises.set(key, promise);
55
58
  }
56
59
  return promise;
57
60
  }
@@ -431,9 +434,10 @@ function PaymentForm({ payLabel, defaultEmail, onCancel, onRestart, wallets }) {
431
434
  ]
432
435
  });
433
436
  }
434
- export function StorefrontPaymentElement({ clientSecret, publishableKey, payLabel, defaultEmail, onCancel, onRestart, wallets, defaultShippingAddress }) {
435
- const stripe = useMemo(()=>getStripe(publishableKey), [
436
- publishableKey
437
+ export function StorefrontPaymentElement({ clientSecret, publishableKey, stripeAccount, payLabel, defaultEmail, onCancel, onRestart, wallets, defaultShippingAddress }) {
438
+ const stripe = useMemo(()=>getStripe(publishableKey, stripeAccount), [
439
+ publishableKey,
440
+ stripeAccount
437
441
  ]);
438
442
  const theme = useTheme();
439
443
  // Built once per session: the provider reads its options at mount and
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/components/storefront-payment-element.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n'use client'\n\n// The `/checkout` entry, not the main one: react-stripe-js v6 moved the\n// Checkout Sessions provider, its hook and its own `PaymentElement` there, and\n// the main entry's `PaymentElement` is the Elements one, which does not mount\n// under a Checkout provider.\nimport {\n CheckoutElementsProvider,\n PaymentElement,\n ShippingAddressElement,\n useCheckoutElements,\n} from '@stripe/react-stripe-js/checkout'\n// `/pure` deliberately, not the bare entry (AGL-2486). The bare entry ends\n// with a module-scope `Promise.resolve().then(() => getStripePromise())`,\n// so merely EVALUATING it injects the js.stripe.com/v3 script tag —\n// 249 KB gzipped — on any page that reaches this module, whether or not\n// `loadStripe` is ever called. `/pure` is the same API without that\n// statement, so the script is fetched when we ask for it and not before.\nimport { loadStripe } from '@stripe/stripe-js/pure'\n// The TYPE only, and from the bare entry because `/pure` does not re-export\n// it. `import type` is erased entirely at compile time, so this adds no\n// runtime import and cannot re-introduce the script injection above.\nimport type {\n Stripe,\n StripeAddressElementChangeEvent,\n StripeCheckoutContact,\n StripeCheckoutElementsSdkOptions,\n} from '@stripe/stripe-js'\nimport Alert from '@mui/material/Alert'\nimport Box from '@mui/material/Box'\nimport Button from '@mui/material/Button'\nimport CircularProgress from '@mui/material/CircularProgress'\nimport Divider from '@mui/material/Divider'\nimport FormControlLabel from '@mui/material/FormControlLabel'\nimport Radio from '@mui/material/Radio'\nimport RadioGroup from '@mui/material/RadioGroup'\nimport TextField from '@mui/material/TextField'\nimport Typography from '@mui/material/Typography'\nimport { useTheme } from '@mui/material/styles'\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport {\n storefrontPaymentAppearance,\n storefrontPaymentFonts,\n} from './storefront-payment-appearance'\nimport type { StorefrontCheckoutWallets } from '../model/commerce-payment-methods'\n\n/**\n * The storefront Payment Element (AGL-1944) — the shopper pays on the\n * merchant's own domain instead of being sent to `checkout.stripe.com`.\n *\n * ## THIS COMPONENT DOES NOT FULFIL ANYTHING\n *\n * It has no success callback, and that absence is the design rather than an\n * omission. `libs/plugins/commerce/src/lib/server/billing-webhook.ts` creates\n * the order on `checkout.session.completed` and is the only thing that ever\n * does. An in-page flow makes trusting the browser far more tempting than a\n * redirect does — the form is right there, `confirm()` resolves in hand, and\n * posting \"done, please fulfil\" is one line away — and the browser is the one\n * participant in a payment that can lie about having paid.\n *\n * It is also the participant that can VANISH. A shopper who confirms and\n * closes the tab never runs a callback, so a flow that fulfils here loses the\n * order outright while keeping the money; a shopper who refreshes the return\n * page runs it twice. Neither is reachable from a design with no callback in\n * it. What happens after a successful confirm is a redirect to `return_url`,\n * carrying the `session_id` the server put there — so the page can SHOW the\n * shopper a result by looking the order up, without being TOLD the outcome by\n * this code.\n *\n * ## Declines and 3DS\n *\n * Both were handled for us by the redirect and now have to be handled here.\n *\n * A decline resolves as `{ type: 'error' }` and is rendered inline WITHOUT\n * unmounting the form: the shopper's basket, address and chosen method are all\n * still on screen and they can try another card. That is the whole difference\n * between a recoverable decline and a dead end, and it is why the error state\n * below sits beside the element rather than replacing it.\n *\n * A 3DS challenge is Stripe's own: `confirm()` presents the challenge and, for\n * redirect-based methods, sends the browser to `return_url` and back. Nothing\n * here has to model it — but the button must stay disabled across the whole\n * await, because a second `confirm()` during a challenge is exactly the\n * double-submit the server's idempotency claim exists to survive and there is\n * no reason to make it lean on that.\n *\n * ## Everything the hosted page collected, collected here (AGL-3606)\n *\n * The hosted page asked for an email, a shipping address and a shipping\n * method, and showed a running total. A `ui_mode: 'elements'` session asks\n * for none of that on its own — the Payment Element is only the payment\n * method — so each is mounted here, read off the SESSION rather than off\n * anything the storefront believes:\n *\n * - **Email.** A session created with `customer_email` (the cart's email\n * field) already has one and Stripe refuses `updateEmail` on it, so it is\n * shown read-only. Otherwise a required field, sent with `updateEmail`\n * before `confirm()` — the receipt and the order's customer both come from\n * it, and a sale without one is an order nobody can be told about.\n * - **Shipping.** Only when the session carries shipping options, which the\n * server attaches only when the store ships to the destination. The\n * Shipping Address Element collects the address (and, under Stripe Tax,\n * is where the tax is computed from); the picker lists the session's own\n * options and selects through `updateShippingOption`.\n * - **Tax address without shipping.** Left to the Payment Element, which\n * collects the country and postal code Stripe Tax needs when the session\n * has `automatic_tax` and no shipping address. A Billing Address Element\n * there would make `updateBillingAddress` conflict with it.\n * - **The total.** Rendered from `session.total`, which Stripe recomputes on\n * every address and option change — tax and shipping included — so the\n * number on the button is the number charged.\n * - **The look.** `elementsOptions.appearance` and `fonts` come from the site\n * theme (`storefront-payment-appearance.ts`), so Stripe's frames wear the\n * merchant's palette, radius and typeface.\n *\n * ## Expired and redirect-returned sessions\n *\n * A session that expired, or that cannot be loaded, offers a fresh one through\n * `onRestart` (a NEW attempt key, so the server does not replay the dead\n * session). A redirect-based method that fails comes back to `return_url`\n * with the session still open; `use-checkout-return-notice.ts` reads that on\n * the return page and says nothing was charged.\n */\n\nexport interface StorefrontPaymentElementProps {\n /** Stripe's instruction to the browser. Not a claim that money moved. */\n clientSecret: string\n publishableKey: string\n /** Shown on the pay button, so the merchant's own total reads through. */\n payLabel?: string\n /**\n * An email the storefront already knows but did not put on the session\n * (it prefills the field; the shopper can still change it). A session the\n * server created WITH an email shows that one read-only instead.\n */\n defaultEmail?: string\n /** Abandon the in-page form and return to the store. */\n onCancel?: () => void\n /**\n * Open a fresh session after this one expired or could not be loaded. The\n * caller must mint a NEW attempt key first, or the server replays the dead\n * session for the old one.\n */\n onRestart?: () => void\n /**\n * The wallets the merchant hid (AGL-3629). Stripe cannot exclude Apple Pay,\n * Google Pay or Link on the session, so the Payment Element is told instead.\n * Absent means every wallet the device supports shows.\n */\n wallets?: StorefrontCheckoutWallets\n /**\n * An address the shipping fields start with, where the session asks for\n * one: a quote's ship-to (AGL-4094). The shopper can still change it.\n */\n defaultShippingAddress?: StripeCheckoutContact\n}\n\n/**\n * `loadStripe` injects a script tag, so it is memoized per key rather than\n * called per render. Keyed because a page could in principle mount this for\n * two different merchants; in practice it is one, and the map costs nothing.\n */\nconst stripePromises = new Map<string, Promise<Stripe | null>>()\nfunction getStripe(publishableKey: string): Promise<Stripe | null> | null {\n if (!publishableKey) return null\n let promise = stripePromises.get(publishableKey)\n if (!promise) {\n promise = loadStripe(publishableKey)\n stripePromises.set(publishableKey, promise)\n }\n return promise\n}\n\n/** Test seam: `loadStripe` caches per key across a file's tests otherwise. */\nexport function __resetStripePromises(): void {\n stripePromises.clear()\n}\n\nconst GENERIC_FAILURE = 'That payment could not be completed. Try another card.'\n\n/** How long the address must sit still before the session re-prices on it. */\nconst ADDRESS_SETTLE_MS = 400\n\nfunction SummaryRow({\n label,\n value,\n strong,\n}: {\n label: string\n value: string\n strong?: boolean\n}) {\n return (\n <Box sx={{ display: 'flex', justifyContent: 'space-between', gap: 2 }}>\n <Typography\n variant={strong ? 'subtitle1' : 'body2'}\n color={strong ? 'text.primary' : 'text.secondary'}\n >\n {label}\n </Typography>\n <Typography variant={strong ? 'subtitle1' : 'body2'}>{value}</Typography>\n </Box>\n )\n}\n\nfunction SessionNotice({\n message,\n onCancel,\n onRestart,\n}: {\n message: string\n onCancel?: () => void\n onRestart?: () => void\n}) {\n return (\n <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>\n <Alert severity=\"error\" role=\"alert\">\n {message}\n </Alert>\n <Box sx={{ display: 'flex', gap: 1 }}>\n {onRestart ? (\n <Button variant=\"contained\" onClick={onRestart}>\n {'Start checkout again'}\n </Button>\n ) : null}\n {onCancel ? (\n <Button variant=\"text\" onClick={onCancel}>\n {'Back to the store'}\n </Button>\n ) : null}\n </Box>\n </Box>\n )\n}\n\nfunction PaymentForm({\n payLabel,\n defaultEmail,\n onCancel,\n onRestart,\n wallets,\n}: Pick<\n StorefrontPaymentElementProps,\n 'payLabel' | 'defaultEmail' | 'onCancel' | 'onRestart' | 'wallets'\n>) {\n // A `{ type: 'loading' | 'success' | 'error' }` union since react-stripe-js\n // v6: the session is not usable until Stripe.js has booted against it.\n const checkoutState = useCheckoutElements()\n const checkout =\n checkoutState.type === 'success' ? checkoutState.checkout : null\n const [status, setStatus] = useState<'idle' | 'confirming' | 'error'>('idle')\n const [message, setMessage] = useState('')\n const [email, setEmail] = useState(defaultEmail ?? '')\n const [emailError, setEmailError] = useState('')\n const [shippingBusy, setShippingBusy] = useState(false)\n\n /**\n * The email the SERVER put on the session, latched at first load. Stripe\n * refuses `updateEmail` on such a session, so it is shown, not edited. Read\n * once rather than live because the session's email also becomes set the\n * moment THIS form calls `updateEmail` — which must not turn the field the\n * shopper is typing in into read-only text.\n */\n const serverEmail = useRef<string | null | undefined>(undefined)\n if (checkout && serverEmail.current === undefined) {\n serverEmail.current = checkout.email ? String(checkout.email) : null\n }\n const emailLocked = Boolean(serverEmail.current)\n\n const sessionShippingOptions = checkout?.shippingOptions\n const shippingOptions = useMemo(\n () => sessionShippingOptions ?? [],\n [sessionShippingOptions],\n )\n const collectsShipping = shippingOptions.length > 0\n const selectedShippingId = checkout?.shipping?.shippingOption?.id ?? ''\n\n // The hosted page pre-selects the first rate, so the in-page one does too:\n // a session with options and no selection cannot be confirmed, and making\n // the shopper discover that at the pay button is a decline they did not\n // cause. Once per session — a later deselect is not something Stripe does.\n const autoSelected = useRef(false)\n useEffect(() => {\n if (!checkout || !collectsShipping || selectedShippingId) return\n if (autoSelected.current) return\n autoSelected.current = true\n void checkout.updateShippingOption(shippingOptions[0].id)\n }, [checkout, collectsShipping, selectedShippingId, shippingOptions])\n\n const chooseShipping = useCallback(\n async (id: string) => {\n if (!checkout || id === selectedShippingId) return\n setShippingBusy(true)\n try {\n const result = await checkout.updateShippingOption(id)\n if (result?.type === 'error') {\n setMessage(\n String(result.error?.message ?? '') ||\n 'That shipping option could not be selected.',\n )\n }\n } finally {\n setShippingBusy(false)\n }\n },\n [checkout, selectedShippingId],\n )\n\n // Re-price on the address once it is complete and has stopped changing:\n // the Address Element fires per keystroke, and under Stripe Tax every\n // update is a tax calculation. Confirm sends the element's value anyway, so\n // this exists for the TOTAL — the shopper sees tax before they pay.\n const addressTimer = useRef<ReturnType<typeof setTimeout> | null>(null)\n useEffect(\n () => () => {\n if (addressTimer.current) clearTimeout(addressTimer.current)\n },\n [],\n )\n const onShippingAddressChange = useCallback(\n (event: StripeAddressElementChangeEvent) => {\n if (!checkout || !event.complete) return\n if (addressTimer.current) clearTimeout(addressTimer.current)\n const { name, address } = event.value\n addressTimer.current = setTimeout(() => {\n void checkout\n .updateShippingAddress({ name, address })\n .catch(() => undefined)\n }, ADDRESS_SETTLE_MS)\n },\n [checkout],\n )\n\n const commitEmail = useCallback(async (): Promise<boolean> => {\n if (!checkout || emailLocked) return true\n const trimmed = email.trim()\n if (!trimmed) {\n setEmailError('Enter your email for the receipt.')\n return false\n }\n if (checkout.email === trimmed) return true\n const result = await checkout.updateEmail(trimmed)\n if (result?.type === 'error') {\n setEmailError(\n String(result.error?.message ?? '') || 'Enter a valid email address.',\n )\n return false\n }\n setEmailError('')\n return true\n }, [checkout, email, emailLocked])\n\n const handlePay = useCallback(async () => {\n // Guarded rather than merely disabled: a disabled button is a rendering\n // fact, and a keyboard or a slow re-render can still land a second call\n // during a 3DS challenge.\n if (status === 'confirming' || !checkout) return\n setStatus('confirming')\n setMessage('')\n try {\n if (!(await commitEmail())) {\n setStatus('idle')\n return\n }\n const result = await checkout.confirm()\n if (result?.type === 'error') {\n // A decline, an expired card, an incomplete field, a failed 3DS\n // challenge. Recoverable: the form stays mounted with everything the\n // shopper typed still in it.\n setMessage(String(result.error?.message ?? '') || GENERIC_FAILURE)\n setStatus('error')\n return\n }\n // Success does NOT mean fulfilled, and nothing is reported to our server\n // here. Stripe redirects to the `return_url` the session carries; if it\n // has not by the time this resolves, the confirm is still in flight and\n // the button stays disabled rather than inviting a second attempt.\n } catch {\n // A throw is an integration error on Stripe's side of the contract, not\n // something the shopper did; its text is not written for them.\n setMessage(GENERIC_FAILURE)\n setStatus('error')\n }\n }, [checkout, commitEmail, status])\n\n if (checkoutState.type === 'error') {\n // The session could not be loaded — expired, or already completed in\n // another tab. Nothing typed here could be charged, so say so and offer a\n // fresh session or the way back rather than a form that cannot submit.\n return (\n <SessionNotice\n message=\"This checkout could not be loaded. Start again, or return to the store.\"\n onCancel={onCancel}\n onRestart={onRestart}\n />\n )\n }\n\n if (!checkout) {\n return (\n <Box sx={{ display: 'flex', justifyContent: 'center', py: 3 }}>\n <CircularProgress size={28} aria-label=\"Loading checkout\" />\n </Box>\n )\n }\n\n if (checkout.status?.type === 'expired') {\n return (\n <SessionNotice\n message=\"This checkout expired before it was paid. Nothing was charged.\"\n onCancel={onCancel}\n onRestart={onRestart}\n />\n )\n }\n\n if (checkout.status?.type === 'complete') {\n // Paid in another tab, or the return redirect is already under way.\n // Offering a restart here would be offering to charge twice.\n return (\n <Alert severity=\"success\" role=\"status\">\n {'This order is already paid.'}\n </Alert>\n )\n }\n\n const total = checkout.total\n const busy = status === 'confirming'\n const discount = total?.discount?.minorUnitsAmount ?? 0\n const tax = total?.taxExclusive?.minorUnitsAmount ?? 0\n const taxPending = checkout.tax?.status && checkout.tax.status !== 'ready'\n\n return (\n <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>\n {emailLocked ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {`Receipt to ${serverEmail.current}`}\n </Typography>\n ) : (\n <TextField\n type=\"email\"\n label=\"Email\"\n required\n fullWidth\n autoComplete=\"email\"\n value={email}\n onChange={(event) => {\n setEmail(event.target.value)\n if (emailError) setEmailError('')\n }}\n onBlur={() => {\n if (email.trim()) void commitEmail()\n }}\n error={Boolean(emailError)}\n helperText={emailError || 'Your receipt is sent here.'}\n disabled={busy}\n />\n )}\n {collectsShipping ? (\n <Box\n sx={{ display: 'flex', flexDirection: 'column', gap: 1 }}\n data-testid=\"storefront-shipping\"\n >\n <Typography variant=\"subtitle2\">{'Shipping address'}</Typography>\n <ShippingAddressElement onChange={onShippingAddressChange} />\n <Typography variant=\"subtitle2\">{'Shipping method'}</Typography>\n <RadioGroup\n aria-label=\"Shipping method\"\n value={selectedShippingId}\n onChange={(event) => void chooseShipping(event.target.value)}\n >\n {shippingOptions.map((option) => (\n <FormControlLabel\n key={option.id}\n value={option.id}\n disabled={busy || shippingBusy}\n control={<Radio />}\n label={`${option.displayName || 'Shipping'} — ${option.amount}`}\n />\n ))}\n </RadioGroup>\n </Box>\n ) : null}\n <PaymentElement options={wallets ? { wallets } : undefined} />\n {total ? (\n <Box\n sx={{ display: 'flex', flexDirection: 'column', gap: 0.5 }}\n data-testid=\"storefront-checkout-total\"\n >\n <SummaryRow label=\"Subtotal\" value={total.subtotal.amount} />\n {discount ? (\n <SummaryRow label=\"Discount\" value={`−${total.discount.amount}`} />\n ) : null}\n {collectsShipping ? (\n <SummaryRow\n label=\"Shipping\"\n value={selectedShippingId ? total.shippingRate.amount : '—'}\n />\n ) : null}\n {tax || taxPending ? (\n <SummaryRow\n label=\"Tax\"\n value={taxPending ? 'Calculated from your address' : total.taxExclusive.amount}\n />\n ) : null}\n <Divider />\n <SummaryRow label=\"Total\" value={total.total.amount} strong />\n </Box>\n ) : null}\n {message ? (\n // `error` severity is right here and wrong for a lockdown pause — this\n // really is \"your payment did not go through\", which is the one thing\n // a shopper must be told plainly.\n <Alert severity=\"error\" role=\"alert\">\n {message}\n </Alert>\n ) : null}\n <Box sx={{ display: 'flex', gap: 1 }}>\n <Button\n variant=\"contained\"\n onClick={handlePay}\n disabled={busy || shippingBusy}\n fullWidth\n >\n {busy ? 'Paying…' : payLabel || 'Pay now'}\n </Button>\n {onCancel ? (\n <Button variant=\"text\" onClick={onCancel} disabled={busy}>\n {'Cancel'}\n </Button>\n ) : null}\n </Box>\n </Box>\n )\n}\n\nexport function StorefrontPaymentElement({\n clientSecret,\n publishableKey,\n payLabel,\n defaultEmail,\n onCancel,\n onRestart,\n wallets,\n defaultShippingAddress,\n}: StorefrontPaymentElementProps) {\n const stripe = useMemo(() => getStripe(publishableKey), [publishableKey])\n const theme = useTheme()\n // Built once per session: the provider reads its options at mount and\n // ignores later changes, so a memo keyed on the theme as well would only\n // suggest a re-theme that never happens.\n const options = useMemo<StripeCheckoutElementsSdkOptions>(\n () => ({\n clientSecret,\n elementsOptions: {\n appearance: storefrontPaymentAppearance(theme),\n fonts: storefrontPaymentFonts(\n typeof theme.typography?.fontFamily === 'string'\n ? theme.typography.fontFamily\n : undefined,\n ),\n },\n ...(defaultShippingAddress ? { defaultValues: { shippingAddress: defaultShippingAddress } } : {}),\n }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [clientSecret],\n )\n // Belt and braces with the server's own gate, which already refuses native\n // mode without a publishable key: rendering nothing beats rendering an empty\n // white box that looks like a broken payment form.\n if (!clientSecret || !stripe) return null\n return (\n <CheckoutElementsProvider stripe={stripe} options={options}>\n <Box sx={{ py: 2 }} data-testid=\"storefront-payment-element\">\n <PaymentForm\n payLabel={payLabel}\n defaultEmail={defaultEmail}\n onCancel={onCancel}\n onRestart={onRestart}\n wallets={wallets}\n />\n </Box>\n </CheckoutElementsProvider>\n )\n}\n\n/**\n * Re-exported so the old import path still resolves, but the definition now\n * lives in its own module (AGL-2486): a fallback imported FROM the lazily\n * loaded module drags that module into the eager bundle and cancels the\n * `lazy()`. Callers must import it from `./storefront-payment-element-fallback`\n * — importing it from here is exactly the bug, and re-exporting it does not\n * make that safe.\n */\nexport { StorefrontPaymentElementFallback } from './storefront-payment-element-fallback'\n\nexport default StorefrontPaymentElement\n"],"names":["CheckoutElementsProvider","PaymentElement","ShippingAddressElement","useCheckoutElements","loadStripe","Alert","Box","Button","CircularProgress","Divider","FormControlLabel","Radio","RadioGroup","TextField","Typography","useTheme","useCallback","useEffect","useMemo","useRef","useState","storefrontPaymentAppearance","storefrontPaymentFonts","stripePromises","Map","getStripe","publishableKey","promise","get","set","__resetStripePromises","clear","GENERIC_FAILURE","ADDRESS_SETTLE_MS","SummaryRow","label","value","strong","sx","display","justifyContent","gap","variant","color","SessionNotice","message","onCancel","onRestart","flexDirection","severity","role","onClick","PaymentForm","payLabel","defaultEmail","wallets","checkout","total","checkoutState","type","status","setStatus","setMessage","email","setEmail","emailError","setEmailError","shippingBusy","setShippingBusy","serverEmail","undefined","current","String","emailLocked","Boolean","sessionShippingOptions","shippingOptions","collectsShipping","length","selectedShippingId","shipping","shippingOption","id","autoSelected","updateShippingOption","chooseShipping","result","error","addressTimer","clearTimeout","onShippingAddressChange","event","complete","name","address","setTimeout","updateShippingAddress","catch","commitEmail","trimmed","trim","updateEmail","handlePay","confirm","py","size","aria-label","busy","discount","minorUnitsAmount","tax","taxExclusive","taxPending","required","fullWidth","autoComplete","onChange","target","onBlur","helperText","disabled","data-testid","map","option","control","displayName","amount","options","subtotal","shippingRate","StorefrontPaymentElement","clientSecret","defaultShippingAddress","stripe","theme","elementsOptions","appearance","fonts","typography","fontFamily","defaultValues","shippingAddress","StorefrontPaymentElementFallback"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;AAEA,wEAAwE;AACxE,+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IACxE,MAAM4G,QAAQvH;IACd,sEAAsE;IACtE,yEAAyE;IACzE,yCAAyC;IACzC,MAAMgH,UAAU7G,QACd;YAKaoH;eALN;YACLH;YACAI,iBAAiB;gBACfC,YAAYnH,4BAA4BiH;gBACxCG,OAAOnH,uBACL,SAAOgH,oBAAAA,MAAMI,UAAU,qBAAhBJ,kBAAkBK,UAAU,MAAK,WACpCL,MAAMI,UAAU,CAACC,UAAU,GAC3BrE;YAER;WACI8D,yBAAyB;YAAEQ,eAAe;gBAAEC,iBAAiBT;YAAuB;QAAE,IAAI,CAAC;OAEjG,uDAAuD;IACvD;QAACD;KAAa;IAEhB,2EAA2E;IAC3E,6EAA6E;IAC7E,mDAAmD;IACnD,IAAI,CAACA,gBAAgB,CAACE,QAAQ,OAAO;IACrC,qBACE,KAACrI;QAAyBqI,QAAQA;QAAQN,SAASA;kBACjD,cAAA,KAACzH;YAAIgC,IAAI;gBAAEkE,IAAI;YAAE;YAAGiB,eAAY;sBAC9B,cAAA,KAACrE;gBACCC,UAAUA;gBACVC,cAAcA;gBACdR,UAAUA;gBACVC,WAAWA;gBACXQ,SAASA;;;;AAKnB;AAEA;;;;;;;CAOC,GACD,SAASuF,gCAAgC,QAAQ,2CAAuC;AAExF,eAAeZ,yBAAwB"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/components/storefront-payment-element.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n'use client'\n\n// The `/checkout` entry, not the main one: react-stripe-js v6 moved the\n// Checkout Sessions provider, its hook and its own `PaymentElement` there, and\n// the main entry's `PaymentElement` is the Elements one, which does not mount\n// under a Checkout provider.\nimport {\n CheckoutElementsProvider,\n PaymentElement,\n ShippingAddressElement,\n useCheckoutElements,\n} from '@stripe/react-stripe-js/checkout'\n// `/pure` deliberately, not the bare entry (AGL-2486). The bare entry ends\n// with a module-scope `Promise.resolve().then(() => getStripePromise())`,\n// so merely EVALUATING it injects the js.stripe.com/v3 script tag —\n// 249 KB gzipped — on any page that reaches this module, whether or not\n// `loadStripe` is ever called. `/pure` is the same API without that\n// statement, so the script is fetched when we ask for it and not before.\nimport { loadStripe } from '@stripe/stripe-js/pure'\n// The TYPE only, and from the bare entry because `/pure` does not re-export\n// it. `import type` is erased entirely at compile time, so this adds no\n// runtime import and cannot re-introduce the script injection above.\nimport type {\n Stripe,\n StripeAddressElementChangeEvent,\n StripeCheckoutContact,\n StripeCheckoutElementsSdkOptions,\n} from '@stripe/stripe-js'\nimport Alert from '@mui/material/Alert'\nimport Box from '@mui/material/Box'\nimport Button from '@mui/material/Button'\nimport CircularProgress from '@mui/material/CircularProgress'\nimport Divider from '@mui/material/Divider'\nimport FormControlLabel from '@mui/material/FormControlLabel'\nimport Radio from '@mui/material/Radio'\nimport RadioGroup from '@mui/material/RadioGroup'\nimport TextField from '@mui/material/TextField'\nimport Typography from '@mui/material/Typography'\nimport { useTheme } from '@mui/material/styles'\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport {\n storefrontPaymentAppearance,\n storefrontPaymentFonts,\n} from './storefront-payment-appearance'\nimport type { StorefrontCheckoutWallets } from '../model/commerce-payment-methods'\n\n/**\n * The storefront Payment Element (AGL-1944) — the shopper pays on the\n * merchant's own domain instead of being sent to `checkout.stripe.com`.\n *\n * ## THIS COMPONENT DOES NOT FULFIL ANYTHING\n *\n * It has no success callback, and that absence is the design rather than an\n * omission. `libs/plugins/commerce/src/lib/server/billing-webhook.ts` creates\n * the order on `checkout.session.completed` and is the only thing that ever\n * does. An in-page flow makes trusting the browser far more tempting than a\n * redirect does — the form is right there, `confirm()` resolves in hand, and\n * posting \"done, please fulfil\" is one line away — and the browser is the one\n * participant in a payment that can lie about having paid.\n *\n * It is also the participant that can VANISH. A shopper who confirms and\n * closes the tab never runs a callback, so a flow that fulfils here loses the\n * order outright while keeping the money; a shopper who refreshes the return\n * page runs it twice. Neither is reachable from a design with no callback in\n * it. What happens after a successful confirm is a redirect to `return_url`,\n * carrying the `session_id` the server put there — so the page can SHOW the\n * shopper a result by looking the order up, without being TOLD the outcome by\n * this code.\n *\n * ## Declines and 3DS\n *\n * Both were handled for us by the redirect and now have to be handled here.\n *\n * A decline resolves as `{ type: 'error' }` and is rendered inline WITHOUT\n * unmounting the form: the shopper's basket, address and chosen method are all\n * still on screen and they can try another card. That is the whole difference\n * between a recoverable decline and a dead end, and it is why the error state\n * below sits beside the element rather than replacing it.\n *\n * A 3DS challenge is Stripe's own: `confirm()` presents the challenge and, for\n * redirect-based methods, sends the browser to `return_url` and back. Nothing\n * here has to model it — but the button must stay disabled across the whole\n * await, because a second `confirm()` during a challenge is exactly the\n * double-submit the server's idempotency claim exists to survive and there is\n * no reason to make it lean on that.\n *\n * ## Everything the hosted page collected, collected here (AGL-3606)\n *\n * The hosted page asked for an email, a shipping address and a shipping\n * method, and showed a running total. A `ui_mode: 'elements'` session asks\n * for none of that on its own — the Payment Element is only the payment\n * method — so each is mounted here, read off the SESSION rather than off\n * anything the storefront believes:\n *\n * - **Email.** A session created with `customer_email` (the cart's email\n * field) already has one and Stripe refuses `updateEmail` on it, so it is\n * shown read-only. Otherwise a required field, sent with `updateEmail`\n * before `confirm()` — the receipt and the order's customer both come from\n * it, and a sale without one is an order nobody can be told about.\n * - **Shipping.** Only when the session carries shipping options, which the\n * server attaches only when the store ships to the destination. The\n * Shipping Address Element collects the address (and, under Stripe Tax,\n * is where the tax is computed from); the picker lists the session's own\n * options and selects through `updateShippingOption`.\n * - **Tax address without shipping.** Left to the Payment Element, which\n * collects the country and postal code Stripe Tax needs when the session\n * has `automatic_tax` and no shipping address. A Billing Address Element\n * there would make `updateBillingAddress` conflict with it.\n * - **The total.** Rendered from `session.total`, which Stripe recomputes on\n * every address and option change — tax and shipping included — so the\n * number on the button is the number charged.\n * - **The look.** `elementsOptions.appearance` and `fonts` come from the site\n * theme (`storefront-payment-appearance.ts`), so Stripe's frames wear the\n * merchant's palette, radius and typeface.\n *\n * ## Expired and redirect-returned sessions\n *\n * A session that expired, or that cannot be loaded, offers a fresh one through\n * `onRestart` (a NEW attempt key, so the server does not replay the dead\n * session). A redirect-based method that fails comes back to `return_url`\n * with the session still open; `use-checkout-return-notice.ts` reads that on\n * the return page and says nothing was charged.\n */\n\nexport interface StorefrontPaymentElementProps {\n /** Stripe's instruction to the browser. Not a claim that money moved. */\n clientSecret: string\n publishableKey: string\n /**\n * The seller's connected account when the session is a DIRECT charge: the\n * session lives on that account, so Stripe.js has to be opened for it or the\n * client secret will not resolve.\n */\n stripeAccount?: string\n /** Shown on the pay button, so the merchant's own total reads through. */\n payLabel?: string\n /**\n * An email the storefront already knows but did not put on the session\n * (it prefills the field; the shopper can still change it). A session the\n * server created WITH an email shows that one read-only instead.\n */\n defaultEmail?: string\n /** Abandon the in-page form and return to the store. */\n onCancel?: () => void\n /**\n * Open a fresh session after this one expired or could not be loaded. The\n * caller must mint a NEW attempt key first, or the server replays the dead\n * session for the old one.\n */\n onRestart?: () => void\n /**\n * The wallets the merchant hid (AGL-3629). Stripe cannot exclude Apple Pay,\n * Google Pay or Link on the session, so the Payment Element is told instead.\n * Absent means every wallet the device supports shows.\n */\n wallets?: StorefrontCheckoutWallets\n /**\n * An address the shipping fields start with, where the session asks for\n * one: a quote's ship-to (AGL-4094). The shopper can still change it.\n */\n defaultShippingAddress?: StripeCheckoutContact\n}\n\n/**\n * `loadStripe` injects a script tag, so it is memoized per key rather than\n * called per render. Keyed because a page could in principle mount this for\n * two different merchants; in practice it is one, and the map costs nothing.\n */\nconst stripePromises = new Map<string, Promise<Stripe | null>>()\nfunction getStripe(\n publishableKey: string,\n stripeAccount?: string,\n): Promise<Stripe | null> | null {\n if (!publishableKey) return null\n const key = stripeAccount ? `${publishableKey}:${stripeAccount}` : publishableKey\n let promise = stripePromises.get(key)\n if (!promise) {\n promise = stripeAccount\n ? loadStripe(publishableKey, { stripeAccount })\n : loadStripe(publishableKey)\n stripePromises.set(key, promise)\n }\n return promise\n}\n\n/** Test seam: `loadStripe` caches per key across a file's tests otherwise. */\nexport function __resetStripePromises(): void {\n stripePromises.clear()\n}\n\nconst GENERIC_FAILURE = 'That payment could not be completed. Try another card.'\n\n/** How long the address must sit still before the session re-prices on it. */\nconst ADDRESS_SETTLE_MS = 400\n\nfunction SummaryRow({\n label,\n value,\n strong,\n}: {\n label: string\n value: string\n strong?: boolean\n}) {\n return (\n <Box sx={{ display: 'flex', justifyContent: 'space-between', gap: 2 }}>\n <Typography\n variant={strong ? 'subtitle1' : 'body2'}\n color={strong ? 'text.primary' : 'text.secondary'}\n >\n {label}\n </Typography>\n <Typography variant={strong ? 'subtitle1' : 'body2'}>{value}</Typography>\n </Box>\n )\n}\n\nfunction SessionNotice({\n message,\n onCancel,\n onRestart,\n}: {\n message: string\n onCancel?: () => void\n onRestart?: () => void\n}) {\n return (\n <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>\n <Alert severity=\"error\" role=\"alert\">\n {message}\n </Alert>\n <Box sx={{ display: 'flex', gap: 1 }}>\n {onRestart ? (\n <Button variant=\"contained\" onClick={onRestart}>\n {'Start checkout again'}\n </Button>\n ) : null}\n {onCancel ? (\n <Button variant=\"text\" onClick={onCancel}>\n {'Back to the store'}\n </Button>\n ) : null}\n </Box>\n </Box>\n )\n}\n\nfunction PaymentForm({\n payLabel,\n defaultEmail,\n onCancel,\n onRestart,\n wallets,\n}: Pick<\n StorefrontPaymentElementProps,\n 'payLabel' | 'defaultEmail' | 'onCancel' | 'onRestart' | 'wallets'\n>) {\n // A `{ type: 'loading' | 'success' | 'error' }` union since react-stripe-js\n // v6: the session is not usable until Stripe.js has booted against it.\n const checkoutState = useCheckoutElements()\n const checkout =\n checkoutState.type === 'success' ? checkoutState.checkout : null\n const [status, setStatus] = useState<'idle' | 'confirming' | 'error'>('idle')\n const [message, setMessage] = useState('')\n const [email, setEmail] = useState(defaultEmail ?? '')\n const [emailError, setEmailError] = useState('')\n const [shippingBusy, setShippingBusy] = useState(false)\n\n /**\n * The email the SERVER put on the session, latched at first load. Stripe\n * refuses `updateEmail` on such a session, so it is shown, not edited. Read\n * once rather than live because the session's email also becomes set the\n * moment THIS form calls `updateEmail` — which must not turn the field the\n * shopper is typing in into read-only text.\n */\n const serverEmail = useRef<string | null | undefined>(undefined)\n if (checkout && serverEmail.current === undefined) {\n serverEmail.current = checkout.email ? String(checkout.email) : null\n }\n const emailLocked = Boolean(serverEmail.current)\n\n const sessionShippingOptions = checkout?.shippingOptions\n const shippingOptions = useMemo(\n () => sessionShippingOptions ?? [],\n [sessionShippingOptions],\n )\n const collectsShipping = shippingOptions.length > 0\n const selectedShippingId = checkout?.shipping?.shippingOption?.id ?? ''\n\n // The hosted page pre-selects the first rate, so the in-page one does too:\n // a session with options and no selection cannot be confirmed, and making\n // the shopper discover that at the pay button is a decline they did not\n // cause. Once per session — a later deselect is not something Stripe does.\n const autoSelected = useRef(false)\n useEffect(() => {\n if (!checkout || !collectsShipping || selectedShippingId) return\n if (autoSelected.current) return\n autoSelected.current = true\n void checkout.updateShippingOption(shippingOptions[0].id)\n }, [checkout, collectsShipping, selectedShippingId, shippingOptions])\n\n const chooseShipping = useCallback(\n async (id: string) => {\n if (!checkout || id === selectedShippingId) return\n setShippingBusy(true)\n try {\n const result = await checkout.updateShippingOption(id)\n if (result?.type === 'error') {\n setMessage(\n String(result.error?.message ?? '') ||\n 'That shipping option could not be selected.',\n )\n }\n } finally {\n setShippingBusy(false)\n }\n },\n [checkout, selectedShippingId],\n )\n\n // Re-price on the address once it is complete and has stopped changing:\n // the Address Element fires per keystroke, and under Stripe Tax every\n // update is a tax calculation. Confirm sends the element's value anyway, so\n // this exists for the TOTAL — the shopper sees tax before they pay.\n const addressTimer = useRef<ReturnType<typeof setTimeout> | null>(null)\n useEffect(\n () => () => {\n if (addressTimer.current) clearTimeout(addressTimer.current)\n },\n [],\n )\n const onShippingAddressChange = useCallback(\n (event: StripeAddressElementChangeEvent) => {\n if (!checkout || !event.complete) return\n if (addressTimer.current) clearTimeout(addressTimer.current)\n const { name, address } = event.value\n addressTimer.current = setTimeout(() => {\n void checkout\n .updateShippingAddress({ name, address })\n .catch(() => undefined)\n }, ADDRESS_SETTLE_MS)\n },\n [checkout],\n )\n\n const commitEmail = useCallback(async (): Promise<boolean> => {\n if (!checkout || emailLocked) return true\n const trimmed = email.trim()\n if (!trimmed) {\n setEmailError('Enter your email for the receipt.')\n return false\n }\n if (checkout.email === trimmed) return true\n const result = await checkout.updateEmail(trimmed)\n if (result?.type === 'error') {\n setEmailError(\n String(result.error?.message ?? '') || 'Enter a valid email address.',\n )\n return false\n }\n setEmailError('')\n return true\n }, [checkout, email, emailLocked])\n\n const handlePay = useCallback(async () => {\n // Guarded rather than merely disabled: a disabled button is a rendering\n // fact, and a keyboard or a slow re-render can still land a second call\n // during a 3DS challenge.\n if (status === 'confirming' || !checkout) return\n setStatus('confirming')\n setMessage('')\n try {\n if (!(await commitEmail())) {\n setStatus('idle')\n return\n }\n const result = await checkout.confirm()\n if (result?.type === 'error') {\n // A decline, an expired card, an incomplete field, a failed 3DS\n // challenge. Recoverable: the form stays mounted with everything the\n // shopper typed still in it.\n setMessage(String(result.error?.message ?? '') || GENERIC_FAILURE)\n setStatus('error')\n return\n }\n // Success does NOT mean fulfilled, and nothing is reported to our server\n // here. Stripe redirects to the `return_url` the session carries; if it\n // has not by the time this resolves, the confirm is still in flight and\n // the button stays disabled rather than inviting a second attempt.\n } catch {\n // A throw is an integration error on Stripe's side of the contract, not\n // something the shopper did; its text is not written for them.\n setMessage(GENERIC_FAILURE)\n setStatus('error')\n }\n }, [checkout, commitEmail, status])\n\n if (checkoutState.type === 'error') {\n // The session could not be loaded — expired, or already completed in\n // another tab. Nothing typed here could be charged, so say so and offer a\n // fresh session or the way back rather than a form that cannot submit.\n return (\n <SessionNotice\n message=\"This checkout could not be loaded. Start again, or return to the store.\"\n onCancel={onCancel}\n onRestart={onRestart}\n />\n )\n }\n\n if (!checkout) {\n return (\n <Box sx={{ display: 'flex', justifyContent: 'center', py: 3 }}>\n <CircularProgress size={28} aria-label=\"Loading checkout\" />\n </Box>\n )\n }\n\n if (checkout.status?.type === 'expired') {\n return (\n <SessionNotice\n message=\"This checkout expired before it was paid. Nothing was charged.\"\n onCancel={onCancel}\n onRestart={onRestart}\n />\n )\n }\n\n if (checkout.status?.type === 'complete') {\n // Paid in another tab, or the return redirect is already under way.\n // Offering a restart here would be offering to charge twice.\n return (\n <Alert severity=\"success\" role=\"status\">\n {'This order is already paid.'}\n </Alert>\n )\n }\n\n const total = checkout.total\n const busy = status === 'confirming'\n const discount = total?.discount?.minorUnitsAmount ?? 0\n const tax = total?.taxExclusive?.minorUnitsAmount ?? 0\n const taxPending = checkout.tax?.status && checkout.tax.status !== 'ready'\n\n return (\n <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>\n {emailLocked ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {`Receipt to ${serverEmail.current}`}\n </Typography>\n ) : (\n <TextField\n type=\"email\"\n label=\"Email\"\n required\n fullWidth\n autoComplete=\"email\"\n value={email}\n onChange={(event) => {\n setEmail(event.target.value)\n if (emailError) setEmailError('')\n }}\n onBlur={() => {\n if (email.trim()) void commitEmail()\n }}\n error={Boolean(emailError)}\n helperText={emailError || 'Your receipt is sent here.'}\n disabled={busy}\n />\n )}\n {collectsShipping ? (\n <Box\n sx={{ display: 'flex', flexDirection: 'column', gap: 1 }}\n data-testid=\"storefront-shipping\"\n >\n <Typography variant=\"subtitle2\">{'Shipping address'}</Typography>\n <ShippingAddressElement onChange={onShippingAddressChange} />\n <Typography variant=\"subtitle2\">{'Shipping method'}</Typography>\n <RadioGroup\n aria-label=\"Shipping method\"\n value={selectedShippingId}\n onChange={(event) => void chooseShipping(event.target.value)}\n >\n {shippingOptions.map((option) => (\n <FormControlLabel\n key={option.id}\n value={option.id}\n disabled={busy || shippingBusy}\n control={<Radio />}\n label={`${option.displayName || 'Shipping'} — ${option.amount}`}\n />\n ))}\n </RadioGroup>\n </Box>\n ) : null}\n <PaymentElement options={wallets ? { wallets } : undefined} />\n {total ? (\n <Box\n sx={{ display: 'flex', flexDirection: 'column', gap: 0.5 }}\n data-testid=\"storefront-checkout-total\"\n >\n <SummaryRow label=\"Subtotal\" value={total.subtotal.amount} />\n {discount ? (\n <SummaryRow label=\"Discount\" value={`−${total.discount.amount}`} />\n ) : null}\n {collectsShipping ? (\n <SummaryRow\n label=\"Shipping\"\n value={selectedShippingId ? total.shippingRate.amount : '—'}\n />\n ) : null}\n {tax || taxPending ? (\n <SummaryRow\n label=\"Tax\"\n value={taxPending ? 'Calculated from your address' : total.taxExclusive.amount}\n />\n ) : null}\n <Divider />\n <SummaryRow label=\"Total\" value={total.total.amount} strong />\n </Box>\n ) : null}\n {message ? (\n // `error` severity is right here and wrong for a lockdown pause — this\n // really is \"your payment did not go through\", which is the one thing\n // a shopper must be told plainly.\n <Alert severity=\"error\" role=\"alert\">\n {message}\n </Alert>\n ) : null}\n <Box sx={{ display: 'flex', gap: 1 }}>\n <Button\n variant=\"contained\"\n onClick={handlePay}\n disabled={busy || shippingBusy}\n fullWidth\n >\n {busy ? 'Paying…' : payLabel || 'Pay now'}\n </Button>\n {onCancel ? (\n <Button variant=\"text\" onClick={onCancel} disabled={busy}>\n {'Cancel'}\n </Button>\n ) : null}\n </Box>\n </Box>\n )\n}\n\nexport function StorefrontPaymentElement({\n clientSecret,\n publishableKey,\n stripeAccount,\n payLabel,\n defaultEmail,\n onCancel,\n onRestart,\n wallets,\n defaultShippingAddress,\n}: StorefrontPaymentElementProps) {\n const stripe = useMemo(\n () => getStripe(publishableKey, stripeAccount),\n [publishableKey, stripeAccount],\n )\n const theme = useTheme()\n // Built once per session: the provider reads its options at mount and\n // ignores later changes, so a memo keyed on the theme as well would only\n // suggest a re-theme that never happens.\n const options = useMemo<StripeCheckoutElementsSdkOptions>(\n () => ({\n clientSecret,\n elementsOptions: {\n appearance: storefrontPaymentAppearance(theme),\n fonts: storefrontPaymentFonts(\n typeof theme.typography?.fontFamily === 'string'\n ? theme.typography.fontFamily\n : undefined,\n ),\n },\n ...(defaultShippingAddress ? { defaultValues: { shippingAddress: defaultShippingAddress } } : {}),\n }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [clientSecret],\n )\n // Belt and braces with the server's own gate, which already refuses native\n // mode without a publishable key: rendering nothing beats rendering an empty\n // white box that looks like a broken payment form.\n if (!clientSecret || !stripe) return null\n return (\n <CheckoutElementsProvider stripe={stripe} options={options}>\n <Box sx={{ py: 2 }} data-testid=\"storefront-payment-element\">\n <PaymentForm\n payLabel={payLabel}\n defaultEmail={defaultEmail}\n onCancel={onCancel}\n onRestart={onRestart}\n wallets={wallets}\n />\n </Box>\n </CheckoutElementsProvider>\n )\n}\n\n/**\n * Re-exported so the old import path still resolves, but the definition now\n * lives in its own module (AGL-2486): a fallback imported FROM the lazily\n * loaded module drags that module into the eager bundle and cancels the\n * `lazy()`. Callers must import it from `./storefront-payment-element-fallback`\n * — importing it from here is exactly the bug, and re-exporting it does not\n * make that safe.\n */\nexport { StorefrontPaymentElementFallback } from './storefront-payment-element-fallback'\n\nexport default StorefrontPaymentElement\n"],"names":["CheckoutElementsProvider","PaymentElement","ShippingAddressElement","useCheckoutElements","loadStripe","Alert","Box","Button","CircularProgress","Divider","FormControlLabel","Radio","RadioGroup","TextField","Typography","useTheme","useCallback","useEffect","useMemo","useRef","useState","storefrontPaymentAppearance","storefrontPaymentFonts","stripePromises","Map","getStripe","publishableKey","stripeAccount","key","promise","get","set","__resetStripePromises","clear","GENERIC_FAILURE","ADDRESS_SETTLE_MS","SummaryRow","label","value","strong","sx","display","justifyContent","gap","variant","color","SessionNotice","message","onCancel","onRestart","flexDirection","severity","role","onClick","PaymentForm","payLabel","defaultEmail","wallets","checkout","total","checkoutState","type","status","setStatus","setMessage","email","setEmail","emailError","setEmailError","shippingBusy","setShippingBusy","serverEmail","undefined","current","String","emailLocked","Boolean","sessionShippingOptions","shippingOptions","collectsShipping","length","selectedShippingId","shipping","shippingOption","id","autoSelected","updateShippingOption","chooseShipping","result","error","addressTimer","clearTimeout","onShippingAddressChange","event","complete","name","address","setTimeout","updateShippingAddress","catch","commitEmail","trimmed","trim","updateEmail","handlePay","confirm","py","size","aria-label","busy","discount","minorUnitsAmount","tax","taxExclusive","taxPending","required","fullWidth","autoComplete","onChange","target","onBlur","helperText","disabled","data-testid","map","option","control","displayName","amount","options","subtotal","shippingRate","StorefrontPaymentElement","clientSecret","defaultShippingAddress","stripe","theme","elementsOptions","appearance","fonts","typography","fontFamily","defaultValues","shippingAddress","StorefrontPaymentElementFallback"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;AAEA,wEAAwE;AACxE,+EAA+E;AAC/E,8EAA8E;AAC9E,6BAA6B;AAC7B,SACEA,wBAAwB,EACxBC,cAAc,EACdC,sBAAsB,EACtBC,mBAAmB,QACd,mCAAkC;AACzC,2EAA2E;AAC3E,0EAA0E;AAC1E,oEAAoE;AACpE,wEAAwE;AACxE,oEAAoE;AACpE,yEAAyE;AACzE,SAASC,UAAU,QAAQ,yBAAwB;AAUnD,OAAOC,WAAW,sBAAqB;AACvC,OAAOC,SAAS,oBAAmB;AACnC,OAAOC,YAAY,uBAAsB;AACzC,OAAOC,sBAAsB,iCAAgC;AAC7D,OAAOC,aAAa,wBAAuB;AAC3C,OAAOC,sBAAsB,iCAAgC;AAC7D,OAAOC,WAAW,sBAAqB;AACvC,OAAOC,gBAAgB,2BAA0B;AACjD,OAAOC,eAAe,0BAAyB;AAC/C,OAAOC,gBAAgB,2BAA0B;AACjD,SAASC,QAAQ,QAAQ,uBAAsB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;IAC3E,6EAA6E;IAC7E,mDAAmD;IACnD,IAAI,CAACA,gBAAgB,CAACE,QAAQ,OAAO;IACrC,qBACE,KAACvI;QAAyBuI,QAAQA;QAAQN,SAASA;kBACjD,cAAA,KAAC3H;YAAIkC,IAAI;gBAAEkE,IAAI;YAAE;YAAGiB,eAAY;sBAC9B,cAAA,KAACrE;gBACCC,UAAUA;gBACVC,cAAcA;gBACdR,UAAUA;gBACVC,WAAWA;gBACXQ,SAASA;;;;AAKnB;AAEA;;;;;;;CAOC,GACD,SAASuF,gCAAgC,QAAQ,2CAAuC;AAExF,eAAeZ,yBAAwB"}
@@ -59,7 +59,7 @@ export declare const COMMERCE_POS_HARDWARE_REFUND_FAILED: OperatorAlertDefinitio
59
59
  */
60
60
  export declare const COMMERCE_POS_HARDWARE_RETURN_REQUESTED: OperatorAlertDefinition;
61
61
  /**
62
- * A workspace's monthly 4G charge for its Stripe Reader S710s did not
62
+ * A workspace's monthly 4G charge for its S710 readers did not
63
63
  * collect (AGL-4038): the card declined or asked for authentication (the
64
64
  * invoice is left open on their Billing page, which nothing retries), or
65
65
  * the workspace has no Stripe customer to bill. Stripe still bills the