@funnelsgrove/payments 0.67.0 → 0.69.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +58 -19
  2. package/dist/components/CheckoutErrorOverlay.d.ts +37 -0
  3. package/dist/components/CheckoutErrorOverlay.js +67 -0
  4. package/dist/generated/package-version.d.ts +1 -1
  5. package/dist/generated/package-version.js +1 -1
  6. package/dist/index.d.ts +1 -0
  7. package/dist/providers/solidgate/components/SolidgateCheckoutDialog.js +5 -1
  8. package/dist/providers/solidgate/services/solidgateDeclineMessage.js +1 -1
  9. package/dist/providers/stripe/components/SharedStripeCheckoutV2Dialog.d.ts +13 -4
  10. package/dist/providers/stripe/components/SharedStripeCheckoutV2Dialog.js +93 -88
  11. package/dist/providers/stripe/components/StripeCheckoutDialog.d.ts +31 -0
  12. package/dist/providers/stripe/components/StripeCheckoutDialog.js +179 -0
  13. package/dist/providers/stripe/components/StripeWalletFirstCheckout.d.ts +91 -2
  14. package/dist/providers/stripe/components/StripeWalletFirstCheckout.js +361 -111
  15. package/dist/providers/stripe/components/StripeWalletFirstCheckout.options.d.ts +24 -0
  16. package/dist/providers/stripe/components/StripeWalletFirstCheckout.options.js +17 -0
  17. package/dist/providers/stripe/components/StripeWalletFirstCheckout.styles.d.ts +3 -1
  18. package/dist/providers/stripe/components/StripeWalletFirstCheckout.styles.js +24 -9
  19. package/dist/providers/stripe/components/WalletButton.d.ts +22 -0
  20. package/dist/providers/stripe/components/WalletButton.js +52 -0
  21. package/dist/providers/stripe/components/checkout-v2.content.d.ts +3 -0
  22. package/dist/providers/stripe/components/index.d.ts +2 -0
  23. package/dist/providers/stripe/components/index.js +2 -0
  24. package/dist/providers/stripe/components/useCheckoutEmail.internal.d.ts +3 -1
  25. package/dist/providers/stripe/components/useCheckoutEmail.internal.js +8 -3
  26. package/dist/providers/stripe/hooks/useStripeOneTimeCheckoutSession.d.ts +10 -3
  27. package/dist/providers/stripe/hooks/useStripeOneTimeCheckoutSession.js +18 -8
  28. package/dist/providers/stripe/hooks/useStripeSubscriptionCheckoutSession.d.ts +10 -3
  29. package/dist/providers/stripe/hooks/useStripeSubscriptionCheckoutSession.js +19 -8
  30. package/dist/providers/stripe/services/checkout/requests.d.ts +8 -4
  31. package/dist/providers/stripe/services/checkout/requests.js +6 -6
  32. package/dist/providers/stripe/services/checkout/types.d.ts +9 -0
  33. package/dist/providers/stripe/services/checkoutCompletionAnalytics.service.d.ts +1 -1
  34. package/package.json +5 -5
  35. package/dist/providers/stripe/components/SharedCheckoutPaymentMethods.internal.d.ts +0 -18
  36. package/dist/providers/stripe/components/SharedCheckoutPaymentMethods.internal.js +0 -15
  37. package/dist/providers/stripe/components/SharedStripeCheckoutV2Form.internal.d.ts +0 -7
  38. package/dist/providers/stripe/components/SharedStripeCheckoutV2Form.internal.js +0 -328
  39. package/dist/providers/stripe/components/SharedStripeCheckoutV2Summary.internal.d.ts +0 -7
  40. package/dist/providers/stripe/components/SharedStripeCheckoutV2Summary.internal.js +0 -19
@@ -1,146 +1,366 @@
1
1
  'use client';
2
- import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
2
+ var __rest = (this && this.__rest) || function (s, e) {
3
+ var t = {};
4
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
5
+ t[p] = s[p];
6
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
7
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
8
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
9
+ t[p[i]] = s[p[i]];
10
+ }
11
+ return t;
12
+ };
13
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
14
  /**
4
- * Wallet-first inline Stripe checkout (Checkout Sessions).
15
+ * Wallet-first inline Stripe checkout (Checkout Sessions), one block per
16
+ * payment method (CHECKOUT-BR-010).
5
17
  *
6
18
  * One platform wallet is the first, preselected method: Google Pay on Android,
7
19
  * Apple Pay everywhere else, shown with Stripe's own wallet button. Card
8
- * payment is always the second method. The whole layout renders immediately,
9
- * even before the checkout session exists; the wallet slot holds a progress
10
- * bar at the exact button height until Stripe's button replaces it, so nothing
11
- * moves. Where the wallet cannot pay, the same slot explains that. The card
12
- * form has no email or terms text: the session carries the email. Stripe asks
13
- * for the postal code only for card countries that use it (US, CA, UK).
14
- * `paymentElementOptions` overrides these card form defaults.
15
- * `initialMethod: 'card'` opens the card form first, e.g. for a bottom-of-page
16
- * "complete your order" block; the wallet stays one tap away.
20
+ * payment is the last method. Between them, every other method the offer
21
+ * supports (Pix, Klarna, …) forms one block, or its own block when `methods`
22
+ * names it; a native PayPal checkout passed as `paypalCheckout` follows the
23
+ * wallet. The wallet and the card share the caller's Checkout Session; every
24
+ * other Stripe block owns a Checkout Session restricted to its methods, created
25
+ * when the block is selected. The whole layout renders immediately, even before
26
+ * the checkout session exists; the wallet slot holds a progress bar at the
27
+ * exact button height until Stripe's button replaces it, so nothing moves.
28
+ * Where the wallet cannot pay, the same slot explains that (or the block hides
29
+ * with `hideUnavailableWallet`). The card form has no email or terms text: the
30
+ * session carries the email, unless `email` asks the visitor for it. Stripe
31
+ * asks for the postal code only for card countries that use it (US, CA, UK).
32
+ * `paymentElementOptions` overrides these card form defaults. `initialMethod`
33
+ * opens another block first, e.g. `'card'` for a bottom-of-page "complete your
34
+ * order" block; the wallet stays one tap away. A failed payment lies over the
35
+ * blocks (CheckoutErrorOverlay), so nothing below moves.
17
36
  *
18
- * The caller owns the subscription Checkout Session (`clientSecret`), the copy
19
- * and what happens after `onSuccess`.
37
+ * The caller owns the card Checkout Session (`clientSecret`, created with
38
+ * `paymentMethodTypes: ['card']` so its form never shows another method), the
39
+ * copy and what happens after `onSuccess`.
20
40
  */
21
41
  import { useEffect, useMemo, useRef, useState } from 'react';
