@flopay/js 1.20.8 → 1.20.10

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.
@@ -109,3 +109,48 @@ export interface CheckoutRuntimeAutomaticPayment {
109
109
  export interface CheckoutRuntimeMountOptions {
110
110
  automaticPayment?: CheckoutRuntimeAutomaticPayment;
111
111
  }
112
+ /** Which setup a hosted setup mount runs (contract 2.4.0). Never inferred from an amount. */
113
+ export type CheckoutRuntimeSetupKind = 'card' | 'payment_method';
114
+ /**
115
+ * The events a hosted setup relays (contract 2.4.0): `setupReady` (no payload), `setupValidation`
116
+ * (`{ message: string | null }`, null once validation clears), `complete`
117
+ * (`{ status: 'succeeded', sessionId, paymentMethod? }`), `decline`
118
+ * (`{ status: 'declined', sessionId, reason?, message? }`), `cancel`
119
+ * (`{ status: 'cancelled', sessionId }`) and `error` (message, type, code, retryable and, where
120
+ * supplied, param and statusCode).
121
+ */
122
+ export type CheckoutRuntimeSetupEventName = 'setupReady' | 'setupValidation' | 'complete' | 'decline' | 'cancel' | 'error';
123
+ export interface CheckoutRuntimeSetupEvent {
124
+ name: CheckoutRuntimeSetupEventName;
125
+ payload?: unknown;
126
+ }
127
+ /**
128
+ * What a wrapper hands the runtime to mount one setup (contract 2.4.0). The session is one the
129
+ * merchant's server created: setup needs no publishable key and creates no purchase session.
130
+ * The runtime resolves the theme and the wording; a wrapper only passes the merchant's choice.
131
+ */
132
+ export interface CheckoutRuntimeSetupMountOptions {
133
+ setup: CheckoutRuntimeSetupKind;
134
+ sessionId: string;
135
+ nonce: string;
136
+ theme?: import('@flopay/shared').ThemeId | import('@flopay/shared').VaultCardThemeColors;
137
+ appearance?: import('@flopay/shared').FloPayAppearance;
138
+ buttonsStyles?: import('@flopay/shared').ButtonsLayoutStyles;
139
+ containerStyle?: Readonly<Record<string, string | number | undefined>>;
140
+ strings?: Record<string, string>;
141
+ contractVersion?: string;
142
+ onEvent?: (event: CheckoutRuntimeSetupEvent) => void;
143
+ }
144
+ /** What a mounted setup accepts after it is mounted. A change never remounts the card fields. */
145
+ export type CheckoutRuntimeSetupUpdateOptions = Partial<Pick<CheckoutRuntimeSetupMountOptions, 'theme' | 'appearance' | 'buttonsStyles' | 'containerStyle' | 'strings' | 'onEvent'>>;
146
+ export interface CheckoutRuntimeSetupHandle {
147
+ update(options: CheckoutRuntimeSetupUpdateOptions): void;
148
+ unmount(): void;
149
+ }
150
+ /**
151
+ * The setup mount, added in contract 2.4.0. A runtime built before it has none, so a wrapper
152
+ * reports a structured error instead of mounting a checkout in its place.
153
+ */
154
+ export interface CheckoutRuntime {
155
+ mountSetup?(container: HTMLElement, options: CheckoutRuntimeSetupMountOptions): CheckoutRuntimeSetupHandle;
156
+ }
@@ -0,0 +1,37 @@
1
+ export interface PaymentMethodDescriptor {
2
+ id: string;
3
+ /** The payment method, e.g. `ideal`: an open string, never a closed list. */
4
+ method: string;
5
+ /** Where the method is placed: `card`, a provider's own group, `wallets` or `apms`. */
6
+ group: string;
7
+ /** The provider that serves it: an open string, which may be one the runtime has no adapter for. */
8
+ provider: string;
9
+ available: boolean;
10
+ /** Whether a payment made with it can be reused. Taken from the response, never guessed. */
11
+ reusable: boolean;
12
+ /** How the method reaches the buyer. `provider-frame` and `hosted-card` are the two card surfaces. */
13
+ presentation: 'button' | 'redirect' | 'provider-frame' | 'hosted-card';
14
+ /** Browser-safe settings for the provider's adapter. */
15
+ config: Readonly<Record<string, unknown>>;
16
+ }
17
+ export interface DescriptorRead {
18
+ /**
19
+ * Whether the response advertises its methods at all (an empty list included). `false` is a
20
+ * response that predates descriptors: the 1.x gateway reading stays in force.
21
+ */
22
+ advertised: boolean;
23
+ methods: PaymentMethodDescriptor[];
24
+ /** How many entries were malformed and left out. */
25
+ rejected: number;
26
+ }
27
+ /**
28
+ * The capability token the runtime sends when it reads a session, so the API only adds
29
+ * descriptors to the answers of a runtime that understands them (1.x answers stay unchanged).
30
+ */
31
+ export declare const PAYMENT_METHODS_CAPABILITY = "payment-methods-v1";
32
+ /**
33
+ * Reads the advertised methods from a session response, wrapped in `data` or flat. A response
34
+ * with no list is a 1.x answer. A list that is not a list advertises nothing, so it can never
35
+ * fall back to the 1.x gateways and hand a method to a provider the API did not name.
36
+ */
37
+ export declare function readPaymentMethodDescriptors(body: unknown): DescriptorRead;
@@ -0,0 +1,13 @@
1
+ export type JsonRecord = Record<string, unknown>;
2
+ export declare function isRecord(value: unknown): value is JsonRecord;
3
+ export declare function text(...values: unknown[]): string | undefined;
4
+ /** The record inside the API's `data` wrapper, or the body itself when it has none. */
5
+ export declare function dataOf(body: unknown): JsonRecord;
6
+ export declare function delay(ms: number): Promise<void>;
7
+ export declare function providerMessage(error: unknown, fallback: string): string;
8
+ export declare function pageGlobal(name: string): unknown;
9
+ /**
10
+ * Adds a provider's script to the page once and settles when it loads. A script still on the
11
+ * page is reused; one that failed or was removed is added again on the next mount.
12
+ */
13
+ export declare function loadScript(src: string, attributes?: Record<string, string>): Promise<void>;
@@ -0,0 +1,118 @@
1
+ import type { PaymentMethodDescriptor } from './method-descriptors.js';
2
+ /** One buyer attempt at one method, from the click to its one terminal outcome. */
3
+ export interface ProviderAttempt {
4
+ readonly method: string;
5
+ /** `POST …/intents` for the descriptor's provider and this method, with `request` merged in. */
6
+ createIntent(request?: Record<string, unknown>): Promise<Record<string, unknown>>;
7
+ /** Remembers `reference` so a redirect back to this page resumes this session. */
8
+ saveContinuation(reference: string): void;
9
+ /**
10
+ * The provider says the buyer paid: the attempt now waits for the backend to say so too. Only
11
+ * the backend's session completes the payment.
12
+ */
13
+ settle(): Promise<void>;
14
+ /**
15
+ * Hands the provider's approval to the backend (`POST …/process`) and ends the attempt with
16
+ * what the backend answers: a refusal is one `decline`, a payment still processing waits for
17
+ * the session, and only an accepted payment completes.
18
+ */
19
+ process(body: Record<string, unknown>, options?: {
20
+ declineMessage?: string;
21
+ }): Promise<void>;
22
+ decline(failure: {
23
+ message: string;
24
+ declineCode?: string;
25
+ }): void;
26
+ /** The buyer cancelled at the provider; `paymentMethodType` is the channel the provider names. */
27
+ cancel(details?: {
28
+ paymentMethodType?: string;
29
+ }): void;
30
+ fail(error: unknown): void;
31
+ /** Ends the attempt with no outcome: the buyer started another one, or a popup was blocked. */
32
+ abandon(): void;
33
+ /** Whether the attempt has ended, so a late callback can be told apart from a live one. */
34
+ readonly ended: boolean;
35
+ }
36
+ /** What the shared host gives an adapter. */
37
+ export interface ProviderServices {
38
+ readonly session: {
39
+ id: string;
40
+ token: string;
41
+ currency?: string;
42
+ amount?: number;
43
+ };
44
+ /** The descriptors this mount hands to this provider, in the order the API sent them. */
45
+ readonly methods: readonly PaymentMethodDescriptor[];
46
+ /** False once the mount is gone: nothing an adapter does afterwards reaches the merchant. */
47
+ active(): boolean;
48
+ /** Whether a new attempt could start now (none running and the session not paid). */
49
+ canAttempt(): boolean;
50
+ /** Starts an attempt, or `null` while another is running or the session is already paid. */
51
+ beginAttempt(method: string): ProviderAttempt | null;
52
+ }
53
+ /** A provider's own redirect return that keeps its own continuation (a 1.x return). */
54
+ interface OwnedProviderReturn {
55
+ /** The session the buyer left from, when this browser saved it before the redirect. */
56
+ resume: {
57
+ sessionId?: string;
58
+ nonce?: string;
59
+ } | null;
60
+ outcome: 'succeeded' | 'failed';
61
+ /** Forgets the continuation and takes the provider's parameters out of the address. */
62
+ consume(): void;
63
+ }
64
+ export interface MountedMethod {
65
+ destroy(): void;
66
+ }
67
+ export interface RuntimeProviderAdapter {
68
+ /** Matches `PaymentMethodDescriptor.provider`. */
69
+ readonly provider: string;
70
+ /** The query parameters this provider's redirect return carries: removed from every outlet. */
71
+ readonly returnParameters?: readonly string[];
72
+ /**
73
+ * Groups in which the provider draws all of its methods as one surface: those descriptors
74
+ * reach `mount` together, once, as `methods`.
75
+ */
76
+ readonly combinedGroups?: readonly string[];
77
+ /** The methods a 1.x session's gateway entry stands for, when the API sends no descriptors. */
78
+ legacyMethods?(gateways: Readonly<Record<string, unknown>>): PaymentMethodDescriptor[];
79
+ /** Loads the provider's SDK or probes the browser, once per mount, before anything renders. */
80
+ prepare?(services: ProviderServices): Promise<void>;
81
+ /** Whether this browser can use the method. It can only suppress a method, never add one. */
82
+ isSupported?(descriptor: PaymentMethodDescriptor, services: ProviderServices): boolean | Promise<boolean>;
83
+ mount(request: {
84
+ descriptor: PaymentMethodDescriptor;
85
+ /** Every descriptor this mount draws: `[descriptor]`, or a whole combined group. */
86
+ methods: readonly PaymentMethodDescriptor[];
87
+ host: HTMLElement;
88
+ services: ProviderServices;
89
+ /** The surface says whether the buyer can use it here (a wallet the device lacks cannot). */
90
+ setAvailable(available: boolean): void;
91
+ /** The surface could not be drawn: its place on the page goes. */
92
+ remove(): void;
93
+ }): MountedMethod | Promise<MountedMethod>;
94
+ /** Reads this provider's return out of the page's query, or `null` when it is not its own. */
95
+ readReturn?(query: URLSearchParams): {
96
+ /** Correlates the return with the continuation saved before the redirect. */
97
+ reference: string;
98
+ outcome: 'succeeded' | 'failed' | 'cancelled';
99
+ } | null;
100
+ /** A return the provider keeps its own continuation for, read once at mount. */
101
+ takeReturn?(): OwnedProviderReturn | null;
102
+ /** Whether the full checkout can take over a saved payment of this method that failed (1.x). */
103
+ recoversInFullCheckout?(method: string): boolean;
104
+ /**
105
+ * The failure a status read's `ACTION_REQUIRED` attempt stands for when the buyer must approve
106
+ * this provider's payment again, or `null` when the attempt is not this provider's.
107
+ */
108
+ reapproval?(attempt: Record<string, unknown>): Record<string, unknown> | null;
109
+ }
110
+ /** Registers an adapter; the function it returns removes it again. */
111
+ export declare function registerRuntimeProvider(adapter: RuntimeProviderAdapter): () => void;
112
+ /** The providers the runtime has an adapter for. */
113
+ export declare function registeredProviderIds(): string[];
114
+ /** The adapter registered for a provider, if any: an unknown provider has none to fall back to. */
115
+ export declare function providerAdapter(provider: string): RuntimeProviderAdapter | undefined;
116
+ /** Every registered adapter, in the order they registered. */
117
+ export declare function registeredAdapters(): RuntimeProviderAdapter[];
118
+ export {};
@@ -0,0 +1,2 @@
1
+ import type { RuntimeProviderAdapter } from '../provider-registry.js';
2
+ export declare const builtInProviders: readonly RuntimeProviderAdapter[];
@@ -0,0 +1,2 @@
1
+ import type { RuntimeProviderAdapter } from '../provider-registry.js';
2
+ export declare const paypalAdapter: RuntimeProviderAdapter;
@@ -0,0 +1,2 @@
1
+ import type { RuntimeProviderAdapter } from '../provider-registry.js';
2
+ export declare const stripeAdapter: RuntimeProviderAdapter;
@@ -1,17 +1,19 @@
1
1
  import type { PaymentMethodGroupLayout } from '@flopay/shared';
2
2
  import { FloPayError } from '@flopay/shared';
3
3
  import type { CheckoutRuntimeEvent, CheckoutRuntimeLayout } from './checkout-runtime/contract.js';
4
- type JsonRecord = Record<string, unknown>;
4
+ import type { DescriptorRead } from './checkout-runtime/method-descriptors.js';
5
+ import type { JsonRecord } from './checkout-runtime/provider-kit.js';
5
6
  export declare function isCompleteStatus(status: unknown): boolean;
6
7
  /**
7
8
  * Whether the full checkout can take over a saved payment that failed recoverably (1.x): one
8
- * that names no payment method, a card, or a PayPal payment (whose order the API supplied).
9
+ * that names no payment method, a card, or a method whose provider says the full checkout can
10
+ * take it over.
9
11
  */
10
12
  export declare function fullCheckoutRecovers(method: string | undefined): boolean;
11
13
  /**
12
14
  * The failure a status read's `ACTION_REQUIRED` attempt stands for when the buyer must approve
13
- * a PayPal order again (1.x `resolveCheckoutSessionStatus`): `paypal_direct_required` with the
14
- * fresh order, which the full checkout then takes over. `null` for any other attempt.
15
+ * the provider's payment again (1.x `resolveCheckoutSessionStatus`), which the full checkout then
16
+ * takes over. `null` for any other attempt.
15
17
  */
16
18
  export declare function reapprovalFailure(attempt: Record<string, unknown>): Record<string, unknown> | null;
17
19
  /** One merchant outcome per payment: nothing reaches the merchant once the session is paid. */
@@ -29,34 +31,59 @@ export interface PaymentMethodsSession {
29
31
  token: string;
30
32
  currency?: string;
31
33
  amount?: number;
34
+ /** The 1.x gateway entries, read only when the API advertises no descriptors. */
32
35
  gateways?: JsonRecord;
36
+ /** The API's method advertisement, from the one descriptor reader. */
37
+ methods?: DescriptorRead;
33
38
  }
34
- /** A buyer the provider's redirect brought back to this page, read once at mount. */
35
- export interface RedirectReturn {
36
- redirectStatus: string | null;
39
+ /** A buyer a provider's redirect brought back to this page, read once at mount. */
40
+ export interface ProviderReturn {
41
+ provider?: string;
42
+ /** The method the buyer left with, when the continuation saved it. */
43
+ method?: string;
44
+ outcome: 'succeeded' | 'failed' | 'cancelled';
37
45
  /** The session this browser left from, saved before the redirect, when it matches. */
38
46
  resume: {
39
47
  sessionId?: string;
40
48
  nonce?: string;
41
49
  } | null;
50
+ consume(): void;
42
51
  }
43
- export declare function readRedirectReturn(): RedirectReturn | null;
52
+ export interface PageReturn {
53
+ /** The page's query with every provider's return parameters taken out, for the frame. */
54
+ query: string | undefined;
55
+ found: ProviderReturn | null;
56
+ }
57
+ /**
58
+ * Reads a provider's return from the page once, at mount, and takes every registered provider's
59
+ * return parameters out of the address before anything else can see them: the frame, telemetry
60
+ * and the merchant get the merchant's own parameters only, on every path.
61
+ */
62
+ export declare function takeProviderReturn(sessionId: string | undefined): PageReturn;
44
63
  /**
45
- * Settles a redirect return against the original session: the saved continuation is consumed
46
- * and the provider's parameters leave the address, so a later mount tells nothing again. Only
47
- * a session the backend reports complete is `complete`; a failed redirect is one `decline`.
64
+ * Settles a redirect return against the original session: the continuation is consumed, so a
65
+ * later mount tells nothing again. Only a session the backend reports complete is `complete`; a
66
+ * failed redirect is one `decline` and a cancelled one one `cancel`.
48
67
  */
49
- export declare function settleRedirectReturn(redirect: RedirectReturn, context: {
68
+ export declare function settleProviderReturn(found: ProviderReturn, context: {
50
69
  apiHost: string;
51
70
  session: PaymentMethodsSession;
52
71
  status: string | undefined;
53
72
  outcomes: Outcomes;
54
73
  active: () => boolean;
55
74
  }): void;
75
+ /**
76
+ * Whether Flo's hosted card form is the session's card surface: for a 1.x answer, and for an
77
+ * advertisement that selects `hosted-card` or names no card surface at all. A `provider-frame`
78
+ * card is never served by Flo's form instead: its provider's adapter mounts it, and a provider
79
+ * the runtime has no adapter for leaves the session with no card surface, as any other method of
80
+ * such a provider is left out, rather than with a card form the API did not offer.
81
+ */
82
+ export declare function hostedCardSelected(methods: DescriptorRead | undefined): boolean;
56
83
  export interface PaymentMethodsContext {
57
84
  container: HTMLElement;
58
- /** The card frame, which stands for the `card` group. */
59
- cardNode: HTMLElement;
85
+ /** Flo's hosted card frame, which stands for the `card` group; `null` for a provider's own. */
86
+ cardNode: HTMLElement | null;
60
87
  apiHost: string;
61
88
  session: PaymentMethodsSession;
62
89
  layout: CheckoutRuntimeLayout;
@@ -72,10 +99,9 @@ export interface PaymentMethodsSurface {
72
99
  destroy(): void;
73
100
  }
74
101
  /**
75
- * Mounts the session's PayPal, wallet and alternative payment method groups in the container.
76
- * The groups appear together once their providers have loaded and the layout is known, so the
77
- * buyer never sees them jump; a provider that cannot load or says the buyer cannot use it
78
- * leaves no group, and never takes the others or the card form down.
102
+ * Mounts the session's payment methods in the container. The groups appear together once their
103
+ * providers have loaded and the layout is known, so the buyer never sees them jump; a provider
104
+ * that cannot load, says the buyer cannot use a method or has no adapter leaves no method, and
105
+ * never takes the others or the card surface down.
79
106
  */
80
107
  export declare function mountPaymentMethods(context: PaymentMethodsContext): PaymentMethodsSurface;
81
- export {};
@@ -0,0 +1,55 @@
1
+ import { FloPayError } from '@flopay/shared';
2
+ type JsonRecord = Record<string, unknown>;
3
+ /** One entry of a setup session's `advertisedPaymentMethods`, as the billing API sends it. */
4
+ export interface SetupMethodEntry {
5
+ family: string;
6
+ paymentMethodType: string;
7
+ providerType?: string;
8
+ publishableKey?: string;
9
+ environment?: string;
10
+ futureUse?: string;
11
+ futureUseUnsupported?: boolean;
12
+ }
13
+ /**
14
+ * One provider's mounting region from the shared UI (ZhSetupSurface's method list), on the
15
+ * merchant page. Declared here by shape, so no declaration this package emits names the private
16
+ * UI package.
17
+ */
18
+ interface SetupMethodRegion {
19
+ readonly element: HTMLElement;
20
+ slot(): HTMLElement;
21
+ action(label: string, onActivate: () => void): void;
22
+ show(): void;
23
+ remove(): void;
24
+ }
25
+ export interface SetupMethodsContext {
26
+ /** The shared UI's method list: each method's controls go in a region of it. */
27
+ regions: {
28
+ region(type: string): SetupMethodRegion;
29
+ };
30
+ apiHost: string;
31
+ sessionId: string;
32
+ nonce: string;
33
+ currency: string;
34
+ accountData?: JsonRecord;
35
+ /** The wallet and alternative payment method entries, each with its own credentials. */
36
+ stripeEntries: SetupMethodEntry[];
37
+ paypalEntry?: SetupMethodEntry;
38
+ /** Whether the hosted card form is offered beside the methods. */
39
+ hasCard: boolean;
40
+ /** A provider could not load; `retryable` is false once no other method is left. */
41
+ onLoadFailure(error: FloPayError, retryable: boolean): void;
42
+ onSubmitting(): void;
43
+ /** The buyer left a provider's sheet or form without an outcome: nothing to report. */
44
+ onIdle(): void;
45
+ /** The provider accepted the setup: only the backend's session can now say it completed. */
46
+ onApproved(): void;
47
+ onDecline(reason?: string, message?: string): void;
48
+ onError(error: FloPayError): void;
49
+ }
50
+ export interface SetupMethodsSurface {
51
+ destroy(): void;
52
+ }
53
+ /** Mounts every advertised wallet, alternative payment method and PayPal in `parent`. */
54
+ export declare function mountSetupMethods(context: SetupMethodsContext): SetupMethodsSurface;
55
+ export {};
@@ -0,0 +1,3 @@
1
+ import type { CheckoutRuntimeConfig, CheckoutRuntimeSetupHandle, CheckoutRuntimeSetupMountOptions } from './checkout-runtime/contract.js';
2
+ /** Mounts one hosted setup in `container`. */
3
+ export declare function mountRuntimeSetup(config: CheckoutRuntimeConfig, container: HTMLElement, options: CheckoutRuntimeSetupMountOptions): CheckoutRuntimeSetupHandle;
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  export type { CardFieldsEvent, CardFieldsFailedEvent, CardFieldsFailureReason, CardFieldsReadyEvent, SentryEventLike, SentryStackFrameLike, } from '@flopay/shared';
2
2
  export { dropThirdPartyOnlyError } from '@flopay/shared';
3
- export type { CheckoutRuntime, CheckoutRuntimeAutomaticPayment, CheckoutRuntimeEvent, CheckoutRuntimeEventName, CheckoutRuntimeHandle, CheckoutRuntimeLayout, CheckoutRuntimeMountOptions, CheckoutRuntimeSuppliedSession, CheckoutRuntimeUpdateOptions, } from './checkout-runtime/contract.js';
3
+ export type { CheckoutRuntime, CheckoutRuntimeAutomaticPayment, CheckoutRuntimeEvent, CheckoutRuntimeEventName, CheckoutRuntimeHandle, CheckoutRuntimeLayout, CheckoutRuntimeMountOptions, CheckoutRuntimeSetupEvent, CheckoutRuntimeSetupEventName, CheckoutRuntimeSetupHandle, CheckoutRuntimeSetupKind, CheckoutRuntimeSetupMountOptions, CheckoutRuntimeSetupUpdateOptions, CheckoutRuntimeSuppliedSession, CheckoutRuntimeUpdateOptions, } from './checkout-runtime/contract.js';
4
4
  export type { LoadCheckoutRuntimeOptions } from './checkout-runtime-loader.js';
5
5
  export { loadCheckoutRuntime } from './checkout-runtime-loader.js';
6
6
  export { createCheckoutSession, createCheckoutSessionWithRetries, } from './create-checkout-session.js';
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{a as W,b as G,c as J,d as se,e as Q,f as Ne,g as Be,h as X,i as ae,j as le,k as ce,l as de,m as ue,n as z,o as A,p as qe,q as ze,r as me,s as Z,t as pe}from"./chunk-5OENCIZW.mjs";import{dropThirdPartyOnlyError as tr}from"@flopay/shared";import{FloPayError as ye}from"@flopay/shared";var je="FloPayCheckoutRuntime",Ve=1e4,te=new Map;function Ke(e){return typeof e=="object"&&e!==null&&typeof e.mount=="function"}function ee(e){return new ye(e==="runtime_load_timeout"?"The checkout runtime did not load in time.":"The checkout runtime failed to load.","network_error",{code:e})}function $e(e,t){return new Promise((r,o)=>{let i=document.createElement("script"),s=!1,d=l=>{s||(s=!0,clearTimeout(n),i.removeEventListener("load",a),i.removeEventListener("error",c),l instanceof ye?(te.delete(e),i.remove(),o(l)):r(l))},a=()=>{let l=Reflect.get(globalThis,je);d(Ke(l)?l:ee("runtime_load_failed"))},c=()=>d(ee("runtime_load_failed")),n=setTimeout(()=>d(ee("runtime_load_timeout")),t);i.addEventListener("load",a),i.addEventListener("error",c),i.async=!0,i.src=e,document.head.appendChild(i)})}function He(e){let{runtimeUrl:t,timeoutMs:r=Ve}=e,o=te.get(t);if(o!==void 0)return o;let i=$e(t,r);return te.set(t,i),i}import{assertCaptureMethodEligible as Ye,buildProductPayload as We,classifyTelemetryFailure as Ge,FloPayError as U,foldIntoProducts as Je,IDEMPOTENCY_IN_PROGRESS_CODE as Qe,IDEMPOTENCY_KEY_HEADER as Xe,resolveIdempotencyKey as fe,resolveSessionCurrency as Ze,SDK_VERSION as ge,telemetryStatusClass as he,withTelemetryHttpDiagnostics as et}from"@flopay/shared";var oe=5,Ce=new WeakSet;function tt(e){(typeof e=="object"&&e!==null||typeof e=="function")&&Ce.add(e)}function rt(e){return(typeof e=="object"&&e!==null||typeof e=="function")&&Ce.has(e)}function ot(e,t){let r=t?.error,o=W(t?.code)??W(r?.code)??`http_${e}`,i=G(t?.message)??G(r?.message)??nt(o,e);return new U(i,"api_error",{code:o,statusCode:e})}function nt(e,t){switch(e){case"CouponLimitExceeded":return`Too many coupon codes \u2014 a checkout session accepts at most ${oe}.`;case"CouponCurrencyUnsupported":return"One of the applied coupons has no price configured for the cart currency.";default:return`Failed to create checkout session (HTTP ${t}).`}}async function ve(e,t,r){let{billingApiUrl:o,checkoutBaseUrl:i,items:s=[],subscriptions:d=[],products:a,account:c,successUrl:n,cancelUrl:l,checkoutMode:m="confirm",captureMethod:h,couponCodes:w=[],checkoutMetadata:p,tagsData:g,redirectParams:I={},setCookie:f=!0,clientId:x,currency:P,utmMetadata:T,idempotencyKey:O}=e,F=fe(O);if(w.length>oe)throw new U(`Too many coupon codes \u2014 a checkout session accepts at most ${oe}.`,"validation_error",{code:"CouponLimitExceeded",param:"couponCodes"});let k=a??Je(s,d);Ye({captureMethod:h,products:k});let _=Ze(P,s,d,k);if(!_)throw new U("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});let C={clientId:x,checkoutVersion:ge,successUrl:n,cancelUrl:l,currency:_,checkoutMode:m,products:k.map(v=>We(v,_)),accountData:{userId:c.userId,firstName:c.firstName??null,lastName:c.lastName??null,email:c.email,country:c.country??null,gender:c.gender??null,city:c.city??null,state:c.state??null,zip:c.zip??null,addressLine1:c.addressLine1??null,addressLine2:c.addressLine2??null},couponCodes:w};h==="manual"&&(C.captureMethod=h),p!==void 0&&(C.checkoutMetadata=p),g&&(C.tagsData=g),T&&T.length>0&&(C.utmMetadata=T);let q=`${o.replace(/\/+$/,"")}/v1/checkouts/sessions`,L={"Content-Type":"application/json"};F&&(L[Xe]=F);let b,E,N={method:"POST",headers:L,body:JSON.stringify(C),signal:t},S;try{r?.startAttempt(),S=await fetch(q,N)}catch(v){throw tt(v),v}try{r?.record(S.status)}catch{}b=S.status;try{E=await S.json()}catch{}if(b>=400)throw et(ot(b,E),S);if(b===201){let v=E?.data?.uuid,M=E?.data?.nonce;if(!v)throw new Error("Checkout session created but no UUID was returned by the billing API");if(!M)throw new U("Checkout session created but no `nonce` was returned by the billing API. Upgrade the billing service to TeamFloPay/backend#640 or later.","api_error",{code:"MissingCheckoutSessionToken"});(k.length>0||_)&&Q(v,{currency:_,products:k.map(u=>({code:u.code??u.providerItemId??u.providerPlanId,type:u.type,name:u.name??u.itemName??u.providerItemName??u.subscriptionName??u.providerPlanName??null,totalAmount:u.totalAmount,overrideAmount:u.overrideAmount,currency:u.currency??_}))});let y=new URL(`${i.replace(/\/+$/,"")}/secure`);y.searchParams.set("id",v);for(let[u,R]of Object.entries(I))y.searchParams.set(u,R);if(f&&typeof window<"u"&&typeof document<"u"){let u=JSON.stringify({origin_url:l}),R=window.location.hostname.split(".").slice(-2).join(".");document.cookie=`checkout_data=${encodeURIComponent(u)}; domain=.${R}; path=/; max-age=3600; SameSite=Lax; Secure;`,document.cookie=`flopay_checkout_token=${encodeURIComponent(M)}; domain=.${R}; path=/; max-age=3600; SameSite=Lax; Secure;`}return typeof window<"u"&&(window.location.href=y.toString()),{status:201,redirectUrl:y.toString(),nonce:M}}return b===204?(typeof window<"u"&&(window.location.href=n),{status:204}):{status:b}}async function it(e){let t=_e(e),r=we(t),o=J(e.timeoutMs);try{let i=await ve(e,o.signal,r);return r.commit(),be(t,i),i}catch(i){throw r.commit(),j(t,i),i}finally{o.clear(),D(t.reporter)}}function we(e){let t=!1,r=e.startedAt,o;return{startAttempt(){r=e.reporter.now()},record(i){o={status:i,durationMs:Math.max(0,e.reporter.now()-r),attempt:e.attempt}},commit(){if(t||!o)return;t=!0;let i=he(o.status);e.reporter.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:i,attempt:o.attempt}),e.reporter.performance({stage:"session_first_byte",durationMs:o.durationMs,durationMode:"machine",requestCategory:"session_create",statusClass:i,attempt:o.attempt})}}}function _e(e){let t=new A({billingApiUrl:e.billingApiUrl,sdkVersion:ge,enabled:e.telemetry!==!1}),r=t.now();return t.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"}),{reporter:t,startedAt:r,attempt:0}}function be(e,t){let r=he(t.status);e.reporter.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:r}),e.reporter.performance({stage:"session_create",durationMs:e.reporter.now()-e.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:r,attempt:e.attempt})}function j(e,t){let{reporter:r}=e,o=Ge(t,"CHECKOUT_SESSION_CREATE_FAILED");if(r.performance({stage:"session_create",durationMs:r.now()-e.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:o.statusClass,attempt:e.attempt}),t instanceof U&&t.type==="validation_error"){r.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"});return}if(o.statusClass==="4xx"){r.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create",statusClass:"4xx"});return}r.error({...o,stage:"session_create",requestCategory:"session_create"})}function D(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}async function st(e){let{maxRetries:t=2,...r}=e,o=_e(e),i=we(o);if(!Number.isFinite(t)||!Number.isInteger(t)||t<0||t>=3)throw o.reporter.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),D(o.reporter),new Error(`Number of retries must be an integer between 0 and ${2}`);let s={...r,idempotencyKey:fe(r.idempotencyKey)},d=J(r.timeoutMs),a;for(let c=0;c<=t;c++){o.attempt=c;try{let n=await ve(s,d.signal,i);return i.commit(),be(o,n),d.clear(),D(o.reporter),n}catch(n){a=n;let l=n instanceof Error&&n.name==="AbortError",m=rt(n),h=n instanceof U&&n.code===Qe;if((l||m||h)&&!d.signal.aborted&&c<t){o.reporter.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:c+1});try{await se(c,d.signal)}catch(w){throw i.commit(),j(o,w),d.clear(),D(o.reporter),w}continue}throw i.commit(),j(o,n),d.clear(),D(o.reporter),n}}throw i.commit(),j(o,a),d.clear(),D(o.reporter),a??new Error("Unknown error during checkout session creation")}import{classifyTelemetryFailure as at,FloPayError as V,resolveBillingApiUrl as Pe,SDK_VERSION as lt}from"@flopay/shared";var ke=Symbol.for("@flopay/js.telemetry.bridge.v1");function Se(e,t,r){let o=()=>t?.now()??r();Object.defineProperty(e,ke,{configurable:!1,enumerable:!1,writable:!1,value:{error:s=>t?.error(s),log:s=>t?.log(s),performance:s=>t?.performance(s),terminal:s=>t?.terminal(s),now:o,elapsed:s=>Math.max(0,o()-s),setCheckoutContext:s=>t?.setCheckoutContext(s),beginCheckout:(s={})=>t?.beginCheckout(s)??o(),disable:()=>t?.disable(),subscribe:s=>t?.subscribe(s)??(()=>{}),flush:()=>t?.flush()??Promise.resolve()}})}function Re(e){return e[ke]}var K=class{now(){return this.telemetryReporter?.now?.()??z()}constructor(t,r,o){this.provider=t,this.config=r,this.telemetryReporter=o??new A({billingApiUrl:Pe(r.billingApiUrl),sdkVersion:lt,enabled:r.telemetry!==!1}),Se(this,this.telemetryReporter,z)}cardCapture(t){return this.telemetryReporter?.log({name:"vault.capture.requested",stage:"vault_request",provider:"pcivault",paymentMethodCategory:"card"}),this.telemetryReporter?pe({sessionId:t?.sessionId,captureMethod:t?.captureMethod,sessionToken:t?.sessionToken,billingApiUrl:this.config.billingApiUrl,cardFieldsTimeoutMs:t?.cardFieldsTimeoutMs},this.telemetryReporter):new Z({sessionId:t?.sessionId,captureMethod:t?.captureMethod,sessionToken:t?.sessionToken,billingApiUrl:this.config.billingApiUrl,cardFieldsTimeoutMs:t?.cardFieldsTimeoutMs,telemetry:!1})}async retrieveSession(t,r){if(!t)throw new V("sessionId is required to retrieve a session.","validation_error",{param:"sessionId"});let o=await this.retrieveUnifiedSession(t,r);if(!o.data.session)throw new V("Session not found","api_error");return o.data.session}async retrieveUnifiedSession(t,r){if(!t)throw new V("sessionId is required.","validation_error",{param:"sessionId"});let o=Pe(r??this.config.billingApiUrl),i=this.now();this.telemetryReporter?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let s,d,a=n=>{if(s===void 0)return;let l=s,m=d;s=void 0,d=void 0,this.telemetryReporter?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:n,attempt:m}),this.telemetryReporter?.performance({stage:"session_first_byte",durationMs:l,durationMode:"machine",requestCategory:"session_read",statusClass:n,attempt:m})},c=me(o,{now:()=>this.telemetryReporter?.now()??z(),onFirstByte:(n,l)=>{s=n,d=l},onRetry:(n,l)=>{this.telemetryReporter?.log({name:"operation.retry",stage:n==="session_read"?"session_read":"processing",requestCategory:n,attempt:l})}});try{let n=await c.getUnifiedCheckoutSession(t);return a("2xx"),this.telemetryReporter?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:"2xx"}),this.telemetryReporter?.log({name:"checkout.data.ready",stage:"checkout_data_ready"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-i,durationMode:"machine",requestCategory:"session_read",statusClass:"2xx"}),n}catch(n){let l=at(n,n instanceof V&&n.code==="checkout_processing_timeout"?"REQUEST_TIMEOUT":"NETWORK_REQUEST_FAILED");throw a(l.statusClass),this.telemetryReporter?.error({...l,stage:"session_read",provider:"flo",paymentMethodCategory:"unknown"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-i,durationMode:"machine",requestCategory:"session_read",statusClass:l.statusClass}),n}}getRawProvider(){return this.provider.getRawProvider()}destroy(){this.telemetryReporter?.log({name:"checkout.unmount",stage:"unmount"}),this.telemetryReporter?.destroy(),this.provider.destroy()}};function Te(e,t,r){let o=K;return new o(e,t,r)}import{FloPayError as mt,resolveBillingApiUrl as ne,SDK_VERSION as xe}from"@flopay/shared";import{FloPayError as Ee}from"@flopay/shared";import{loadStripe as ct}from"@stripe/stripe-js";import{toStripeAppearance as dt,toStripeAppearanceTheme as ut}from"@flopay/shared";var Ae=new WeakSet;function Ie(e){return e instanceof Ee&&Ae.has(e)}var B=class{constructor(){this.name="stripe";this.stripe=null}async initialize(t){if(typeof window>"u")return;let r=await ct(t.publishableKey,{locale:t.locale??"auto"});if(!r){let o=new Ee("Failed to initialize Stripe. Check your publishable key.","authentication_error");throw Ae.add(o),o}this.stripe=r}getRawProvider(){return this.stripe}destroy(){this.stripe=null}};var Fe=new Map;function ie(e){return Array.isArray(e)?e.map(ie):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,ie(r)])):e}function pt(e,t){return JSON.stringify([e,ne(t?.billingApiUrl),t?.telemetry!==!1,t?.locale??"auto",t?.apiVersion??null,ie(t?.appearance??null)])}var $=new Map;async function yt(e,t){if(!e){let a=new A({billingApiUrl:ne(t?.billingApiUrl),sdkVersion:xe,enabled:t?.telemetry!==!1});throw a.error({errorCode:"CONFIGURATION_INVALID",stage:"sdk_initialize",paymentMethodCategory:"unknown"}),a.flush().catch(()=>{}).finally(()=>a.destroy()),new mt("A publishable key is required to initialize FloPay.","validation_error",{param:"publishableKey"})}let r=pt(e,t),o=Fe.get(r);if(o)return t?.telemetry!==!1&&Re(o)?.log({name:"sdk.cache.hit",stage:"sdk_initialize"}),o;let i=$.get(r);if(i)return i;let s={...t,publishableKey:e},d=(async()=>{let a=new A({billingApiUrl:ne(s.billingApiUrl),sdkVersion:xe,enabled:s.telemetry!==!1}),c=a.now();a.log({name:"sdk.initialize.started",stage:"sdk_initialize"}),a.log({name:"sdk.cache.miss",stage:"sdk_initialize"}),a.log({name:"provider.load.started",stage:"provider_load",provider:"stripe"});let n=new B,l=a.now();try{await n.initialize(s)}catch(w){throw a.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:Ie(w)?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"unknown"}),a.destroy(),w}let m=a.now();a.log({name:"provider.ready",stage:"provider_ready",provider:"stripe"}),a.log({name:"provider.availability.checked",stage:"provider_ready",provider:"stripe"}),a.log({name:"sdk.initialize.ready",stage:"sdk_initialize"}),a.performance({stage:"sdk_initialize",durationMs:m-c,durationMode:"machine",provider:"stripe"}),a.performance({stage:"provider_ready",durationMs:m-l,durationMode:"machine",provider:"stripe"});let h=Te(n,s,a);return Fe.set(r,h),h})();$.set(r,d);try{return await d}finally{$.get(r)===d&&$.delete(r)}}import{FloPayError as Y,THREE_DS_CHALLENGE_WINDOW_MS as De}from"@flopay/shared";var ft=4,gt=1e3,ht=1e3,Ct=15e3;function vt(e){let t=!!e?.gateways?.stripe,r=!!e?.gateways?.worldpayCorporateGateway;return t===r?"unknown":t?"stripe":"worldpay"}function wt(e,t,r){try{return typeof e?.beginThreeDsChallenge!="function"?void 0:e.beginThreeDsChallenge(t,{provider:vt(r)})}catch{return}}function H(e){return new Y("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function Ue(){return new Y("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function Oe(e){return e.replace(/\/+$/,"")}function _t(e){return e.status==="succeeded"||e.status==="authorized"||e.status==="declined"}function bt(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",r=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":case"authorized":case"pending":case"timeout":return{status:t,providerIntentId:r};case"declined":return{status:"declined",providerIntentId:r,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:r,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}async function Le(e){if(typeof document>"u"||typeof window>"u")throw new Y("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});let t=X(e.telemetry);t.record("handoff_planned");let r=ae(e.nextActionRedirectUrl);r==="missing"?t.record("action_missing",{reason:"missing_url"}):r==="invalid"&&t.record("action_invalid",{reason:"invalid_url"});let o=p=>{let g=le(p);if(g==="buyer_cancel"){t.record("cancel_requested",{reason:g,evidenceBasis:"signal_reason"}),t.terminal("cancel",{reason:g,evidenceBasis:"signal_reason"});return}t.record("abort_observed",{reason:g,evidenceBasis:"signal_reason"}),t.terminal("abort",{reason:g,evidenceBasis:"signal_reason"})},i=p=>{(p.status==="succeeded"||p.status==="authorized"||p.status==="declined"||p.status==="timeout")&&t.reconcile(p.status)};if(e.signal?.aborted)throw o(e.signal.reason),H();let s=`${Oe(e.billingApiUrl)}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,d=async()=>{let p=new AbortController,g=()=>p.abort();e.signal?.aborted?p.abort():e.signal?.addEventListener("abort",g);let I=window.setTimeout(()=>p.abort(),Ct);try{let f=await fetch(s,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json",...t.attemptId?{"x-flopay-challenge-attempt":t.attemptId}:{}},body:"{}",signal:p.signal});if(!f.ok)return{status:"unknown"};let x=await f.json().catch(()=>null),P=bt(x);return i(P),P}catch{return{status:"unknown"}}finally{window.clearTimeout(I),e.signal?.removeEventListener("abort",g)}},a,c=()=>e.pollCompletionEndpoint!==!1?d():(a??(a=d()),a),n=document.activeElement instanceof HTMLElement?document.activeElement:null,l=document.createElement("div");l.setAttribute("data-flopay-auto-3ds-overlay","1"),l.setAttribute("role","dialog"),l.setAttribute("aria-modal","true"),l.setAttribute("aria-label","Card authentication"),l.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let m=document.createElement("iframe");m.setAttribute("title","Card authentication"),m.setAttribute("allow","payment"),m.tabIndex=0,m.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";");let h=null;try{h=new URL(e.billingApiUrl,window.location.href).origin}catch{h=null}let w=ue(e.nextActionRedirectUrl);try{let p=await new Promise((g,I)=>{let f=!1,x=0,P=0,T=0,O=!1,F=!1,k=!1,_=0,C=()=>{window.clearTimeout(x),window.clearInterval(P),window.clearTimeout(T),window.removeEventListener("message",v),window.removeEventListener("pagehide",L),document.removeEventListener("securitypolicyviolation",b),m.removeEventListener("load",E),e.signal?.removeEventListener("abort",N)},q=async()=>{if(!(f||O)){O=!0;try{let y=await c();if(f||!_t(y))return;f=!0,C(),t.terminal("status_poll",{evidenceBasis:"server_status"}),g(y)}finally{O=!1}}},L=()=>{t.record("pagehide_observed",{evidenceBasis:"page_lifecycle_event"})},b=y=>{if(k)return;let u=de(y,w);u&&(k=!0,t.record("policy_violation",{reason:u,evidenceBasis:"parent_csp_event"}))},E=()=>{F||(F=!0,t.record("iframe_load",{evidenceBasis:"iframe_load_event"})),e.pollCompletionEndpoint!==!1&&(window.clearTimeout(T),T=window.setTimeout(()=>{q()},250))},N=()=>{f||(f=!0,C(),o(e.signal?.reason),I(H()))},S=y=>{f||_>=ft||(_+=1,t.record("return_rejected",{reason:y,evidenceBasis:"message_origin_check"}))},v=y=>{let u=y.data,R=!!u&&typeof u=="object"&&u.source==="flopay-vault-3ds-return";if(y.source!==m.contentWindow){R&&S("untrusted_source");return}if(h&&y.origin!==h){R&&S("untrusted_origin");return}R&&(f||(f=!0,C(),t.record("trusted_return",{evidenceBasis:"message_origin_check"}),t.terminal("trusted_return",{evidenceBasis:"message_origin_check"}),g(null)))};x=window.setTimeout(()=>{f||(f=!0,C(),F||t.record("load_unconfirmed",{evidenceBasis:"no_load_signal"}),t.record("timer_expired",{reason:"window_elapsed",evidenceBasis:"timer"}),t.terminal("timer",{reason:"window_elapsed",evidenceBasis:"timer"}),I(Ue()))},De),e.pollCompletionEndpoint!==!1&&(P=window.setInterval(()=>{q()},ht)),m.addEventListener("load",E),window.addEventListener("message",v),window.addEventListener("pagehide",L),document.addEventListener("securitypolicyviolation",b),e.signal?.addEventListener("abort",N),m.src=e.nextActionRedirectUrl,t.record("render_attempted");try{l.appendChild(m),document.body.appendChild(l)}catch(y){throw f=!0,C(),t.record("render_failed"),y}t.record("container_attached"),t.record("navigation_assigned");let M=ce(l);M&&t.record("container_visibility",{reason:M,evidenceBasis:"parent_computed_style"}),m.focus(),e.signal?.aborted&&N()});return p||await c()}finally{l.parentNode?.removeChild(l),t.record("teardown"),n?.isConnected&&n.focus()}}function Me(e,t){try{let r=t.data.session?.status;r==="complete"?e.reconcile("succeeded"):r==="authorized"&&e.reconcile("authorized")}catch{}}function kt(e){return new Y("Card was declined.","api_error",{code:e.declineReason??"authorization_declined",...e.gatewayDeclineReason?{declineCode:e.gatewayDeclineReason}:{}})}async function St(e,t){let r=`${Oe(e.billingApiUrl)}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/status`,o=new AbortController,i=new AbortController,s=()=>{o.abort(e.signal?.reason),i.abort(e.signal?.reason)};e.signal?.aborted?s():e.signal?.addEventListener("abort",s,{once:!0});let d=X(e.telemetry),a=Le({billingApiUrl:e.billingApiUrl,sessionId:e.sessionId,nonce:e.nonce,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:o.signal,pollCompletionEndpoint:!1,...e.telemetry?{telemetry:e.telemetry}:{}}),c=t.waitForCheckoutSessionCompletion(e.sessionId,{initialDelayMs:gt,nonce:e.nonce,statusUrl:r,continueAfterActionRequired:!0,timeoutMs:De+15e3,signal:i.signal,...d.attemptId?{challengeAttemptId:d.attemptId}:{}});c.catch(()=>{}),a.catch(()=>{});try{let n=await Promise.race([a,c]);if("data"in n)return d.terminal("status_poll",{evidenceBasis:"server_status"}),Me(d,n),n;if(n.status==="declined")throw(e.createDeclineError??kt)(n);if(n.status==="timeout")throw Ue();let l=await c;return Me(d,l),l}catch(n){throw e.signal?.aborted||n instanceof Error&&n.name==="AbortError"?H(n):n}finally{e.signal?.removeEventListener("abort",s),o.abort(),i.abort()}}export{K as FloPay,ze as PaymentAPI,Z as PciVaultCardCapture,qe as SESSION_CREATE_TELEMETRY,B as StripeAdapter,wt as beginSavedCardChallengeTelemetry,Q as cacheSessionDisplayData,Be as clearSessionDisplayData,St as completeSavedCardNextAction,it as createCheckoutSession,st as createCheckoutSessionWithRetries,H as createSavedCardActionAbortedError,tr as dropThirdPartyOnlyError,Ne as getSessionDisplayData,He as loadCheckoutRuntime,yt as loadFloPay,Le as runSavedCardChallenge,dt as toStripeAppearance,ut as toStripeAppearanceTheme};
1
+ import{a as W,b as G,c as J,d as se,e as Q,f as Ne,g as Be,h as X,i as ae,j as le,k as ce,l as de,m as ue,n as z,o as A,p as qe,q as ze,r as me,s as Z,t as pe}from"./chunk-5OENCIZW.mjs";import{dropThirdPartyOnlyError as tr}from"@flopay/shared";import{FloPayError as ye}from"@flopay/shared";var je="FloPayCheckoutRuntime",Ve=1e4,te=new Map;function Ke(e){return typeof e=="object"&&e!==null&&typeof e.mount=="function"}function ee(e){return new ye(e==="runtime_load_timeout"?"The checkout runtime did not load in time.":"The checkout runtime failed to load.","network_error",{code:e})}function $e(e,t){return new Promise((r,o)=>{let i=document.createElement("script"),s=!1,d=l=>{s||(s=!0,clearTimeout(n),i.removeEventListener("load",a),i.removeEventListener("error",c),l instanceof ye?(te.delete(e),i.remove(),o(l)):r(l))},a=()=>{let l=Reflect.get(globalThis,je);d(Ke(l)?l:ee("runtime_load_failed"))},c=()=>d(ee("runtime_load_failed")),n=setTimeout(()=>d(ee("runtime_load_timeout")),t);i.addEventListener("load",a),i.addEventListener("error",c),i.async=!0,i.src=e,document.head.appendChild(i)})}function He(e){let{runtimeUrl:t,timeoutMs:r=Ve}=e,o=te.get(t);if(o!==void 0)return o;let i=$e(t,r);return te.set(t,i),i}import{assertCaptureMethodEligible as Ye,buildProductPayload as We,classifyTelemetryFailure as Ge,FloPayError as U,foldIntoProducts as Je,IDEMPOTENCY_IN_PROGRESS_CODE as Qe,IDEMPOTENCY_KEY_HEADER as Xe,resolveIdempotencyKey as fe,resolveSessionCurrency as Ze,SDK_VERSION as ge,telemetryStatusClass as he,withTelemetryHttpDiagnostics as et}from"@flopay/shared";var oe=5,Ce=new WeakSet;function tt(e){(typeof e=="object"&&e!==null||typeof e=="function")&&Ce.add(e)}function rt(e){return(typeof e=="object"&&e!==null||typeof e=="function")&&Ce.has(e)}function ot(e,t){let r=t?.error,o=W(t?.code)??W(r?.code)??`http_${e}`,i=G(t?.message)??G(r?.message)??nt(o,e);return new U(i,"api_error",{code:o,statusCode:e})}function nt(e,t){switch(e){case"CouponLimitExceeded":return`Too many coupon codes \u2014 a checkout session accepts at most ${oe}.`;case"CouponCurrencyUnsupported":return"One of the applied coupons has no price configured for the cart currency.";default:return`Failed to create checkout session (HTTP ${t}).`}}async function ve(e,t,r){let{billingApiUrl:o,checkoutBaseUrl:i,items:s=[],subscriptions:d=[],products:a,account:c,successUrl:n,cancelUrl:l,checkoutMode:m="confirm",captureMethod:h,couponCodes:w=[],checkoutMetadata:p,tagsData:g,redirectParams:I={},setCookie:f=!0,clientId:x,currency:P,utmMetadata:E,idempotencyKey:O}=e,F=fe(O);if(w.length>oe)throw new U(`Too many coupon codes \u2014 a checkout session accepts at most ${oe}.`,"validation_error",{code:"CouponLimitExceeded",param:"couponCodes"});let k=a??Je(s,d);Ye({captureMethod:h,products:k});let _=Ze(P,s,d,k);if(!_)throw new U("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});let C={clientId:x,checkoutVersion:ge,successUrl:n,cancelUrl:l,currency:_,checkoutMode:m,products:k.map(v=>We(v,_)),accountData:{userId:c.userId,firstName:c.firstName??null,lastName:c.lastName??null,email:c.email,country:c.country??null,gender:c.gender??null,city:c.city??null,state:c.state??null,zip:c.zip??null,addressLine1:c.addressLine1??null,addressLine2:c.addressLine2??null},couponCodes:w};h==="manual"&&(C.captureMethod=h),p!==void 0&&(C.checkoutMetadata=p),g&&(C.tagsData=g),E&&E.length>0&&(C.utmMetadata=E);let q=`${o.replace(/\/+$/,"")}/v1/checkouts/sessions`,L={"Content-Type":"application/json"};F&&(L[Xe]=F);let b,T,N={method:"POST",headers:L,body:JSON.stringify(C),signal:t},S;try{r?.startAttempt(),S=await fetch(q,N)}catch(v){throw tt(v),v}try{r?.record(S.status)}catch{}b=S.status;try{T=await S.json()}catch{}if(b>=400)throw et(ot(b,T),S);if(b===201){let v=T?.data?.uuid,M=T?.data?.nonce;if(!v)throw new Error("Checkout session created but no UUID was returned by the billing API");if(!M)throw new U("Checkout session created but no `nonce` was returned by the billing API. Upgrade the billing service to TeamFloPay/backend#640 or later.","api_error",{code:"MissingCheckoutSessionToken"});(k.length>0||_)&&Q(v,{currency:_,products:k.map(u=>({code:u.code??u.providerItemId??u.providerPlanId,type:u.type,name:u.name??u.itemName??u.providerItemName??u.subscriptionName??u.providerPlanName??null,totalAmount:u.totalAmount,overrideAmount:u.overrideAmount,currency:u.currency??_}))});let y=new URL(`${i.replace(/\/+$/,"")}/secure`);y.searchParams.set("id",v);for(let[u,R]of Object.entries(I))y.searchParams.set(u,R);if(f&&typeof window<"u"&&typeof document<"u"){let u=JSON.stringify({origin_url:l}),R=window.location.hostname.split(".").slice(-2).join(".");document.cookie=`checkout_data=${encodeURIComponent(u)}; domain=.${R}; path=/; max-age=3600; SameSite=Lax; Secure;`,document.cookie=`flopay_checkout_token=${encodeURIComponent(M)}; domain=.${R}; path=/; max-age=3600; SameSite=Lax; Secure;`}return typeof window<"u"&&(window.location.href=y.toString()),{status:201,redirectUrl:y.toString(),nonce:M}}return b===204?(typeof window<"u"&&(window.location.href=n),{status:204}):{status:b}}async function it(e){let t=_e(e),r=we(t),o=J(e.timeoutMs);try{let i=await ve(e,o.signal,r);return r.commit(),be(t,i),i}catch(i){throw r.commit(),j(t,i),i}finally{o.clear(),D(t.reporter)}}function we(e){let t=!1,r=e.startedAt,o;return{startAttempt(){r=e.reporter.now()},record(i){o={status:i,durationMs:Math.max(0,e.reporter.now()-r),attempt:e.attempt}},commit(){if(t||!o)return;t=!0;let i=he(o.status);e.reporter.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:i,attempt:o.attempt}),e.reporter.performance({stage:"session_first_byte",durationMs:o.durationMs,durationMode:"machine",requestCategory:"session_create",statusClass:i,attempt:o.attempt})}}}function _e(e){let t=new A({billingApiUrl:e.billingApiUrl,sdkVersion:ge,enabled:e.telemetry!==!1}),r=t.now();return t.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"}),{reporter:t,startedAt:r,attempt:0}}function be(e,t){let r=he(t.status);e.reporter.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:r}),e.reporter.performance({stage:"session_create",durationMs:e.reporter.now()-e.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:r,attempt:e.attempt})}function j(e,t){let{reporter:r}=e,o=Ge(t,"CHECKOUT_SESSION_CREATE_FAILED");if(r.performance({stage:"session_create",durationMs:r.now()-e.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:o.statusClass,attempt:e.attempt}),t instanceof U&&t.type==="validation_error"){r.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"});return}if(o.statusClass==="4xx"){r.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create",statusClass:"4xx"});return}r.error({...o,stage:"session_create",requestCategory:"session_create"})}function D(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}async function st(e){let{maxRetries:t=2,...r}=e,o=_e(e),i=we(o);if(!Number.isFinite(t)||!Number.isInteger(t)||t<0||t>=3)throw o.reporter.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),D(o.reporter),new Error(`Number of retries must be an integer between 0 and ${2}`);let s={...r,idempotencyKey:fe(r.idempotencyKey)},d=J(r.timeoutMs),a;for(let c=0;c<=t;c++){o.attempt=c;try{let n=await ve(s,d.signal,i);return i.commit(),be(o,n),d.clear(),D(o.reporter),n}catch(n){a=n;let l=n instanceof Error&&n.name==="AbortError",m=rt(n),h=n instanceof U&&n.code===Qe;if((l||m||h)&&!d.signal.aborted&&c<t){o.reporter.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:c+1});try{await se(c,d.signal)}catch(w){throw i.commit(),j(o,w),d.clear(),D(o.reporter),w}continue}throw i.commit(),j(o,n),d.clear(),D(o.reporter),n}}throw i.commit(),j(o,a),d.clear(),D(o.reporter),a??new Error("Unknown error during checkout session creation")}import{classifyTelemetryFailure as at,FloPayError as V,resolveBillingApiUrl as Pe,SDK_VERSION as lt}from"@flopay/shared";var ke=Symbol.for("@flopay/js.telemetry.bridge.v1");function Se(e,t,r){let o=()=>t?.now()??r();Object.defineProperty(e,ke,{configurable:!1,enumerable:!1,writable:!1,value:{error:s=>t?.error(s),log:s=>t?.log(s),performance:s=>t?.performance(s),terminal:s=>t?.terminal(s),now:o,elapsed:s=>Math.max(0,o()-s),setCheckoutContext:s=>t?.setCheckoutContext(s),beginCheckout:(s={})=>t?.beginCheckout(s)??o(),disable:()=>t?.disable(),subscribe:s=>t?.subscribe(s)??(()=>{}),flush:()=>t?.flush()??Promise.resolve()}})}function Re(e){return e[ke]}var K=class{now(){return this.telemetryReporter?.now?.()??z()}constructor(t,r,o){this.provider=t,this.config=r,this.telemetryReporter=o??new A({billingApiUrl:Pe(r.billingApiUrl),sdkVersion:lt,enabled:r.telemetry!==!1}),Se(this,this.telemetryReporter,z)}cardCapture(t){return this.telemetryReporter?.log({name:"vault.capture.requested",stage:"vault_request",provider:"pcivault",paymentMethodCategory:"card"}),this.telemetryReporter?pe({sessionId:t?.sessionId,captureMethod:t?.captureMethod,sessionToken:t?.sessionToken,billingApiUrl:this.config.billingApiUrl,cardFieldsTimeoutMs:t?.cardFieldsTimeoutMs},this.telemetryReporter):new Z({sessionId:t?.sessionId,captureMethod:t?.captureMethod,sessionToken:t?.sessionToken,billingApiUrl:this.config.billingApiUrl,cardFieldsTimeoutMs:t?.cardFieldsTimeoutMs,telemetry:!1})}async retrieveSession(t,r){if(!t)throw new V("sessionId is required to retrieve a session.","validation_error",{param:"sessionId"});let o=await this.retrieveUnifiedSession(t,r);if(!o.data.session)throw new V("Session not found","api_error");return o.data.session}async retrieveUnifiedSession(t,r){if(!t)throw new V("sessionId is required.","validation_error",{param:"sessionId"});let o=Pe(r??this.config.billingApiUrl),i=this.now();this.telemetryReporter?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let s,d,a=n=>{if(s===void 0)return;let l=s,m=d;s=void 0,d=void 0,this.telemetryReporter?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:n,attempt:m}),this.telemetryReporter?.performance({stage:"session_first_byte",durationMs:l,durationMode:"machine",requestCategory:"session_read",statusClass:n,attempt:m})},c=me(o,{now:()=>this.telemetryReporter?.now()??z(),onFirstByte:(n,l)=>{s=n,d=l},onRetry:(n,l)=>{this.telemetryReporter?.log({name:"operation.retry",stage:n==="session_read"?"session_read":"processing",requestCategory:n,attempt:l})}});try{let n=await c.getUnifiedCheckoutSession(t);return a("2xx"),this.telemetryReporter?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:"2xx"}),this.telemetryReporter?.log({name:"checkout.data.ready",stage:"checkout_data_ready"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-i,durationMode:"machine",requestCategory:"session_read",statusClass:"2xx"}),n}catch(n){let l=at(n,n instanceof V&&n.code==="checkout_processing_timeout"?"REQUEST_TIMEOUT":"NETWORK_REQUEST_FAILED");throw a(l.statusClass),this.telemetryReporter?.error({...l,stage:"session_read",provider:"flo",paymentMethodCategory:"unknown"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-i,durationMode:"machine",requestCategory:"session_read",statusClass:l.statusClass}),n}}getRawProvider(){return this.provider.getRawProvider()}destroy(){this.telemetryReporter?.log({name:"checkout.unmount",stage:"unmount"}),this.telemetryReporter?.destroy(),this.provider.destroy()}};function Ee(e,t,r){let o=K;return new o(e,t,r)}import{FloPayError as mt,resolveBillingApiUrl as ne,SDK_VERSION as xe}from"@flopay/shared";import{FloPayError as Te}from"@flopay/shared";import{loadStripe as ct}from"@stripe/stripe-js";import{toStripeAppearance as dt,toStripeAppearanceTheme as ut}from"@flopay/shared";var Ae=new WeakSet;function Ie(e){return e instanceof Te&&Ae.has(e)}var B=class{constructor(){this.name="stripe";this.stripe=null}async initialize(t){if(typeof window>"u")return;let r=await ct(t.publishableKey,{locale:t.locale??"auto"});if(!r){let o=new Te("Failed to initialize Stripe. Check your publishable key.","authentication_error");throw Ae.add(o),o}this.stripe=r}getRawProvider(){return this.stripe}destroy(){this.stripe=null}};var Fe=new Map;function ie(e){return Array.isArray(e)?e.map(ie):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,ie(r)])):e}function pt(e,t){return JSON.stringify([e,ne(t?.billingApiUrl),t?.telemetry!==!1,t?.locale??"auto",t?.apiVersion??null,ie(t?.appearance??null)])}var $=new Map;async function yt(e,t){if(!e){let a=new A({billingApiUrl:ne(t?.billingApiUrl),sdkVersion:xe,enabled:t?.telemetry!==!1});throw a.error({errorCode:"CONFIGURATION_INVALID",stage:"sdk_initialize",paymentMethodCategory:"unknown"}),a.flush().catch(()=>{}).finally(()=>a.destroy()),new mt("A publishable key is required to initialize FloPay.","validation_error",{param:"publishableKey"})}let r=pt(e,t),o=Fe.get(r);if(o)return t?.telemetry!==!1&&Re(o)?.log({name:"sdk.cache.hit",stage:"sdk_initialize"}),o;let i=$.get(r);if(i)return i;let s={...t,publishableKey:e},d=(async()=>{let a=new A({billingApiUrl:ne(s.billingApiUrl),sdkVersion:xe,enabled:s.telemetry!==!1}),c=a.now();a.log({name:"sdk.initialize.started",stage:"sdk_initialize"}),a.log({name:"sdk.cache.miss",stage:"sdk_initialize"}),a.log({name:"provider.load.started",stage:"provider_load",provider:"stripe"});let n=new B,l=a.now();try{await n.initialize(s)}catch(w){throw a.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:Ie(w)?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"unknown"}),a.destroy(),w}let m=a.now();a.log({name:"provider.ready",stage:"provider_ready",provider:"stripe"}),a.log({name:"provider.availability.checked",stage:"provider_ready",provider:"stripe"}),a.log({name:"sdk.initialize.ready",stage:"sdk_initialize"}),a.performance({stage:"sdk_initialize",durationMs:m-c,durationMode:"machine",provider:"stripe"}),a.performance({stage:"provider_ready",durationMs:m-l,durationMode:"machine",provider:"stripe"});let h=Ee(n,s,a);return Fe.set(r,h),h})();$.set(r,d);try{return await d}finally{$.get(r)===d&&$.delete(r)}}import{FloPayError as Y,THREE_DS_CHALLENGE_WINDOW_MS as De}from"@flopay/shared";var ft=4,gt=1e3,ht=1e3,Ct=15e3;function vt(e){let t=!!e?.gateways?.stripe,r=!!e?.gateways?.worldpayCorporateGateway;return t===r?"unknown":t?"stripe":"worldpay"}function wt(e,t,r){try{return typeof e?.beginThreeDsChallenge!="function"?void 0:e.beginThreeDsChallenge(t,{provider:vt(r)})}catch{return}}function H(e){return new Y("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function Ue(){return new Y("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function Oe(e){return e.replace(/\/+$/,"")}function _t(e){return e.status==="succeeded"||e.status==="authorized"||e.status==="declined"}function bt(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",r=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":case"authorized":case"pending":case"timeout":return{status:t,providerIntentId:r};case"declined":return{status:"declined",providerIntentId:r,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:r,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}async function Le(e){if(typeof document>"u"||typeof window>"u")throw new Y("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});let t=X(e.telemetry);t.record("handoff_planned");let r=ae(e.nextActionRedirectUrl);r==="missing"?t.record("action_missing",{reason:"missing_url"}):r==="invalid"&&t.record("action_invalid",{reason:"invalid_url"});let o=p=>{let g=le(p);if(g==="buyer_cancel"){t.record("cancel_requested",{reason:g,evidenceBasis:"signal_reason"}),t.terminal("cancel",{reason:g,evidenceBasis:"signal_reason"});return}t.record("abort_observed",{reason:g,evidenceBasis:"signal_reason"}),t.terminal("abort",{reason:g,evidenceBasis:"signal_reason"})},i=p=>{(p.status==="succeeded"||p.status==="authorized"||p.status==="declined"||p.status==="timeout")&&t.reconcile(p.status)};if(e.signal?.aborted)throw o(e.signal.reason),H();let s=`${Oe(e.billingApiUrl)}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,d=async()=>{let p=new AbortController,g=()=>p.abort();e.signal?.aborted?p.abort():e.signal?.addEventListener("abort",g);let I=window.setTimeout(()=>p.abort(),Ct);try{let f=await fetch(s,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json",...t.attemptId?{"x-flopay-challenge-attempt":t.attemptId}:{}},body:"{}",signal:p.signal});if(!f.ok)return{status:"unknown"};let x=await f.json().catch(()=>null),P=bt(x);return i(P),P}catch{return{status:"unknown"}}finally{window.clearTimeout(I),e.signal?.removeEventListener("abort",g)}},a,c=()=>e.pollCompletionEndpoint!==!1?d():(a??(a=d()),a),n=document.activeElement instanceof HTMLElement?document.activeElement:null,l=document.createElement("div");l.setAttribute("data-flopay-auto-3ds-overlay","1"),l.setAttribute("role","dialog"),l.setAttribute("aria-modal","true"),l.setAttribute("aria-label","Card authentication"),l.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let m=document.createElement("iframe");m.setAttribute("title","Card authentication"),m.setAttribute("allow","payment"),m.tabIndex=0,m.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";");let h=null;try{h=new URL(e.billingApiUrl,window.location.href).origin}catch{h=null}let w=ue(e.nextActionRedirectUrl);try{let p=await new Promise((g,I)=>{let f=!1,x=0,P=0,E=0,O=!1,F=!1,k=!1,_=0,C=()=>{window.clearTimeout(x),window.clearInterval(P),window.clearTimeout(E),window.removeEventListener("message",v),window.removeEventListener("pagehide",L),document.removeEventListener("securitypolicyviolation",b),m.removeEventListener("load",T),e.signal?.removeEventListener("abort",N)},q=async()=>{if(!(f||O)){O=!0;try{let y=await c();if(f||!_t(y))return;f=!0,C(),t.terminal("status_poll",{evidenceBasis:"server_status"}),g(y)}finally{O=!1}}},L=()=>{t.record("pagehide_observed",{evidenceBasis:"page_lifecycle_event"})},b=y=>{if(k)return;let u=de(y,w);u&&(k=!0,t.record("policy_violation",{reason:u,evidenceBasis:"parent_csp_event"}))},T=()=>{F||(F=!0,t.record("iframe_load",{evidenceBasis:"iframe_load_event"})),e.pollCompletionEndpoint!==!1&&(window.clearTimeout(E),E=window.setTimeout(()=>{q()},250))},N=()=>{f||(f=!0,C(),o(e.signal?.reason),I(H()))},S=y=>{f||_>=ft||(_+=1,t.record("return_rejected",{reason:y,evidenceBasis:"message_origin_check"}))},v=y=>{let u=y.data,R=!!u&&typeof u=="object"&&u.source==="flopay-vault-3ds-return";if(y.source!==m.contentWindow){R&&S("untrusted_source");return}if(h&&y.origin!==h){R&&S("untrusted_origin");return}R&&(f||(f=!0,C(),t.record("trusted_return",{evidenceBasis:"message_origin_check"}),t.terminal("trusted_return",{evidenceBasis:"message_origin_check"}),g(null)))};x=window.setTimeout(()=>{f||(f=!0,C(),F||t.record("load_unconfirmed",{evidenceBasis:"no_load_signal"}),t.record("timer_expired",{reason:"window_elapsed",evidenceBasis:"timer"}),t.terminal("timer",{reason:"window_elapsed",evidenceBasis:"timer"}),I(Ue()))},De),e.pollCompletionEndpoint!==!1&&(P=window.setInterval(()=>{q()},ht)),m.addEventListener("load",T),window.addEventListener("message",v),window.addEventListener("pagehide",L),document.addEventListener("securitypolicyviolation",b),e.signal?.addEventListener("abort",N),m.src=e.nextActionRedirectUrl,t.record("render_attempted");try{l.appendChild(m),document.body.appendChild(l)}catch(y){throw f=!0,C(),t.record("render_failed"),y}t.record("container_attached"),t.record("navigation_assigned");let M=ce(l);M&&t.record("container_visibility",{reason:M,evidenceBasis:"parent_computed_style"}),m.focus(),e.signal?.aborted&&N()});return p||await c()}finally{l.parentNode?.removeChild(l),t.record("teardown"),n?.isConnected&&n.focus()}}function Me(e,t){try{let r=t.data.session?.status;r==="complete"?e.reconcile("succeeded"):r==="authorized"&&e.reconcile("authorized")}catch{}}function kt(e){return new Y("Card was declined.","api_error",{code:e.declineReason??"authorization_declined",...e.gatewayDeclineReason?{declineCode:e.gatewayDeclineReason}:{}})}async function St(e,t){let r=`${Oe(e.billingApiUrl)}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/status`,o=new AbortController,i=new AbortController,s=()=>{o.abort(e.signal?.reason),i.abort(e.signal?.reason)};e.signal?.aborted?s():e.signal?.addEventListener("abort",s,{once:!0});let d=X(e.telemetry),a=Le({billingApiUrl:e.billingApiUrl,sessionId:e.sessionId,nonce:e.nonce,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:o.signal,pollCompletionEndpoint:!1,...e.telemetry?{telemetry:e.telemetry}:{}}),c=t.waitForCheckoutSessionCompletion(e.sessionId,{initialDelayMs:gt,nonce:e.nonce,statusUrl:r,continueAfterActionRequired:!0,timeoutMs:De+15e3,signal:i.signal,...d.attemptId?{challengeAttemptId:d.attemptId}:{}});c.catch(()=>{}),a.catch(()=>{});try{let n=await Promise.race([a,c]);if("data"in n)return d.terminal("status_poll",{evidenceBasis:"server_status"}),Me(d,n),n;if(n.status==="declined")throw(e.createDeclineError??kt)(n);if(n.status==="timeout")throw Ue();let l=await c;return Me(d,l),l}catch(n){throw e.signal?.aborted||n instanceof Error&&n.name==="AbortError"?H(n):n}finally{e.signal?.removeEventListener("abort",s),o.abort(),i.abort()}}export{K as FloPay,ze as PaymentAPI,Z as PciVaultCardCapture,qe as SESSION_CREATE_TELEMETRY,B as StripeAdapter,wt as beginSavedCardChallengeTelemetry,Q as cacheSessionDisplayData,Be as clearSessionDisplayData,St as completeSavedCardNextAction,it as createCheckoutSession,st as createCheckoutSessionWithRetries,H as createSavedCardActionAbortedError,tr as dropThirdPartyOnlyError,Ne as getSessionDisplayData,He as loadCheckoutRuntime,yt as loadFloPay,Le as runSavedCardChallenge,dt as toStripeAppearance,ut as toStripeAppearanceTheme};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flopay/js",
3
- "version": "1.20.8",
3
+ "version": "1.20.10",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "publishConfig": {
@@ -31,10 +31,11 @@
31
31
  "dist"
32
32
  ],
33
33
  "dependencies": {
34
- "@flopay/shared": "1.20.8",
34
+ "@flopay/shared": "1.20.10",
35
35
  "@stripe/stripe-js": "^10.3.0"
36
36
  },
37
37
  "devDependencies": {
38
+ "@flopay/ui": "1.20.10",
38
39
  "jsdom": "^29.1.1",
39
40
  "tsup": "^9.0.0",
40
41
  "typescript": "^7.0.2",