22
42
  import { CheckoutProvider, PaymentElement, useCheckout } from '@stripe/react-stripe-js/checkout';
23
43
  import { completePaywallCheckout } from '@funnelsgrove/runtime';
24
- import { StripeCheckoutExpressCheckoutButton } from './StripeCheckoutExpressCheckoutButton.js';
25
44
  import { ApplePayMark, CardBrandMarks, GooglePayMark, MethodCard, usePlatformWallet } from '../../../components/walletFirstParts.js';
26
45
  import { stripeWalletFirstCheckoutStyles } from './StripeWalletFirstCheckout.styles.js';
46
+ import { CheckoutErrorOverlay } from '../../../components/CheckoutErrorOverlay.js';
47
+ import { PaymentBrandMark } from './CheckoutBrandAssets.js';
48
+ import { WalletButton } from './WalletButton.js';
49
+ import { buildWalletFirstCheckoutOptions } from './StripeWalletFirstCheckout.options.js';
50
+ import { getUnsupportedCheckoutCountryMessage, normalizeSupportedCheckoutCountries } from './checkoutCountries.js';
51
+ import { useCheckoutEmail } from './useCheckoutEmail.internal.js';
52
+ import { isCheckoutEmailError, isValidCheckoutEmail } from '../../../services/checkoutEmail.js';
53
+ import { resolveCheckoutReturnUrl } from '../services/checkout/checkoutReturnUrl.js';
54
+ import { getCheckoutSessionPaymentMethodTypes } from '../services/checkoutSessionPaymentMethods.js';
27
55
  import { queueStripeSubscriptionCheckoutStarted, trackPaidStripeSubscriptionCheckoutCompleted, trackStripeCheckoutShown, trackStripeSubscriptionPaymentInfoSubmitted, } from '../services/checkoutCompletionAnalytics.service.js';
28
56
  import { trackCheckoutFailureShown } from '../../../services/checkoutObservability.service.js';
29
57
  import { useCheckoutShownOnce } from '../hooks/useCheckoutShownOnce.js';
58
+ import { isInactiveCheckoutSessionError, useStripeSubscriptionCheckoutSession, } from '../hooks/useStripeSubscriptionCheckoutSession.js';
30
59
  import { isStripeCheckoutAlreadyPaidError, normalizeStripeCheckoutError } from '../services/stripeCheckoutError.js';
31
- const appearance = {
32
- labels: 'above',
33
- variables: {
34
- borderRadius: '12px',
35
- colorBackground: '#fff',
36
- colorText: '#303136',
37
- colorTextPlaceholder: '#8c909a',
38
- spacingUnit: '4px',
39
- },
40
- };
60
+ const DEFAULT_METHODS = ['wallet', 'other', 'card'];
61
+ const RESERVED_METHODS = new Set(['wallet', 'card', 'other', 'paypal']);
62
+ /** Only methods the offer supports become blocks; unnamed extras share the `'other'` block. */
63
+ function resolveMethodBlocks(methods, availablePaymentMethodTypes, canCreateSessions, hasPayPal) {
64
+ const extras = (availablePaymentMethodTypes !== null && availablePaymentMethodTypes !== void 0 ? availablePaymentMethodTypes : []).filter((type) => type !== 'card');
65
+ const named = methods.filter((method) => !RESERVED_METHODS.has(method));
66
+ const blocks = [];
67
+ for (const method of new Set(methods)) {
68
+ if (method === 'wallet') {
69
+ blocks.push({ id: 'wallet', kind: 'wallet' });
70
+ }
71
+ else if (method === 'card') {
72
+ blocks.push({ id: 'card', kind: 'card' });
73
+ }
74
+ else if (method === 'paypal') {
75
+ if (hasPayPal)
76
+ blocks.push({ id: 'paypal', kind: 'paypal' });
77
+ }
78
+ else if (!canCreateSessions) {
79
+ continue;
80
+ }
81
+ else if (method === 'other') {
82
+ const types = extras.filter((type) => !named.includes(type));
83
+ if (types.length)
84
+ blocks.push({ id: 'other', kind: 'session', types });
85
+ }
86
+ else if (extras.includes(method)) {
87
+ blocks.push({ id: method, kind: 'session', types: [method] });
88
+ }
89
+ }
90
+ if (hasPayPal && !methods.includes('paypal')) {
91
+ blocks.splice(blocks.findIndex((block) => block.kind === 'wallet') + 1, 0, { id: 'paypal', kind: 'paypal' });
92
+ }
93
+ return blocks;
94
+ }
95
+ const methodLabel = (type, copy) => { var _a, _b; return (_b = (_a = copy.methodLabels) === null || _a === void 0 ? void 0 : _a[type]) !== null && _b !== void 0 ? _b : type.replace(/_/g, ' ').replace(/^./, (first) => first.toUpperCase()); };
41
96
  export function StripeWalletFirstCheckout(props) {
42
- const { buttonColor, checkoutAnalytics, checkoutSessionId, clientSecret, copy, initialMethod = 'wallet', stripePromise, themeColor } = props;
97
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;
98
+ const { availablePaymentMethodTypes, buttonColor, checkoutAnalytics, checkoutSessionId, clientSecret, copy, initialMethod = 'wallet', methods = DEFAULT_METHODS, methodSessionInput, onError, onSuccess, stripePromise, themeColor, paypalPending = false, } = props;
43
99
  const wallet = usePlatformWallet();
100
+ const [error, setError] = useState(null);
101
+ const [failure, setFailure] = useState(null);
102
+ const email = useCheckoutEmail({
103
+ customerEmail: props.customerEmail,
104
+ allowEmailEditing: Boolean((_a = props.email) === null || _a === void 0 ? void 0 : _a.editable),
105
+ customerEmailInvalidMessage: (_c = (_b = props.email) === null || _b === void 0 ? void 0 : _b.invalidMessage) !== null && _c !== void 0 ? _c : 'Enter a valid email address.',
106
+ onCustomerEmailCommit: (_d = props.email) === null || _d === void 0 ? void 0 : _d.onCommit,
107
+ onCustomerEmailChange: (_e = props.email) === null || _e === void 0 ? void 0 : _e.onChange,
108
+ // The visitor fixes the email in its field, so the message stays next to the form.
109
+ onError: (message) => status.showError(message, { blockId: 'card', checkoutSessionId, failureStage: 'card_form' }, validationFailure(message)),
110
+ sessionKey: clientSecret,
111
+ });
112
+ const emailController = props.email ? Object.assign(Object.assign({}, email), { field: props.email }) : null;
113
+ // Wallets confirm with the session's email, so they show only while the visitor keeps it.
114
+ const walletEmailReady = !emailController || (!email.emailSessionChanged && isValidCheckoutEmail(email.initialCustomerEmail)
115
+ && email.rejectedEmail === null && email.resolvedCustomerEmail === email.initialCustomerEmail);
116
+ const [walletAvailable, setWalletAvailable] = useState((_f = props.initialWalletAvailable) !== null && _f !== void 0 ? _f : null);
117
+ // A wallet this browser cannot use stays mounted but hidden, so a later availability report brings it back.
118
+ const walletHidden = Boolean(props.hideUnavailableWallet && walletAvailable === false);
119
+ const supportedCountriesKey = (_h = (_g = props.supportedCountries) === null || _g === void 0 ? void 0 : _g.join(',')) !== null && _h !== void 0 ? _h : '';
120
+ const countries = useMemo(() => {
121
+ const supported = normalizeSupportedCheckoutCountries(supportedCountriesKey.split(','));
122
+ return { supported, fixed: supported.length === 1 ? supported[0] : null, message: props.unsupportedCountryMessage };
123
+ }, [supportedCountriesKey, props.unsupportedCountryMessage]);
124
+ // A card session that offers other methods itself shows them in its form; other blocks would repeat them.
125
+ const cardSessionCardsOnly = getCheckoutSessionPaymentMethodTypes(checkoutSessionId).every((type) => type === 'card');
126
+ const canCreateSessions = Boolean(methodSessionInput) && cardSessionCardsOnly;
127
+ const hasPayPal = Boolean(props.paypalCheckout);
128
+ // Keyed by content so inline arrays from the caller keep each block's `types` identity stable.
129
+ const methodsKey = methods.join(',');
130
+ const availableKey = (_j = availablePaymentMethodTypes === null || availablePaymentMethodTypes === void 0 ? void 0 : availablePaymentMethodTypes.join(',')) !== null && _j !== void 0 ? _j : null;
131
+ const allBlocks = useMemo(() => resolveMethodBlocks(methodsKey.split(',').filter(Boolean), availableKey === null ? null : availableKey.split(',').filter(Boolean), canCreateSessions, hasPayPal), [methodsKey, availableKey, canCreateSessions, hasPayPal]);
132
+ const renderedBlocks = walletEmailReady ? allBlocks : allBlocks.filter((block) => block.kind !== 'wallet');
133
+ const blocks = walletHidden ? renderedBlocks.filter((block) => block.kind !== 'wallet') : renderedBlocks;
44
134
  const [selected, setSelected] = useState(initialMethod);
45
- // A card form that is open on mount has not been opened by the visitor yet.
46
- const [cardEngaged, setCardEngaged] = useState(initialMethod !== 'card');
47
- const select = (method) => {
48
- if (method === 'card')
49
- setCardEngaged(true);
50
- setSelected(method);
135
+ // A method inside the other block selects that block; a hidden block gives way to the first one.
136
+ const activeId = paypalPending && hasPayPal ? 'paypal' : (_m = ((_l = (_k = blocks.find((block) => block.id === selected)) !== null && _k !== void 0 ? _k : blocks.find((block) => block.kind === 'session' && block.types.includes(selected))) !== null && _l !== void 0 ? _l : blocks[0])) === null || _m === void 0 ? void 0 : _m.id;
137
+ // A form that is open on mount has not been opened by the visitor yet.
138
+ const [engaged, setEngaged] = useState(initialMethod === 'wallet');
139
+ const select = (id) => {
140
+ if (id !== 'wallet')
141
+ setEngaged(true);
142
+ setSelected(id);
143
+ };
144
+ const engage = () => setEngaged(true);
145
+ const [busy, setBusy] = useState(false);
146
+ const [confirmed, setConfirmed] = useState(false);
147
+ const [confirmedSessionId, setConfirmedSessionId] = useState(null);
148
+ const [completed, setCompleted] = useState(false);
149
+ // A replaced card session starts clean, as its remounted form did before.
150
+ const [seenClientSecret, setSeenClientSecret] = useState(clientSecret);
151
+ if (seenClientSecret !== clientSecret) {
152
+ setSeenClientSecret(clientSecret);
153
+ setError(null);
154
+ setFailure(null);
155
+ setBusy(false);
156
+ setConfirmed(false);
157
+ setConfirmedSessionId(null);
158
+ setCompleted(false);
159
+ }
160
+ const paymentStatus = completed ? copy.paymentConfirmed : confirmed ? copy.verifyingPayment : null;
161
+ const status = {
162
+ busy,
163
+ paymentStatus,
164
+ locked: Boolean(paymentStatus) && !error,
165
+ error,
166
+ setBusy,
167
+ markConfirmed: (confirmedId) => { setConfirmed(true); setConfirmedSessionId(confirmedId); },
168
+ markCompleted: () => setCompleted(true),
169
+ showError: (message, context, details, alreadyTracked = false) => {
170
+ // An expired session is replaced by the caller; Stripe's stale-session message never shows.
171
+ if (message && props.onInactiveCheckoutSession && isInactiveCheckoutSessionError(message)) {
172
+ setError(null);
173
+ setFailure(null);
174
+ props.onInactiveCheckoutSession();
175
+ return;
176
+ }
177
+ const errorDetails = message ? details !== null && details !== void 0 ? details : normalizeStripeCheckoutError(message, undefined, context.paymentMethod) : undefined;
178
+ // Stripe rejected the session's email: the visitor corrects it in the card form.
179
+ if (emailController && message && (isCheckoutEmailError({ code: errorDetails === null || errorDetails === void 0 ? void 0 : errorDetails.providerErrorCode }) || isCheckoutEmailError(message))) {
180
+ email.setRejectedEmail(email.initialCustomerEmail);
181
+ setSelected('card');
182
+ }
183
+ if (message && checkoutAnalytics && !alreadyTracked) {
184
+ trackCheckoutFailureShown(Object.assign({ analytics: checkoutAnalytics, checkoutSessionId: context.checkoutSessionId, errorMessage: message, failureStage: context.failureStage, provider: 'stripe' }, errorDetails));
185
+ }
186
+ setError(message);
187
+ setFailure(message && errorDetails ? { blockId: context.blockId, details: errorDetails } : null);
188
+ if (message)
189
+ onError === null || onError === void 0 ? void 0 : onError(message, errorDetails);
190
+ else
191
+ onError === null || onError === void 0 ? void 0 : onError(message);
192
+ },
193
+ trackSuccess: async (paidCheckoutSessionId, embedded = false) => {
194
+ if (checkoutAnalytics)
195
+ await trackPaidStripeSubscriptionCheckoutCompleted(Object.assign(Object.assign({}, checkoutAnalytics), { checkoutSessionId: paidCheckoutSessionId }));
196
+ if (embedded)
197
+ return false;
198
+ return (await (onSuccess === null || onSuccess === void 0 ? void 0 : onSuccess())) === true;
199
+ },
51
200
  };
52
- const engageCard = () => setCardEngaged(true);
201
+ // Once any block confirmed a payment, no other block may start a second one.
202
+ const disabled = busy || confirmed || paypalPending;
53
203
  const style = { '--wfc-theme': themeColor, '--wfc-button': buttonColor };
54
- const options = useMemo(() => clientSecret ? {
55
- clientSecret,
56
- elementsOptions: { appearance: Object.assign(Object.assign({}, appearance), { variables: Object.assign(Object.assign({}, appearance.variables), { colorPrimary: themeColor }) }) },
57
- } : null, [clientSecret, themeColor]);
204
+ const options = useMemo(() => clientSecret ? buildWalletFirstCheckoutOptions(clientSecret, themeColor, countries.fixed) : null, [clientSecret, themeColor, countries.fixed]);
58
205
  // The whole layout shows on mount, so one mount is one show.
206
+ const checkoutSurface = (_o = props.checkoutSurface) !== null && _o !== void 0 ? _o : 'inline';
59
207
  useCheckoutShownOnce(Boolean(checkoutAnalytics), () => {
60
208
  if (checkoutAnalytics)
61
- trackStripeCheckoutShown(Object.assign(Object.assign({}, checkoutAnalytics), { checkoutSessionId, checkoutSurface: 'inline' }));
209
+ trackStripeCheckoutShown(Object.assign(Object.assign({}, checkoutAnalytics), { checkoutSessionId, checkoutSurface }));
62
210
  });
63
- // Session creation is preparation; the card checkout starts when the visitor opens the card form,
64
- // or, when it opens preselected, on their first input into it.
211
+ const cardPaymentElementOptions = useMemo(() => resolveCardPaymentElementOptions(props.paymentElementOptions, countries.fixed), [props.paymentElementOptions, countries.fixed]);
212
+ const live = Boolean(options && stripePromise);
213
+ const formProps = {
214
+ checkoutAnalytics, copy, countries, customerEmail: props.customerEmail, email: emailController, engaged,
215
+ onEngage: engage, onPaymentInfoSubmitted: props.onPaymentInfoSubmitted, returnUrl: props.returnUrl, status,
216
+ };
217
+ const renderBlock = (block) => {
218
+ var _a, _b;
219
+ const checked = activeId === block.id;
220
+ if (block.kind === 'wallet') {
221
+ const WalletMark = wallet === 'applePay' ? ApplePayMark : GooglePayMark;
222
+ const walletNote = checked ? status.paymentStatus : null;
223
+ return (_jsxs(MethodCard, { checked: checked, disabled: disabled, label: copy.walletLabels[wallet], onSelect: () => select('wallet'), header: _jsx(WalletMark, {}), children: [_jsx("ul", { className: 'wfc-benefits', children: copy.walletBenefits[wallet].map((item) => _jsxs("li", { children: [_jsx(CheckIcon, {}), item] }, item)) }), live ? _jsx("div", { className: 'wfc-wallet-confirm', inert: confirmed || completed, children: _jsx(WalletButton, { amountCents: props.amountCents, beforeConfirm: async () => {
224
+ setBusy(true);
225
+ if (!emailController)
226
+ return props.customerEmail || null;
227
+ const confirmedEmail = await email.ensureCustomerEmail();
228
+ if (!confirmedEmail)
229
+ setBusy(false);
230
+ return confirmedEmail;
231
+ }, checkoutAnalytics: checkoutAnalytics, checkoutSessionId: checkoutSessionId, customerEmail: emailController ? email.resolvedCustomerEmail : props.customerEmail, customerName: props.customerName, initialAvailable: props.initialWalletAvailable, onAvailabilityChange: setWalletAvailable, onCancel: () => { var _a; setBusy(false); (_a = props.onCancel) === null || _a === void 0 ? void 0 : _a.call(props); }, onEmbeddedComplete: () => setCompleted(true), onError: (message, details) => { setBusy(false); status.showError(message, { blockId: 'wallet', checkoutSessionId, failureStage: 'wallet', paymentMethod: wallet }, details, true); }, onPaymentInfoSubmitted: props.onPaymentInfoSubmitted, onPaymentRejected: () => { setBusy(false); select('card'); }, onSuccess: async () => { await status.trackSuccess(checkoutSessionId); }, onVerificationPending: () => status.markConfirmed(checkoutSessionId), processingLabel: copy.processingLabel, returnUrl: props.returnUrl, summaryLabel: props.summaryLabel, supportedCountries: countries.supported, unavailableNote: copy.walletUnavailableNote.replace('{wallet}', copy.walletLabels[wallet]), unsupportedCountryMessage: countries.message, wallet: wallet }) }) : _jsx("div", { className: 'wfc-wallet-slot', children: _jsx("span", { className: 'wfc-progress', role: 'status', "aria-label": copy.processingLabel }) }), _jsx("p", { className: walletNote ? 'wfc-secure is-status' : 'wfc-secure', role: walletNote ? 'status' : undefined, children: walletNote || copy.secureNote })] }, 'wallet'));
232
+ }
233
+ if (block.kind === 'card') {
234
+ const brands = ((_a = props.cardBrandLabels) === null || _a === void 0 ? void 0 : _a.length)
235
+ ? _jsx("span", { className: 'wfc-card-marks', "aria-hidden": 'true', children: props.cardBrandLabels.map((label) => _jsx(PaymentBrandMark, { label: label, className: 'wfc-brand' }, label)) })
236
+ : _jsx(CardBrandMarks, {});
237
+ return (_jsx(MethodCard, { checked: checked, disabled: disabled, label: copy.cardLabel, onSelect: () => select('card'), header: brands, children: live
238
+ ? _jsx(MethodForm, Object.assign({}, formProps, { blockId: 'card', checkoutSessionId: checkoutSessionId, failureStage: 'card_form', paymentElementOptions: cardPaymentElementOptions, paymentMethod: 'card', selected: checked, startSource: 'card_form_open' }))
239
+ : _jsx(FormPlaceholder, {}) }, 'card'));
240
+ }
241
+ if (block.kind === 'paypal') {
242
+ const label = (_b = props.paypalLabel) !== null && _b !== void 0 ? _b : 'PayPal';
243
+ return (_jsx(MethodCard, { checked: checked, disabled: disabled, label: label, onSelect: () => select('paypal'), header: _jsx(PaymentBrandMark, { label: 'PayPal', className: 'wfc-brand wfc-brand--paypal' }), children: _jsx("div", { className: 'wfc-paypal', inert: busy || confirmed, children: checked ? props.paypalCheckout : null }) }, 'paypal'));
244
+ }
245
+ return methodSessionInput ? (_jsx(SessionMethodBlock, Object.assign({}, formProps, { block: block, checked: checked, disabled: disabled, onSelect: () => select(block.id), sessionInput: methodSessionInput, themeColor: themeColor }), block.id)) : null;
246
+ };
247
+ // A confirmed payment that failed to verify is checked again, never paid again.
248
+ const checkPaymentStatus = async () => {
249
+ var _a;
250
+ const paidSessionId = confirmedSessionId !== null && confirmedSessionId !== void 0 ? confirmedSessionId : checkoutSessionId;
251
+ const context = { blockId: (_a = failure === null || failure === void 0 ? void 0 : failure.blockId) !== null && _a !== void 0 ? _a : 'card', checkoutSessionId: paidSessionId, failureStage: 'verification' };
252
+ status.showError(null, context);
253
+ setBusy(true);
254
+ try {
255
+ if (await completePaywallCheckout('stripe', paidSessionId || '', {
256
+ beforeNotify: async () => { setCompleted(true); await status.trackSuccess(paidSessionId, true); },
257
+ }))
258
+ return;
259
+ if (await status.trackSuccess(paidSessionId))
260
+ return;
261
+ window.location.assign(resolveCheckoutReturnUrl(props.returnUrl, paidSessionId));
262
+ }
263
+ catch (verifyError) {
264
+ status.showError(verifyError instanceof Error && verifyError.message ? verifyError.message : copy.paymentFailed, context, undefined, true);
265
+ }
266
+ finally {
267
+ setBusy(false);
268
+ }
269
+ };
270
+ // A field the form can mark keeps its error inline; any other failure lies over the blocks.
271
+ // After a confirmation every failure lies over the blocks: the only action left is checking the payment.
272
+ const overlayFailure = error && failure && (confirmed || failure.details.category !== 'validation_failure') ? failure : null;
273
+ const dismissFailure = () => status.showError(null, { blockId: activeId !== null && activeId !== void 0 ? activeId : 'card', checkoutSessionId, failureStage: 'dismiss' });
274
+ // Only a method this browser can pay with is offered as the way out of a decline.
275
+ const alternativeBlock = !confirmed && (overlayFailure === null || overlayFailure === void 0 ? void 0 : overlayFailure.details.category) === 'payment_rejection'
276
+ ? blocks.find((block) => block.id === (overlayFailure.blockId === 'card' ? 'wallet' : 'card')
277
+ && !(block.kind === 'wallet' && walletAvailable === false))
278
+ : undefined;
279
+ const blockLabel = (block) => {
280
+ var _a;
281
+ return block.kind === 'wallet' ? copy.walletLabels[wallet]
282
+ : block.kind === 'card' ? copy.cardLabel
283
+ : block.kind === 'paypal' ? (_a = props.paypalLabel) !== null && _a !== void 0 ? _a : 'PayPal'
284
+ : block.types.map((type) => methodLabel(type, copy)).join(' · ');
285
+ };
286
+ const layout = (_jsxs("div", { className: 'wfc', style: style, children: [renderedBlocks.map((block) => block.kind === 'wallet' && walletHidden
287
+ ? _jsx("div", { hidden: true, children: renderBlock(block) }, 'wallet')
288
+ : renderBlock(block)), error && !overlayFailure ? _jsx("p", { className: 'wfc-error', role: 'alert', children: error }) : null, overlayFailure && error ? (_jsx(CheckoutErrorOverlay, { category: overlayFailure.details.category, copy: copy.errors, message: error, onDismiss: dismissFailure, title: confirmed ? copy.verifyingPayment : undefined, dismissible: !confirmed, primary: confirmed ? { label: (_q = (_p = copy.errors) === null || _p === void 0 ? void 0 : _p.checkStatusLabel) !== null && _q !== void 0 ? _q : 'Check payment status', onClick: () => void checkPaymentStatus() } : undefined, alternative: alternativeBlock ? { label: blockLabel(alternativeBlock), onSelect: () => { select(alternativeBlock.id); dismissFailure(); } } : null }, `${overlayFailure.blockId}:${error}`)) : null] }));
289
+ return (_jsxs(_Fragment, { children: [options && stripePromise ? (_jsx(CheckoutProvider, { stripe: stripePromise, options: options, children: layout }, options.clientSecret)) : layout, _jsx("style", { children: stripeWalletFirstCheckoutStyles })] }));
290
+ }
291
+ /** Stripe collects what each other method needs (e.g. the CPF for Pix); only the card form restricts its fields. */
292
+ const methodPaymentElementOptions = {
293
+ layout: 'tabs',
294
+ terms: { card: 'never' },
295
+ wallets: { applePay: 'never', googlePay: 'never', link: 'never' },
296
+ };
297
+ /** One block with its own Checkout Session restricted to its methods, created when the block is selected. */
298
+ function SessionMethodBlock(_a) {
299
+ var { block, checked, disabled, onSelect, sessionInput, themeColor } = _a, form = __rest(_a, ["block", "checked", "disabled", "onSelect", "sessionInput", "themeColor"]);
300
+ // The caller's callbacks belong to the card session; this block reports its own session error below.
301
+ const session = useStripeSubscriptionCheckoutSession(Object.assign(Object.assign({}, sessionInput), { onError: undefined, onPreparationStart: undefined, onReset: undefined, paymentMethodTypes: block.types }));
302
+ const { activeClientSecret, prepareCardCheckout } = session;
303
+ // Session creation is preparation, not a checkout start; the client reports the start on engagement.
65
304
  useEffect(() => {
66
- if (!checkoutAnalytics || !clientSecret || selected !== 'card' || !cardEngaged)
305
+ if (!checked || activeClientSecret)
67
306
  return;
68
- queueStripeSubscriptionCheckoutStarted(Object.assign(Object.assign({}, checkoutAnalytics), { checkoutSessionId, checkoutStartSource: 'card_form_open', paymentMethod: 'card' }));
69
- }, [checkoutAnalytics, checkoutSessionId, clientSecret, selected, cardEngaged]);
70
- return (_jsxs(_Fragment, { children: [options && stripePromise ? (_jsx(CheckoutProvider, { stripe: stripePromise, options: options, children: _jsx(StripeWalletFirstCheckoutForm, Object.assign({}, props, { wallet: wallet, selected: selected, onSelect: select, onCardEngaged: engageCard, style: style })) }, options.clientSecret)) : (_jsx(CheckoutLayout, { copy: copy, wallet: wallet, selected: selected, onSelect: select, disabled: false, style: style, walletSlot: _jsx("span", { className: 'wfc-progress', role: 'status', "aria-label": copy.processingLabel }), cardBody: _jsx("span", { className: 'wfc-progress wfc-progress--form', "aria-hidden": 'true' }) })), _jsx("style", { children: stripeWalletFirstCheckoutStyles })] }));
307
+ void prepareCardCheckout({ checkoutStartSource: 'checkout_render' });
308
+ }, [activeClientSecret, checked, prepareCardCheckout]);
309
+ const options = useMemo(() => activeClientSecret ? buildWalletFirstCheckoutOptions(activeClientSecret, themeColor) : null, [activeClientSecret, themeColor]);
310
+ const label = block.types.map((type) => methodLabel(type, form.copy)).join(' · ');
311
+ return (_jsxs(MethodCard, { checked: checked, disabled: disabled, label: label, onSelect: onSelect, header: _jsx("span", { className: 'wfc-method-label', children: label }), children: [options && session.stripePromise ? (_jsx(CheckoutProvider, { stripe: session.stripePromise, options: options, children: _jsx(MethodForm, Object.assign({}, form, { blockId: block.id, checkoutSessionId: session.checkoutSessionId, failureStage: 'method_form', paymentElementOptions: methodPaymentElementOptions, paymentMethod: block.types.length === 1 ? block.types[0] : undefined, selected: checked, startSource: 'method_form_open' })) }, options.clientSecret)) : _jsx(FormPlaceholder, {}), session.error ? _jsx("p", { className: 'wfc-error', role: 'alert', children: session.error }) : null] }));
71
312
  }
72
- function StripeWalletFirstCheckoutForm({ amountCents, checkoutAnalytics, checkoutSessionId, copy, customerEmail, customerName, onCancel, onError, onSuccess, paymentElementOptions: paymentElementOverrides, returnUrl, summaryLabel, wallet, selected, onSelect, onCardEngaged, style, }) {
313
+ /** Stripe's Payment Element for one Checkout Session plus the submit button; must render inside that session's `CheckoutProvider`. */
314
+ function MethodForm({ blockId, checkoutAnalytics, checkoutSessionId, copy, countries, customerEmail, email, engaged, failureStage, onEngage, onPaymentInfoSubmitted, paymentElementOptions, paymentMethod, returnUrl, selected, startSource, status, }) {
315
+ var _a, _b;
73
316
  const checkoutState = useCheckout();
74
- // null until Stripe answers; the slot shows progress at the button's height meanwhile.
75
- const [walletAvailable, setWalletAvailable] = useState(null);
76
- const [walletConfirming, setWalletConfirming] = useState(false);
77
317
  const [paymentElementReady, setPaymentElementReady] = useState(false);
78
318
  const [paymentElementComplete, setPaymentElementComplete] = useState(false);
319
+ const [pickedMethod, setPickedMethod] = useState(undefined);
320
+ const [billingCountry, setBillingCountry] = useState(null);
79
321
  const [submitting, setSubmitting] = useState(false);
322
+ // Confirmation belongs to this session: a replaced session confirms again.
80
323
  const [providerConfirmed, setProviderConfirmed] = useState(false);
81
- const [completed, setCompleted] = useState(false);
82
- const [error, setError] = useState(null);
83
324
  const submitInFlight = useRef(false);
84
- const expressOptions = useMemo(() => ({
85
- buttonHeight: 55,
86
- buttonTheme: { applePay: 'black', googlePay: 'black' },
87
- buttonType: { applePay: 'plain', googlePay: 'plain' },
88
- layout: { maxColumns: 1, maxRows: 1, overflow: 'auto' },
89
- paymentMethods: {
90
- amazonPay: 'never', klarna: 'never', link: 'never', paypal: 'never',
91
- applePay: wallet === 'applePay' ? 'always' : 'never',
92
- googlePay: wallet === 'googlePay' ? 'always' : 'never',
93
- },
94
- }), [wallet]);
95
- const paymentElementOptions = useMemo(() => {
96
- var _a;
97
- const billingDetails = (_a = paymentElementOverrides === null || paymentElementOverrides === void 0 ? void 0 : paymentElementOverrides.fields) === null || _a === void 0 ? void 0 : _a.billingDetails;
98
- return Object.assign(Object.assign({ layout: 'tabs', terms: { card: 'never' }, wallets: { applePay: 'never', googlePay: 'never', link: 'never' } }, paymentElementOverrides), { fields: {
99
- billingDetails: typeof billingDetails === 'string' ? billingDetails : Object.assign({ name: 'never', email: 'never',
100
- // US banks match the postal code against the cardholder's; without it they decline more as fraud.
101
- address: { country: 'auto', postalCode: 'auto' } }, billingDetails),
102
- } });
103
- }, [paymentElementOverrides]);
325
+ const method = paymentMethod !== null && paymentMethod !== void 0 ? paymentMethod : pickedMethod;
326
+ // A saved email change replaces the session; this form waits for the new one.
327
+ const emailPending = Boolean(email && (email.emailSaving || email.emailSessionChanged));
328
+ // The checkout starts when the visitor opens the form, or, when it opens preselected, on their first input into it.
329
+ useEffect(() => {
330
+ if (!checkoutAnalytics || !selected || !engaged)
331
+ return;
332
+ queueStripeSubscriptionCheckoutStarted(Object.assign(Object.assign({}, checkoutAnalytics), { checkoutSessionId, checkoutStartSource: startSource, paymentMethod: method }));
333
+ }, [checkoutAnalytics, checkoutSessionId, selected, engaged, method, startSource]);
104
334
  // A hidden Payment Element measures 0px wide; let Stripe re-layout when it opens.
105
335
  useEffect(() => {
106
- if (selected !== 'card')
336
+ if (!selected)
107
337
  return;
108
338
  const timer = window.setTimeout(() => window.dispatchEvent(new Event('resize')), 0);
109
339
  return () => window.clearTimeout(timer);
110
340
  }, [selected]);
111
- const showError = (message, details, alreadyTracked = false) => {
112
- const errorDetails = message ? details !== null && details !== void 0 ? details : normalizeStripeCheckoutError(message, undefined, 'card') : undefined;
113
- if (message && checkoutAnalytics && !alreadyTracked) {
114
- trackCheckoutFailureShown(Object.assign({ analytics: checkoutAnalytics, checkoutSessionId, errorMessage: message, failureStage: 'card_form', provider: 'stripe' }, errorDetails));
115
- }
116
- setError(message);
117
- if (message)
118
- onError === null || onError === void 0 ? void 0 : onError(message, errorDetails);
119
- else
120
- onError === null || onError === void 0 ? void 0 : onError(message);
121
- };
122
- /** Resolves true when the caller's onSuccess handled the navigation itself. */
123
- const trackSuccess = async (embedded = false) => {
124
- if (checkoutAnalytics)
125
- await trackPaidStripeSubscriptionCheckoutCompleted(Object.assign(Object.assign({}, checkoutAnalytics), { checkoutSessionId }));
126
- if (embedded)
127
- return false;
128
- return (await (onSuccess === null || onSuccess === void 0 ? void 0 : onSuccess())) === true;
129
- };
341
+ const failure = { blockId, checkoutSessionId, failureStage, paymentMethod: method };
342
+ const showError = (message, details, alreadyTracked = false) => status.showError(message, failure, details, alreadyTracked);
130
343
  const finishPaidCheckout = async () => {
131
344
  if (await completePaywallCheckout('stripe', checkoutSessionId || '', {
132
- beforeNotify: async () => { setCompleted(true); await trackSuccess(true); },
345
+ beforeNotify: async () => { status.markCompleted(); await status.trackSuccess(checkoutSessionId, true); },
133
346
  }))
134
347
  return;
135
- if (await trackSuccess())
348
+ if (await status.trackSuccess(checkoutSessionId))
136
349
  return;
137
- window.location.assign(returnUrl);
350
+ window.location.assign(resolveCheckoutReturnUrl(returnUrl, checkoutSessionId));
138
351
  };
139
- const submitCard = async (event) => {
352
+ const submit = async (event) => {
140
353
  event.preventDefault();
141
- if (submitInFlight.current)
354
+ if (submitInFlight.current || (emailPending && !providerConfirmed))
142
355
  return;
143
356
  if (!providerConfirmed) {
357
+ const countryError = getUnsupportedCheckoutCountryMessage({
358
+ billingCountry: billingCountry !== null && billingCountry !== void 0 ? billingCountry : countries.fixed, message: countries.message, supportedCountries: countries.supported,
359
+ });
360
+ if (countryError) {
361
+ showError(countryError, validationFailure(countryError, method));
362
+ return;
363
+ }
144
364
  if (checkoutState.type !== 'success') {
145
365
  showError(checkoutState.type === 'error' ? checkoutState.error.message : copy.formNotReady);
146
366
  return;
@@ -152,49 +372,79 @@ function StripeWalletFirstCheckoutForm({ amountCents, checkoutAnalytics, checkou
152
372
  }
153
373
  submitInFlight.current = true;
154
374
  setSubmitting(true);
375
+ status.setBusy(true);
155
376
  showError(null);
377
+ const stopSubmitting = () => {
378
+ submitInFlight.current = false;
379
+ setSubmitting(false);
380
+ status.setBusy(false);
381
+ };
156
382
  let confirmed = providerConfirmed;
157
383
  try {
158
384
  if (!providerConfirmed && checkoutState.type === 'success') {
159
385
  const { checkout } = checkoutState;
160
- if (!checkout.email && customerEmail) {
161
- const updated = await checkout.updateEmail(customerEmail);
386
+ const payerEmail = email ? await email.ensureCustomerEmail() : customerEmail;
387
+ // A missing or just-saved email needs a fresh action on the replaced session.
388
+ if (email && !payerEmail) {
389
+ stopSubmitting();
390
+ return;
391
+ }
392
+ if (!checkout.email && payerEmail) {
393
+ const updated = await checkout.updateEmail(payerEmail);
162
394
  if (updated.type === 'error')
163
395
  throw new Error(updated.error.message);
164
396
  }
165
- if (paymentElementComplete && checkoutAnalytics) {
166
- await trackStripeSubscriptionPaymentInfoSubmitted(Object.assign(Object.assign({}, checkoutAnalytics), { checkoutSessionId })).catch(() => 'analytics_rejected');
397
+ if (paymentElementComplete) {
398
+ if (checkoutAnalytics) {
399
+ await trackStripeSubscriptionPaymentInfoSubmitted(Object.assign(Object.assign({}, checkoutAnalytics), { checkoutSessionId })).catch(() => 'analytics_rejected');
400
+ }
401
+ await (onPaymentInfoSubmitted === null || onPaymentInfoSubmitted === void 0 ? void 0 : onPaymentInfoSubmitted());
167
402
  }
168
403
  const result = await checkout.confirm({ redirect: 'if_required' });
169
404
  if (result.type === 'error' && !isStripeCheckoutAlreadyPaidError(result.error)) {
170
405
  const message = result.error.message || copy.paymentFailed;
171
- showError(message, normalizeStripeCheckoutError(message, result.error, 'card'));
172
- submitInFlight.current = false;
173
- setSubmitting(false);
406
+ showError(message, normalizeStripeCheckoutError(message, result.error, method));
407
+ stopSubmitting();
174
408
  return;
175
409
  }
176
410
  confirmed = true;
177
411
  setProviderConfirmed(true);
412
+ status.markConfirmed(checkoutSessionId);
178
413
  }
179
414
  await finishPaidCheckout();
180
415
  }
181
416
  catch (submitError) {
182
417
  showError(submitError instanceof Error && submitError.message ? submitError.message : copy.paymentFailed, undefined, confirmed);
183
- submitInFlight.current = false;
184
- setSubmitting(false);
418
+ stopSubmitting();
185
419
  }
186
420
  };
187
421
  // After a successful confirmation the form stays in place and reports progress
188
422
  // where the customer paid, until the success screen takes over.
189
- const paymentStatus = completed ? copy.paymentConfirmed : providerConfirmed ? copy.verifyingPayment : null;
190
- const locked = Boolean(paymentStatus) && !error;
191
- return (_jsx(CheckoutLayout, { copy: copy, wallet: wallet, selected: selected, onSelect: onSelect, disabled: submitting || walletConfirming || locked, style: style, walletNote: selected === 'wallet' ? paymentStatus : null, walletSlot: _jsxs(_Fragment, { children: [_jsx("div", { className: 'wfc-wallet-button', "data-ready": walletAvailable === true, children: _jsx(StripeCheckoutExpressCheckoutButton, { amountCents: amountCents, availabilityPaymentMethods: [wallet], beforeConfirm: async () => { setWalletConfirming(true); return customerEmail || null; }, checkoutAnalytics: checkoutAnalytics, checkoutSessionId: checkoutSessionId, confirmEmail: false, customerEmail: customerEmail, customerName: customerName, onAvailabilityChange: setWalletAvailable, onCancel: () => { setWalletConfirming(false); onCancel === null || onCancel === void 0 ? void 0 : onCancel(); }, onEmbeddedComplete: () => setCompleted(true), onError: (message, details) => { setWalletConfirming(false); showError(message, details, true); }, onPaymentRejected: () => { setWalletConfirming(false); onSelect('card'); }, onSuccess: async () => { await trackSuccess(); }, onVerificationPending: () => setProviderConfirmed(true), options: expressOptions, returnUrl: returnUrl, summaryLabel: summaryLabel }) }), walletAvailable === null ? _jsx("span", { className: 'wfc-progress wfc-progress--overlay', role: 'status', "aria-label": copy.processingLabel }) : null, walletAvailable === false ? _jsx("p", { className: 'wfc-wallet-unavailable', role: 'status', children: copy.walletUnavailableNote.replace('{wallet}', copy.walletLabels[wallet]) }) : null] }), cardBody: _jsxs("form", { className: 'wfc-card-form', onSubmit: event => void submitCard(event), children: [_jsx(PaymentElement, { options: paymentElementOptions, onChange: event => { setPaymentElementComplete(event.complete); if (!event.empty)
192
- onCardEngaged(); }, onReady: () => setPaymentElementReady(true) }), _jsx("button", { type: 'submit', className: 'wfc-submit', disabled: locked || submitting || !paymentElementReady, "aria-live": 'polite', children: locked && paymentStatus ? paymentStatus : submitting ? copy.processingLabel : copy.cardSubmitLabel }), _jsx("p", { className: 'wfc-secure', children: copy.secureNote })] }), footer: error ? _jsx("p", { className: 'wfc-error', role: 'alert', children: error }) : null }));
423
+ const { locked } = status;
424
+ const showEmailField = Boolean(email && email.customerEmailEditable);
425
+ return (_jsxs("form", { className: 'wfc-card-form', onSubmit: (event) => void submit(event), children: [email && showEmailField ? (_jsxs("label", { className: 'wfc-email', children: [_jsx("span", { className: 'wfc-email-label', children: (_a = email.field.label) !== null && _a !== void 0 ? _a : 'Email' }), _jsx("input", { type: 'email', autoComplete: 'email', inputMode: 'email', className: 'wfc-email-input', disabled: email.emailSaving || locked, placeholder: (_b = email.field.placeholder) !== null && _b !== void 0 ? _b : 'Enter your email', value: email.emailDraft, onBlur: (event) => email.commitEmailDraftIfValid(event.currentTarget.value), onChange: (event) => { email.setEmailDraft(event.target.value); onEngage(); } })] })) : null, _jsx(PaymentElement, { options: paymentElementOptions, onChange: (event) => {
426
+ var _a, _b, _c, _d, _e;
427
+ setPaymentElementComplete(event.complete);
428
+ setPickedMethod((_a = event.value) === null || _a === void 0 ? void 0 : _a.type);
429
+ setBillingCountry((_e = (_d = (_c = (_b = event.value) === null || _b === void 0 ? void 0 : _b.billingDetails) === null || _c === void 0 ? void 0 : _c.address) === null || _d === void 0 ? void 0 : _d.country) !== null && _e !== void 0 ? _e : countries.fixed);
430
+ if (!event.empty)
431
+ onEngage();
432
+ }, onReady: () => setPaymentElementReady(true) }), _jsx("button", { type: 'submit', className: 'wfc-submit', disabled: locked || submitting || emailPending || !paymentElementReady, "aria-live": 'polite', children: locked && status.paymentStatus ? status.paymentStatus : submitting || emailPending ? copy.processingLabel : copy.cardSubmitLabel }), _jsx("p", { className: 'wfc-secure', children: copy.secureNote })] }));
433
+ }
434
+ /** A failure the visitor fixes in a field: shown next to the form, not over it. */
435
+ const validationFailure = (message, paymentMethod) => (Object.assign(Object.assign({}, normalizeStripeCheckoutError(message, undefined, paymentMethod)), { category: 'validation_failure' }));
436
+ function FormPlaceholder() {
437
+ return _jsx("span", { className: 'wfc-progress wfc-progress--form', "aria-hidden": 'true' });
193
438
  }
194
- /** Shared by the loading and live states so switching between them moves nothing. */
195
- function CheckoutLayout({ cardBody, copy, disabled, footer, onSelect, selected, style, wallet, walletNote, walletSlot }) {
196
- const WalletMark = wallet === 'applePay' ? ApplePayMark : GooglePayMark;
197
- return (_jsxs("div", { className: 'wfc', style: style, children: [_jsxs(MethodCard, { checked: selected === 'wallet', disabled: disabled, label: copy.walletLabels[wallet], onSelect: () => onSelect('wallet'), header: _jsx(WalletMark, {}), children: [_jsx("ul", { className: 'wfc-benefits', children: copy.walletBenefits[wallet].map(item => _jsxs("li", { children: [_jsx(CheckIcon, {}), item] }, item)) }), _jsx("div", { className: 'wfc-wallet-slot', children: walletSlot }), _jsx("p", { className: walletNote ? 'wfc-secure is-status' : 'wfc-secure', role: walletNote ? 'status' : undefined, children: walletNote || copy.secureNote })] }), _jsx(MethodCard, { checked: selected === 'card', disabled: disabled, label: copy.cardLabel, onSelect: () => onSelect('card'), header: _jsx(CardBrandMarks, {}), children: cardBody }), footer] }));
439
+ function resolveCardPaymentElementOptions(overrides, fixedCountry) {
440
+ var _a;
441
+ const billingDetails = (_a = overrides === null || overrides === void 0 ? void 0 : overrides.fields) === null || _a === void 0 ? void 0 : _a.billingDetails;
442
+ return Object.assign(Object.assign(Object.assign({}, methodPaymentElementOptions), overrides), { fields: {
443
+ billingDetails: typeof billingDetails === 'string' ? billingDetails : Object.assign({ name: 'never', email: 'never',
444
+ // US banks match the postal code against the cardholder's; without it they decline more as fraud.
445
+ // A single accepted country is filled in through the session's default billing address.
446
+ address: { country: fixedCountry ? 'never' : 'auto', postalCode: 'auto' } }, billingDetails),
447
+ } });
198
448
  }
199
449
  function CheckIcon() {
200
450
  return _jsx("svg", { className: 'wfc-check', viewBox: '0 0 16 16', "aria-hidden": 'true', children: _jsx("path", { d: 'M3 8.5 6.5 12 13 4.5', fill: 'none', stroke: 'currentColor', strokeWidth: '2', strokeLinecap: 'round', strokeLinejoin: 'round' }) });
@@ -0,0 +1,24 @@
1
+ /** `fixedBillingCountry` fills in the only billing country the offer accepts. */
2
+ export declare function buildWalletFirstCheckoutOptions(clientSecret: string, themeColor?: string, fixedBillingCountry?: string | null): {
3
+ elementsOptions: {
4
+ appearance: {
5
+ variables: {
6
+ colorPrimary?: string | undefined;
7
+ borderRadius: string;
8
+ colorBackground: string;
9
+ colorText: string;
10
+ colorTextPlaceholder: string;
11
+ spacingUnit: string;
12
+ };
13
+ labels: "above";
14
+ };
15
+ };
16
+ defaultValues?: {
17
+ billingAddress: {
18
+ address: {
19
+ country: string;
20
+ };
21
+ };
22
+ } | undefined;
23
+ clientSecret: string;
24
+ };