@flopay/js 1.20.6 → 1.20.8
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.
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { CheckoutRuntimeAutomaticPayment, CheckoutRuntimeEvent, CheckoutRuntimeMountOptions } from './contract.js';
|
|
2
|
+
/** The session fields the saved payment reads. */
|
|
3
|
+
export interface SavedPaymentSession {
|
|
4
|
+
id: string;
|
|
5
|
+
nonce?: string;
|
|
6
|
+
status?: string;
|
|
7
|
+
}
|
|
8
|
+
/** A session the API returned, with its record and the whole response body. */
|
|
9
|
+
export interface AcquiredSession<S extends SavedPaymentSession> {
|
|
10
|
+
session: S;
|
|
11
|
+
/** The session record (`data`), as the API answered it. */
|
|
12
|
+
record: Record<string, unknown>;
|
|
13
|
+
/** The response body: a create response carries the server's auto-processing beside `data`. */
|
|
14
|
+
body: Record<string, unknown>;
|
|
15
|
+
}
|
|
16
|
+
/** What the runtime's mount gives the saved payment: its page, its API and its full checkout. */
|
|
17
|
+
export interface AutomaticPaymentHost<S extends SavedPaymentSession> {
|
|
18
|
+
container: HTMLElement;
|
|
19
|
+
apiHost: string;
|
|
20
|
+
options: CheckoutRuntimeMountOptions & {
|
|
21
|
+
automaticPayment: CheckoutRuntimeAutomaticPayment;
|
|
22
|
+
};
|
|
23
|
+
relay: (event: CheckoutRuntimeEvent) => void;
|
|
24
|
+
label: string;
|
|
25
|
+
readSession: (sessionId: string, nonce: string | undefined) => Promise<AcquiredSession<S>>;
|
|
26
|
+
createSession: (body: Record<string, unknown>) => Promise<AcquiredSession<S>>;
|
|
27
|
+
/** The session the journey now runs against (the overlay and telemetry name it). */
|
|
28
|
+
adoptSession: (session: S) => void;
|
|
29
|
+
/** Shows the challenge overlay and returns its frame; `onClose` runs if the buyer closes it. */
|
|
30
|
+
showChallenge: (url: string, onClose: () => void) => HTMLIFrameElement | null;
|
|
31
|
+
hideChallenge: () => void;
|
|
32
|
+
/** Mounts the full checkout for the same session and token. */
|
|
33
|
+
fallBack: (session: S, recovery: Record<string, unknown>) => void;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Mounts the hosted pay control in the container and runs the saved payment when the buyer
|
|
37
|
+
* clicks it. Returns the teardown: it aborts a pending supplier, ends a running challenge and
|
|
38
|
+
* silences every late answer.
|
|
39
|
+
*/
|
|
40
|
+
export declare function mountAutomaticPayment<S extends SavedPaymentSession>(host: AutomaticPaymentHost<S>): {
|
|
41
|
+
destroy(): void;
|
|
42
|
+
};
|
|
@@ -38,7 +38,15 @@ export interface CheckoutRuntimeMountOptions {
|
|
|
38
38
|
* presentation. The runtime never sends or looks up a buyer country.
|
|
39
39
|
*/
|
|
40
40
|
paymentMethodLayout?: PaymentMethodLayoutRules;
|
|
41
|
+
/**
|
|
42
|
+
* The checkout layout the merchant chose, as in 1.x (contract 2.2.0): `default` keeps the
|
|
43
|
+
* card form in view, `buttons` lets the layout rules put it behind "More payment options".
|
|
44
|
+
* Left out, the runtime uses `default`. A new layout is a new mount.
|
|
45
|
+
*/
|
|
46
|
+
layout?: CheckoutRuntimeLayout;
|
|
41
47
|
}
|
|
48
|
+
/** The checkout layouts a merchant chooses from, as in 1.x. */
|
|
49
|
+
export type CheckoutRuntimeLayout = 'default' | 'buttons';
|
|
42
50
|
/**
|
|
43
51
|
* The options a mounted checkout accepts after it is mounted. As with `appearance` and
|
|
44
52
|
* `strings`, leaving `paymentMethodLayout` out (or `undefined`) keeps the current layout; new
|
|
@@ -71,3 +79,33 @@ export interface CheckoutRuntimeConfig {
|
|
|
71
79
|
apiHost: string;
|
|
72
80
|
onTelemetry?: (event: CheckoutRuntimeTelemetryEvent) => void;
|
|
73
81
|
}
|
|
82
|
+
/** A session the merchant's server minted for one saved payment, and its session-bound token. */
|
|
83
|
+
export interface CheckoutRuntimeSuppliedSession {
|
|
84
|
+
sessionId: string;
|
|
85
|
+
nonce: string;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Automatic or confirm saved payment (contract 2.3.0), as the 1.x automatic payment button ran
|
|
89
|
+
* it. The runtime shows the pay control in the container and does nothing until the buyer
|
|
90
|
+
* clicks it. It then takes the session from `sessionId`/`nonce`, creates `createSession`, or
|
|
91
|
+
* calls `getSession`, and runs the saved payment: a session the server already completed or
|
|
92
|
+
* attempted is not paid again, a card challenge runs in the runtime's overlay, a recoverable
|
|
93
|
+
* failure opens the full checkout for the same session, and an unknown processing outcome stays
|
|
94
|
+
* pending with no second chance to pay.
|
|
95
|
+
*/
|
|
96
|
+
export interface CheckoutRuntimeAutomaticPayment {
|
|
97
|
+
/** `confirm` is the 1.x confirmation trigger; both modes pay only on the buyer's click. */
|
|
98
|
+
mode: 'automatic' | 'confirm';
|
|
99
|
+
/**
|
|
100
|
+
* Called in the merchant's page at click time, never sent to a frame. It has 15 seconds;
|
|
101
|
+
* the runtime aborts `signal` then, or when the checkout unmounts. Read at click time, so a
|
|
102
|
+
* wrapper may hand over a property that always returns the merchant's current function.
|
|
103
|
+
*/
|
|
104
|
+
getSession?: (options: {
|
|
105
|
+
signal: AbortSignal;
|
|
106
|
+
}) => Promise<CheckoutRuntimeSuppliedSession>;
|
|
107
|
+
}
|
|
108
|
+
/** The saved-payment mount option, added in contract 2.3.0. */
|
|
109
|
+
export interface CheckoutRuntimeMountOptions {
|
|
110
|
+
automaticPayment?: CheckoutRuntimeAutomaticPayment;
|
|
111
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import type { PaymentMethodGroupLayout } from '@flopay/shared';
|
|
2
|
+
import { FloPayError } from '@flopay/shared';
|
|
3
|
+
import type { CheckoutRuntimeEvent, CheckoutRuntimeLayout } from './checkout-runtime/contract.js';
|
|
4
|
+
type JsonRecord = Record<string, unknown>;
|
|
5
|
+
export declare function isCompleteStatus(status: unknown): boolean;
|
|
6
|
+
/**
|
|
7
|
+
* 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
|
+
*/
|
|
10
|
+
export declare function fullCheckoutRecovers(method: string | undefined): boolean;
|
|
11
|
+
/**
|
|
12
|
+
* 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
|
+
*/
|
|
16
|
+
export declare function reapprovalFailure(attempt: Record<string, unknown>): Record<string, unknown> | null;
|
|
17
|
+
/** One merchant outcome per payment: nothing reaches the merchant once the session is paid. */
|
|
18
|
+
export interface Outcomes {
|
|
19
|
+
readonly paid: boolean;
|
|
20
|
+
complete(payload: JsonRecord): void;
|
|
21
|
+
decline(payload: JsonRecord): void;
|
|
22
|
+
cancel(payload: JsonRecord): void;
|
|
23
|
+
error(error: FloPayError): void;
|
|
24
|
+
}
|
|
25
|
+
export declare function createOutcomes(relay: (event: CheckoutRuntimeEvent) => void, active: () => boolean): Outcomes;
|
|
26
|
+
/** The session the payment methods pay into, and the token that authorises it. */
|
|
27
|
+
export interface PaymentMethodsSession {
|
|
28
|
+
id: string;
|
|
29
|
+
token: string;
|
|
30
|
+
currency?: string;
|
|
31
|
+
amount?: number;
|
|
32
|
+
gateways?: JsonRecord;
|
|
33
|
+
}
|
|
34
|
+
/** A buyer the provider's redirect brought back to this page, read once at mount. */
|
|
35
|
+
export interface RedirectReturn {
|
|
36
|
+
redirectStatus: string | null;
|
|
37
|
+
/** The session this browser left from, saved before the redirect, when it matches. */
|
|
38
|
+
resume: {
|
|
39
|
+
sessionId?: string;
|
|
40
|
+
nonce?: string;
|
|
41
|
+
} | null;
|
|
42
|
+
}
|
|
43
|
+
export declare function readRedirectReturn(): RedirectReturn | null;
|
|
44
|
+
/**
|
|
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`.
|
|
48
|
+
*/
|
|
49
|
+
export declare function settleRedirectReturn(redirect: RedirectReturn, context: {
|
|
50
|
+
apiHost: string;
|
|
51
|
+
session: PaymentMethodsSession;
|
|
52
|
+
status: string | undefined;
|
|
53
|
+
outcomes: Outcomes;
|
|
54
|
+
active: () => boolean;
|
|
55
|
+
}): void;
|
|
56
|
+
export interface PaymentMethodsContext {
|
|
57
|
+
container: HTMLElement;
|
|
58
|
+
/** The card frame, which stands for the `card` group. */
|
|
59
|
+
cardNode: HTMLElement;
|
|
60
|
+
apiHost: string;
|
|
61
|
+
session: PaymentMethodsSession;
|
|
62
|
+
layout: CheckoutRuntimeLayout;
|
|
63
|
+
outcomes: Outcomes;
|
|
64
|
+
/** Settles once the first layout answer is in, or will not come. */
|
|
65
|
+
layoutReady: Promise<unknown>;
|
|
66
|
+
/** The resolved layout, when the API has already answered. */
|
|
67
|
+
initialLayout?: PaymentMethodGroupLayout;
|
|
68
|
+
strings: () => Record<string, string> | undefined;
|
|
69
|
+
}
|
|
70
|
+
export interface PaymentMethodsSurface {
|
|
71
|
+
setLayout(layout: PaymentMethodGroupLayout): void;
|
|
72
|
+
destroy(): void;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
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.
|
|
79
|
+
*/
|
|
80
|
+
export declare function mountPaymentMethods(context: PaymentMethodsContext): PaymentMethodsSurface;
|
|
81
|
+
export {};
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var xe=Object.defineProperty;var Vt=Object.getOwnPropertyDescriptor;var zt=Object.getOwnPropertyNames;var jt=Object.prototype.hasOwnProperty;var Ht=(r,e)=>{for(var t in e)xe(r,t,{get:e[t],enumerable:!0})},Kt=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of zt(e))!jt.call(r,i)&&i!==t&&xe(r,i,{get:()=>e[i],enumerable:!(n=Vt(e,i))||n.enumerable});return r};var $t=r=>Kt(xe({},"__esModule",{value:!0}),r);var Sn={};Ht(Sn,{FloPay:()=>ye,PaymentAPI:()=>Q,PciVaultCardCapture:()=>X,SESSION_CREATE_TELEMETRY:()=>ze,StripeAdapter:()=>ie,beginSavedCardChallengeTelemetry:()=>Ut,cacheSessionDisplayData:()=>W,clearSessionDisplayData:()=>Te,completeSavedCardNextAction:()=>Nt,createCheckoutSession:()=>nt,createCheckoutSessionWithRetries:()=>at,createSavedCardActionAbortedError:()=>ge,dropThirdPartyOnlyError:()=>Bt.dropThirdPartyOnlyError,getSessionDisplayData:()=>ve,loadCheckoutRuntime:()=>Ge,loadFloPay:()=>xt,runSavedCardChallenge:()=>$e,toStripeAppearance:()=>oe.toStripeAppearance,toStripeAppearanceTheme:()=>oe.toStripeAppearanceTheme});module.exports=$t(Sn);var Bt=require("@flopay/shared");var Le=require("@flopay/shared"),Gt="FloPayCheckoutRuntime",Yt=1e4,Ue=new Map;function Wt(r){return typeof r=="object"&&r!==null&&typeof r.mount=="function"}function Oe(r){return new Le.FloPayError(r==="runtime_load_timeout"?"The checkout runtime did not load in time.":"The checkout runtime failed to load.","network_error",{code:r})}function Jt(r,e){return new Promise((t,n)=>{let i=document.createElement("script"),o=!1,s=u=>{o||(o=!0,clearTimeout(c),i.removeEventListener("load",a),i.removeEventListener("error",l),u instanceof Le.FloPayError?(Ue.delete(r),i.remove(),n(u)):t(u))},a=()=>{let u=Reflect.get(globalThis,Gt);s(Wt(u)?u:Oe("runtime_load_failed"))},l=()=>s(Oe("runtime_load_failed")),c=setTimeout(()=>s(Oe("runtime_load_timeout")),e);i.addEventListener("load",a),i.addEventListener("error",l),i.async=!0,i.src=r,document.head.appendChild(i)})}function Ge(r){let{runtimeUrl:e,timeoutMs:t=Yt}=r,n=Ue.get(e);if(n!==void 0)return n;let i=Jt(e,t);return Ue.set(e,i),i}var T=require("@flopay/shared");function le(r){return typeof r=="string"&&r.trim()?r:void 0}function ce(r){if(typeof r=="string")return r.trim()?r:void 0;if(Array.isArray(r))return r.filter(t=>typeof t=="string"&&t.trim().length>0).join("; ")||void 0}function L(r=12e3){let e=Number.isFinite(r)&&r>=0?r:12e3,t=new AbortController,n=setTimeout(()=>t.abort(),e);return{signal:t.signal,clear:()=>clearTimeout(n)}}function Qt(){return Object.assign(new Error("The operation was aborted."),{name:"AbortError"})}function te(r,e){let t=150*2**r,n=Math.round(t*(.75+Math.random()*.5));return new Promise((i,o)=>{let s,a=()=>e.removeEventListener("abort",l),l=()=>{s!==void 0&&clearTimeout(s),a(),o(Qt())};if(e.aborted){l();return}s=setTimeout(()=>{a(),i()},n),e.addEventListener("abort",l,{once:!0})})}var Xt="flopay_session_display:";var fe=new Map;function Ce(r){return`${Xt}${r}`}function qe(){if(typeof window>"u")return null;try{return window.sessionStorage}catch{return null}}function W(r,e,t){if(!r)return;let n=t?.ttlMs??36e5,i={data:e,expiresAt:Date.now()+n},o=qe();if(o)try{o.setItem(Ce(r),JSON.stringify(i));return}catch{}fe.set(r,i)}function ve(r){if(!r)return null;let e=qe();if(e)try{let n=e.getItem(Ce(r));if(n){let i=JSON.parse(n);if(i&&typeof i.expiresAt=="number"&&i.expiresAt>Date.now())return i.data;e.removeItem(Ce(r))}}catch{}let t=fe.get(r);if(t){if(t.expiresAt>Date.now())return t.data;fe.delete(r)}return null}function Te(r){if(!r)return;fe.delete(r);let e=qe();if(e)try{e.removeItem(Ce(r))}catch{}}var k=require("@flopay/shared");var Ne=require("@flopay/shared"),Zt=32,Ye=Symbol.for("@flopay/js.three-ds-challenge.attempts.v1");function er(){let r=globalThis,e=r[Ye];if(e instanceof Map)return e;let t=new Map;try{Object.defineProperty(r,Ye,{configurable:!0,enumerable:!1,writable:!1,value:t})}catch{}return t}function tr(r,e){let t=er(),n=t.get(r);if(n)return n;for(;t.size>=Zt;){let o=t.keys().next();if(o.done)break;t.delete(o.value)}let i={nextSequence:0,startedAt:e,terminated:!1,reconciled:new Set,provider:"unknown"};return t.set(r,i),i}var rr=new Set(["pagehide_observed","cancel_requested","abort_observed","browser_terminal"]),nr=new Set(["teardown","recovery_read_completed","provider_reconciled"]);function We(r,e={}){let t=(0,Ne.isThreeDsChallengeAttemptId)(e.attemptId)?e.attemptId.toLowerCase():r.newAttemptId(),n=()=>{try{let a=r.now();return Number.isFinite(a)?a:0}catch{return 0}},i=tr(t,n());(e.provider==="stripe"||e.provider==="worldpay")&&(i.provider=e.provider);let o=i.provider,s=(a,l)=>{if(i.terminated&&!nr.has(a))return;let c={attemptId:t,phase:a,attemptSequence:i.nextSequence,elapsedMs:Math.max(0,n()-i.startedAt),provider:o};i.nextSequence+=1,l.reason!==void 0&&(c.reason=l.reason),l.evidenceBasis!==void 0&&(c.evidenceBasis=l.evidenceBasis),l.terminalSource!==void 0&&(c.terminalSource=l.terminalSource),l.providerOutcome!==void 0&&(c.providerOutcome=l.providerOutcome);try{r.emit(c,rr.has(a))}catch{}};return{attemptId:t,record(a,l={}){a==="browser_terminal"||a==="provider_reconciled"||s(a,{reason:l.reason,evidenceBasis:l.evidenceBasis})},terminal(a,l={}){i.terminated||(s("browser_terminal",{terminalSource:a,reason:l.reason,evidenceBasis:l.evidenceBasis}),i.terminated=!0)},reconcile(a){i.reconciled.has(a)||(i.reconciled.add(a),s("provider_reconciled",{providerOutcome:a,evidenceBasis:"provider_fact"}))}}}function de(r){let e=null;try{e=(0,Ne.isThreeDsChallengeAttemptId)(r?.attemptId)?r?.attemptId??null:null}catch{e=null}return{attemptId:e,record(t,n){try{r?.record(t,n)}catch{}},terminal(t,n){try{r?.terminal(t,n)}catch{}},reconcile(t){try{r?.reconcile(t)}catch{}}}}function ue(r){if(typeof r!="string"||r.trim()==="")return"missing";try{let e=new URL(r);return e.protocol==="https:"||e.protocol==="http:"?"valid":"invalid"}catch{return"invalid"}}function Je(r){return r==="buyer_cancel"||r==="component_unmount"||r==="navigation"?r:"unspecified"}function be(r){try{if(typeof window>"u"||typeof window.getComputedStyle!="function")return null;for(let e=r;e;e=e.parentElement){let t=window.getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden"||t.visibility==="collapse"||t.opacity==="0")return"hidden"}return"visible"}catch{return null}}function _e(r,e){if(!e)return null;try{let t=r,n=String(t.effectiveDirective||t.violatedDirective||"").trim().split(/\s+/)[0],i=null;return n==="frame-src"&&(i="frame_src"),n==="child-src"&&(i="child_src"),!i||typeof t.blockedURI!="string"?null:new URL(t.blockedURI).origin===e?i:null}catch{return null}}function Se(r){try{return ue(r)==="valid"?new URL(r).origin:null}catch{return null}}var ir="/v1/sdk-telemetry/events",we=16,Qe=64,or=1500,Xe=1e3,sr=64,ar="00000000-0000-4000-8000-000000000000",lr={technical_error:8,lifecycle:32,expected_outcome:32,performance:24},cr=48;function H(){try{return globalThis.crypto.randomUUID()}catch{let r=new Uint8Array(16);try{globalThis.crypto.getRandomValues(r)}catch{for(let t=0;t<r.length;t+=1)r[t]=Math.floor(Math.random()*256)}r[6]=(r[6]??0)&15|64,r[8]=(r[8]??0)&63|128;let e=[...r].map(t=>t.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}}function dr(r){try{return new TextEncoder().encode(r).byteLength}catch{return r.length}}function ur(r){return JSON.stringify([r.code,r.failureCategory,r.reason,r.stage,r.provider,r.attempt,r.statusClass,r.requestCategory,r.paymentMethodCategory,r.walletType,r.operationOutcome,r.checkoutMode,r.layout,r.inAppBrowser,r.appFamily,r.popupCapability,r.presentationMode,r.terminalReason])}function E(){return globalThis.performance?.now()??0}var A=class{constructor(e){this.ingestionDisabled=!1;this.queue=[];this.sequence=0;this.threeDsChallengeCount=0;this.flushTimer=null;this.flushInFlight=null;this.reportedFailures=new Map;this.checkoutContext={};this.checkoutStartedAt=null;this.destroyed=!1;this.observers=new Set;this.pageExitHandler=()=>{this.drainQueue()};this.visibilityHandler=()=>{document.visibilityState==="hidden"&&this.flush()};this.eventCounts={technical_error:0,lifecycle:0,expected_outcome:0,performance:0};this.endpoint=`${e.billingApiUrl.replace(/\/+$/,"")}${ir}`,this.sdkPackage=e.sdkPackage??"@flopay/js",this.sdkVersion=e.sdkVersion,this.correlationId=H(),this.merchantEnabled=e.enabled!==!1,this.clock=e.clock??E,this.browserTransportAvailable=typeof window<"u"&&typeof document<"u",this.browserTransportAvailable&&(window.addEventListener("pagehide",this.pageExitHandler),document.addEventListener("visibilitychange",this.visibilityHandler))}log(e){this.notify({...e,class:"lifecycle"}),this.canCollect()&&this.enqueue((0,k.buildTelemetryLogEvent)({...this.checkoutContext,...e,eventId:H(),sequence:this.sequence++}))}error(e){if(this.notify({...e,class:"technical_error"}),!this.canCollect())return;let t=(0,k.buildTelemetryErrorEvent)({...this.checkoutContext,...e,eventId:ar,sequence:0}),n=ur(t),i=this.now();this.pruneReportedFailures(i);let o=this.reportedFailures.get(n);if(o!==void 0&&i>=o&&i-o<Xe){this.log({name:"operation.deduplicated",stage:e.stage,provider:e.provider,paymentMethodCategory:e.paymentMethodCategory,attempt:e.attempt,inAppBrowser:e.inAppBrowser,appFamily:e.appFamily,popupCapability:e.popupCapability,presentationMode:e.presentationMode,terminalReason:e.terminalReason});return}this.rememberReportedFailure(n,i),this.enqueue((0,k.buildTelemetryErrorEvent)({...this.checkoutContext,...e,eventId:H(),sequence:this.sequence++}))}performance(e){this.canCollect()&&this.enqueue((0,k.buildTelemetryPerformanceEvent)({...this.checkoutContext,...e,eventId:H(),sequence:this.sequence++}))}terminal(e){if(this.canCollect()&&(this.enqueue((0,k.buildTelemetryTerminalEvent)({...this.checkoutContext,...e,eventId:H(),sequence:this.sequence++})),e.outcome!=="action_required"&&this.checkoutStartedAt!==null)){let t=this.checkoutStartedAt;this.checkoutStartedAt=null,this.performance({...e,stage:"total_journey",durationMs:Math.max(0,this.now()-t),durationMode:"total"})}}beginThreeDsChallenge(e={}){return We({now:()=>this.now(),newAttemptId:H,emit:(t,n)=>this.recordThreeDsChallenge(t,n)},e)}recordThreeDsChallenge(e,t){if(!this.canCollect()||this.threeDsChallengeCount>=cr)return;let n=(0,k.buildTelemetryLogEvent)({...this.checkoutContext,...e,name:"three_ds.challenge",stage:"three_ds_handoff",eventId:H(),sequence:this.sequence++});if(!(this.queue.length>=Qe)){if(this.threeDsChallengeCount+=1,this.queue.push(n),t){this.drainQueue();return}if(this.queue.length>=we){this.flush();return}this.scheduleFlush()}}now(){try{return this.clock()}catch{return E()}}subscribe(e){return this.destroyed?()=>{}:(this.observers.add(e),()=>this.observers.delete(e))}notify(e){if(!this.destroyed)for(let t of this.observers)try{t(e)}catch{}}pruneReportedFailures(e){for(let[t,n]of this.reportedFailures)(e<n||e-n>=Xe)&&this.reportedFailures.delete(t)}rememberReportedFailure(e,t){for(;this.reportedFailures.size>=sr;){let n=this.reportedFailures.keys().next();if(n.done)break;this.reportedFailures.delete(n.value)}this.reportedFailures.set(e,t)}setCheckoutContext(e){this.checkoutContext={checkoutMode:e.checkoutMode,layout:e.layout}}beginCheckout(e={}){return this.canCollect()?(this.drainQueue(),this.setCheckoutContext(e),this.sequence=0,this.threeDsChallengeCount=0,this.reportedFailures.clear(),this.eventCounts={technical_error:0,lifecycle:0,expected_outcome:0,performance:0},this.checkoutStartedAt=this.now(),this.checkoutStartedAt):0}enqueue(e){if(this.canCollect()&&!(this.queue.length>=Qe||this.eventCounts[e.class]>=lr[e.class])){if(this.eventCounts[e.class]+=1,this.queue.push(e),this.queue.length>=we){this.flush();return}this.scheduleFlush()}}canCollect(){return this.browserTransportAvailable&&this.merchantEnabled&&!this.ingestionDisabled&&!this.destroyed}async flush(){if(this.flushInFlight!==null)return this.flushInFlight;if(!this.browserTransportAvailable||this.destroyed||this.ingestionDisabled||this.queue.length===0)return;this.clearFlushTimer();let e=this.queue.splice(0,we);return this.flushInFlight=this.sendBatch(e).finally(()=>{this.flushInFlight=null,this.queue.length>0&&this.scheduleFlush()}),this.flushInFlight}destroy(){this.destroyed||(this.drainQueue(),this.destroyed=!0,this.clearFlushTimer(),this.browserTransportAvailable&&(window.removeEventListener("pagehide",this.pageExitHandler),document.removeEventListener("visibilitychange",this.visibilityHandler)),this.queue.splice(0),this.reportedFailures.clear(),this.observers.clear())}disable(){this.merchantEnabled=!1,this.queue.splice(0),this.reportedFailures.clear(),this.clearFlushTimer()}drainQueue(){if(!(!this.browserTransportAvailable||this.destroyed||this.ingestionDisabled||this.queue.length===0))for(this.clearFlushTimer();this.queue.length>0;){let e=this.queue.splice(0,we);this.sendBatch(e)}}async sendBatch(e){if(!this.browserTransportAvailable||this.ingestionDisabled)return;let t=(0,k.serializeTelemetryBatch)(e,{correlationId:this.correlationId,sdkPackage:this.sdkPackage,sdkVersion:this.sdkVersion,batchId:H()});if(dr(t)>k.TELEMETRY_MAX_BATCH_BYTES)return;let n=typeof AbortController>"u"?null:new AbortController,i=null;try{let o=fetch(this.endpoint,{method:"POST",headers:{"content-type":"text/plain;charset=UTF-8"},body:t,credentials:"omit",keepalive:!0,referrerPolicy:"no-referrer",signal:n?.signal}).then(async l=>{if(l.status!==202)return null;let c=null;try{c=await l.json()}catch{}return c?.status==="disabled"?"disabled":null}).catch(()=>null),s=new Promise(l=>{i=setTimeout(()=>{n?.abort(),l(null)},or)});await Promise.race([o,s])==="disabled"&&this.disableFromIngestion()}catch{}finally{i&&clearTimeout(i)}}disableFromIngestion(){this.ingestionDisabled=!0,this.queue.splice(0),this.reportedFailures.clear(),this.clearFlushTimer()}scheduleFlush(){this.flushTimer||this.destroyed||this.ingestionDisabled||(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush()},0))}clearFlushTimer(){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null)}},Ze=Symbol.for("@flopay/js.telemetry.reporter-factory.v1"),et=globalThis;et[Ze]===void 0&&Object.defineProperty(et,Ze,{configurable:!0,enumerable:!1,writable:!1,value:r=>new A(r)});var Be=5,tt=new WeakSet;function mr(r){(typeof r=="object"&&r!==null||typeof r=="function")&&tt.add(r)}function pr(r){return(typeof r=="object"&&r!==null||typeof r=="function")&&tt.has(r)}function hr(r,e){let t=e?.error,n=le(e?.code)??le(t?.code)??`http_${r}`,i=ce(e?.message)??ce(t?.message)??yr(n,r);return new T.FloPayError(i,"api_error",{code:n,statusCode:r})}function yr(r,e){switch(r){case"CouponLimitExceeded":return`Too many coupon codes \u2014 a checkout session accepts at most ${Be}.`;case"CouponCurrencyUnsupported":return"One of the applied coupons has no price configured for the cart currency.";default:return`Failed to create checkout session (HTTP ${e}).`}}async function rt(r,e,t){let{billingApiUrl:n,checkoutBaseUrl:i,items:o=[],subscriptions:s=[],products:a,account:l,successUrl:c,cancelUrl:u,checkoutMode:h="confirm",captureMethod:p,couponCodes:y=[],checkoutMetadata:m,tagsData:g,redirectParams:v={},setCookie:f=!0,clientId:S,currency:C,utmMetadata:F,idempotencyKey:G}=r,V=(0,T.resolveIdempotencyKey)(G);if(y.length>Be)throw new T.FloPayError(`Too many coupon codes \u2014 a checkout session accepts at most ${Be}.`,"validation_error",{code:"CouponLimitExceeded",param:"couponCodes"});let x=a??(0,T.foldIntoProducts)(o,s);(0,T.assertCaptureMethodEligible)({captureMethod:p,products:x});let I=(0,T.resolveSessionCurrency)(C,o,s,x);if(!I)throw new T.FloPayError("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 R={clientId:S,checkoutVersion:T.SDK_VERSION,successUrl:c,cancelUrl:u,currency:I,checkoutMode:h,products:x.map(P=>(0,T.buildProductPayload)(P,I)),accountData:{userId:l.userId,firstName:l.firstName??null,lastName:l.lastName??null,email:l.email,country:l.country??null,gender:l.gender??null,city:l.city??null,state:l.state??null,zip:l.zip??null,addressLine1:l.addressLine1??null,addressLine2:l.addressLine2??null},couponCodes:y};p==="manual"&&(R.captureMethod=p),m!==void 0&&(R.checkoutMetadata=m),g&&(R.tagsData=g),F&&F.length>0&&(R.utmMetadata=F);let Z=`${n.replace(/\/+$/,"")}/v1/checkouts/sessions`,se={"Content-Type":"application/json"};V&&(se[T.IDEMPOTENCY_KEY_HEADER]=V);let U,Y,ae={method:"POST",headers:se,body:JSON.stringify(R),signal:e},z;try{t?.startAttempt(),z=await fetch(Z,ae)}catch(P){throw mr(P),P}try{t?.record(z.status)}catch{}U=z.status;try{Y=await z.json()}catch{}if(U>=400)throw(0,T.withTelemetryHttpDiagnostics)(hr(U,Y),z);if(U===201){let P=Y?.data?.uuid,ee=Y?.data?.nonce;if(!P)throw new Error("Checkout session created but no UUID was returned by the billing API");if(!ee)throw new T.FloPayError("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"});(x.length>0||I)&&W(P,{currency:I,products:x.map(b=>({code:b.code??b.providerItemId??b.providerPlanId,type:b.type,name:b.name??b.itemName??b.providerItemName??b.subscriptionName??b.providerPlanName??null,totalAmount:b.totalAmount,overrideAmount:b.overrideAmount,currency:b.currency??I}))});let w=new URL(`${i.replace(/\/+$/,"")}/secure`);w.searchParams.set("id",P);for(let[b,j]of Object.entries(v))w.searchParams.set(b,j);if(f&&typeof window<"u"&&typeof document<"u"){let b=JSON.stringify({origin_url:u}),j=window.location.hostname.split(".").slice(-2).join(".");document.cookie=`checkout_data=${encodeURIComponent(b)}; domain=.${j}; path=/; max-age=3600; SameSite=Lax; Secure;`,document.cookie=`flopay_checkout_token=${encodeURIComponent(ee)}; domain=.${j}; path=/; max-age=3600; SameSite=Lax; Secure;`}return typeof window<"u"&&(window.location.href=w.toString()),{status:201,redirectUrl:w.toString(),nonce:ee}}return U===204?(typeof window<"u"&&(window.location.href=c),{status:204}):{status:U}}async function nt(r){let e=ot(r),t=it(e),n=L(r.timeoutMs);try{let i=await rt(r,n.signal,t);return t.commit(),st(e,i),i}catch(i){throw t.commit(),Re(e,i),i}finally{n.clear(),re(e.reporter)}}function it(r){let e=!1,t=r.startedAt,n;return{startAttempt(){t=r.reporter.now()},record(i){n={status:i,durationMs:Math.max(0,r.reporter.now()-t),attempt:r.attempt}},commit(){if(e||!n)return;e=!0;let i=(0,T.telemetryStatusClass)(n.status);r.reporter.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:i,attempt:n.attempt}),r.reporter.performance({stage:"session_first_byte",durationMs:n.durationMs,durationMode:"machine",requestCategory:"session_create",statusClass:i,attempt:n.attempt})}}}function ot(r){let e=new A({billingApiUrl:r.billingApiUrl,sdkVersion:T.SDK_VERSION,enabled:r.telemetry!==!1}),t=e.now();return e.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"}),{reporter:e,startedAt:t,attempt:0}}function st(r,e){let t=(0,T.telemetryStatusClass)(e.status);r.reporter.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:t}),r.reporter.performance({stage:"session_create",durationMs:r.reporter.now()-r.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:t,attempt:r.attempt})}function Re(r,e){let{reporter:t}=r,n=(0,T.classifyTelemetryFailure)(e,"CHECKOUT_SESSION_CREATE_FAILED");if(t.performance({stage:"session_create",durationMs:t.now()-r.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:n.statusClass,attempt:r.attempt}),e instanceof T.FloPayError&&e.type==="validation_error"){t.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"});return}if(n.statusClass==="4xx"){t.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create",statusClass:"4xx"});return}t.error({...n,stage:"session_create",requestCategory:"session_create"})}function re(r){r.flush().catch(()=>{}).finally(()=>r.destroy())}async function at(r){let{maxRetries:e=2,...t}=r,n=ot(r),i=it(n);if(!Number.isFinite(e)||!Number.isInteger(e)||e<0||e>=3)throw n.reporter.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),re(n.reporter),new Error(`Number of retries must be an integer between 0 and ${2}`);let o={...t,idempotencyKey:(0,T.resolveIdempotencyKey)(t.idempotencyKey)},s=L(t.timeoutMs),a;for(let l=0;l<=e;l++){n.attempt=l;try{let c=await rt(o,s.signal,i);return i.commit(),st(n,c),s.clear(),re(n.reporter),c}catch(c){a=c;let u=c instanceof Error&&c.name==="AbortError",h=pr(c),p=c instanceof T.FloPayError&&c.code===T.IDEMPOTENCY_IN_PROGRESS_CODE;if((u||h||p)&&!s.signal.aborted&&l<e){n.reporter.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:l+1});try{await te(l,s.signal)}catch(y){throw i.commit(),Re(n,y),s.clear(),re(n.reporter),y}continue}throw i.commit(),Re(n,c),s.clear(),re(n.reporter),c}}throw i.commit(),Re(n,a),s.clear(),re(n.reporter),a??new Error("Unknown error during checkout session creation")}var M=require("@flopay/shared");var d=require("@flopay/shared");function gr(r){return r==="on_session"||r==="off_session"}function fr(r){if(!r||typeof r!="object")return!1;let e=r;return typeof e.paymentMethodType=="string"&&typeof e.reason=="string"}function Cr(r){let e=r.vaultOutcome;if(!(!e||e.code!==d.CHECKOUT_SESSION_BUYER_EMAIL_REQUIRED))return typeof e.message=="string"&&e.message.trim()!==""?e.message:void 0}var vr="x-flopay-process-result-source",Tr="status",Ct=new WeakSet;function br(r,e){let t=new d.FloPayError(r,"api_error",{code:e,statusCode:500});return Ct.add(t),t}function _r(r){return typeof r=="object"&&r!==null&&Ct.has(r)}function lt(r){return r?.result==="DECLINE"||r?.result==="ERROR"}var Sr=50,J=new Map;function wr(r,e){return J.get(r)?.has(e)===!0}function Rr(r,e){let t=J.get(r)??new Set;if(t.add(e),J.delete(r),J.set(r,t),J.size>Sr){let n=J.keys().next().value;n!==void 0&&J.delete(n)}}function Ar(r){let e=r?.threeDSecureActionResultTokenId;if(typeof e=="string"&&e.length>0)return e;if(r?.gateway==="paypal"&&r.type!=="paypal_setup_token"&&typeof r.id=="string"&&r.id.length>0)return r.id}var ct=0,dt=500,Ae=15e3,ut=15e3,kr=3e3,Er=1e4,Mr=1e4;function pe(r){return typeof r=="object"&&r!==null}function K(r,e){return le(r?.[e])}function mt(r,e){return ce(r?.[e])}function Ir(r,e){let t=r?.[e];return typeof t=="number"&&Number.isFinite(t)?t:void 0}function Ee(r,e){return e?new Promise((t,n)=>{let i=()=>{clearTimeout(o),n(e.reason??Object.assign(new Error("The operation was aborted."),{name:"AbortError"}))},o=setTimeout(()=>{e.removeEventListener("abort",i),t()},r);e.aborted?i():e.addEventListener("abort",i,{once:!0})}):new Promise(t=>setTimeout(t,r))}function Ve(r){return r instanceof Error&&r.name==="AbortError"}function D(){return new d.FloPayError(d.CHECKOUT_PROCESSING_TIMEOUT_MESSAGE,"api_error",{code:"checkout_processing_timeout"})}async function N(r,e){let t=await r.json().catch(()=>null),n=pe(t?.error)?t.error:null,i=mt(t,"message")??mt(n,"message")??e,o=K(t,"code")??K(t,"gatewayErrorCode")??K(n,"code")??`http_${r.status}`;return(0,d.withTelemetryHttpDiagnostics)(new d.FloPayError(i,"api_error",{code:o,statusCode:r.status}),r)}async function Pr(r){if(r.status!==403)return!1;let e=await r.clone().json().catch(()=>null),t=pe(e?.error)?e.error:null;return(K(e,"code")??K(t,"code"))==="verification_required"}function Dr(r){if(!(!pe(r)||typeof r.required!="boolean"))return{required:r.required,provider:"turnstile"}}async function Fr(r){let e=r.status===400?await r.clone().json().catch(()=>null):null;return(0,d.classifyPaymentRejection)(r.status,e)}function pt(r){return r===400||r===422}var Me=2;async function ke(r,e,t=Me,n,i){let o;for(let s=0;;s++)try{return i?.(s),await fetch(r,e)}catch(a){if(e?.signal?.aborted||a instanceof Error&&a.name==="AbortError")throw a;if(o=a,s>=t)throw o;try{n?.(s+1)}catch{}await Ee(150*2**s,e?.signal??void 0)}}var xr=2e3,Or=1e4,Ur=150;async function Lr(r){try{let t=(await r.json())?.data?.status;return t==="closed"||t==="not_open"?t:"failed"}catch{return"failed"}}async function ht(r,e,t){let n=new AbortController,i=()=>n.abort();t?.addEventListener("abort",i,{once:!0});let o,s=new Promise(a=>{o=setTimeout(()=>{n.abort(),a("timeout")},Or)});try{let a=await Promise.race([fetch(r,{...e,signal:n.signal}),s]);return a==="timeout"?"failed":a.status>=500?"retry":a.ok?await Lr(a):"failed"}catch{return n.signal.aborted?"failed":"retry"}finally{clearTimeout(o),t?.removeEventListener("abort",i)}}function qr(r,e){return new Promise(t=>{let n=setTimeout(t,e);r.then(()=>{clearTimeout(n),t()},()=>{clearTimeout(n),t()})})}var yt="stripe-account-switch-v1",ze=Symbol.for("@flopay/js.session-create.telemetry.v1");function Nr(r){return r[ze]}function Br(r){return"now"in r||"onFirstByte"in r||"onSessionCreateFailure"in r||"onRetry"in r}function vt(r){let e=(0,d.isCardHolderNamePlaceholder)(r.firstName,r.lastName);return{userId:r.userId,firstName:e?null:r.firstName??null,lastName:e?null:r.lastName??null,email:r.email,country:r.country??null,gender:r.gender??null,city:r.city??null,state:r.state??null,zip:r.zip??null,addressLine1:r.addressLine1??null,addressLine2:r.addressLine2??null}}function Tt(r,e){e.checkoutMetadata!==void 0&&(r.checkoutMetadata=e.checkoutMetadata),e.tagsData&&(r.tagsData=e.tagsData),e.utmMetadata&&e.utmMetadata.length>0&&(r.utmMetadata=e.utmMetadata),e.avsCheck!==void 0&&(r.avsCheck=e.avsCheck),e.checkoutType&&(r.checkoutType=e.checkoutType),e.checkoutLayout&&(r.checkoutLayout=e.checkoutLayout),e.avsConfig&&(r.avsConfig=e.avsConfig)}function gt(r){if(typeof r!="string")return;let e=r.trim();return e.length>0?e:void 0}function Vr(r){let e={};if(r.country&&(e.country=r.country),!(0,d.isCardHolderNamePlaceholder)(r.firstName,r.lastName)){let t=gt(r.firstName),n=gt(r.lastName);t&&(e.firstName=t),n&&(e.lastName=n)}return Object.keys(e).length>0?e:void 0}function zr(r,e,t){let n={clientId:r.clientId,checkoutVersion:d.SDK_VERSION,successUrl:r.successUrl,cancelUrl:r.cancelUrl,currency:e,checkoutMode:"full",deferDataAttachment:!0};r.captureMethod==="manual"&&(n.captureMethod=r.captureMethod);let i=Vr(r.account);i&&(n.accountData=i),Tt(n,r);let o=jr(t);return o&&(n.routingProducts=o),n}function jr(r){let e=new Set;for(let t of r){let n=[t.code,t.providerItemId,t.providerPlanId].map(i=>typeof i=="string"?i.trim():"").find(i=>i.length>0);n&&e.add(n)}return e.size>0?Array.from(e,t=>({code:t})):void 0}function ft(r,e,t){return{currency:e,products:t.map(n=>(0,d.buildProductPayload)(n,e)),couponCodes:r.couponCodes??[],accountData:vt(r.account)}}function Hr(r,e,t){return{currency:e,products:t.map(n=>(0,d.buildProductPayload)(n,e)),couponCodes:r.couponCodes??[]}}function Kr(r){let e={},t=(0,d.isCardHolderNamePlaceholder)(r.firstName,r.lastName);for(let[n,i]of Object.entries(r)){if(t&&n.endsWith("Name")||typeof i!="string")continue;let o=i.trim();o&&(e[n]=o)}return{accountData:e}}var O=class O{constructor(e,t={}){this.baseUrl=e.replace(/\/+$/,"");let n=Br(t);this.telemetryHooks=n?t:void 0,this.stripeAccountSwitch=!n&&t.stripeAccountSwitch===!0,this.directTelemetry=n||t.telemetry===!1?void 0:new A({billingApiUrl:this.baseUrl,sdkVersion:d.SDK_VERSION})}destroy(){this.directTelemetry?.destroy()}reportDirectFailure(e,t,n,i,o="unknown"){let s=(0,d.classifyTelemetryFailure)(e,t);this.directTelemetry?.error({...s,..._r(e)?{reason:"capture_failed"}:{},stage:n,requestCategory:i,paymentMethodCategory:o})}reportAccountSnapshotFailure(e,t){let n=(0,d.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED");if(t==="best_effort"&&n.errorCode==="REQUEST_TIMEOUT"){this.directTelemetry?.log({name:"operation.fallback",stage:"processing",requestCategory:"account_snapshot",statusClass:"timeout"});return}this.directTelemetry?.error({...n,stage:"processing",requestCategory:"account_snapshot",paymentMethodCategory:"unknown"})}telemetryTimestamp(){try{return this.telemetryHooks?.now?.()??this.directTelemetry?.now()??E()}catch{return E()}}beginDirectTelemetryCheckout(e){!this.directTelemetry||this.directTelemetryCheckoutId===e||(this.directTelemetryCheckoutId=e,this.directTelemetry.beginCheckout())}beginDirectTelemetryOperation(){this.directTelemetry&&(this.directTelemetryCheckoutId=void 0,this.directTelemetry.beginCheckout())}adoptDirectTelemetryCheckout(e){e&&(this.directTelemetryCheckoutId=e)}async getCheckoutSession(e,t){return this.fetchCheckoutSession(e,t)}async fetchCheckoutSession(e,t,n=!0,i){this.beginDirectTelemetryCheckout(e);let o=this.telemetryTimestamp(),s=o,a=0;this.directTelemetry?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let l={[d.FLO_SDK_VERSION_HEADER]:d.SDK_VERSION};t&&(l["x-checkout-session-token"]=t);let c=!1;try{let u=await ke(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}`,{headers:l,signal:i},Me,m=>{this.telemetryHooks?.onRetry?.("session_read",m),this.directTelemetry?.log({name:"operation.retry",stage:"session_read",requestCategory:"session_read",attempt:m})},m=>{a=m,s=this.telemetryTimestamp()});c=!0;let h=Math.max(0,this.telemetryTimestamp()-s);try{this.telemetryHooks?.onFirstByte?.(h,a)}catch{}let p=`${Math.floor(u.status/100)}xx`;if(this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:p,attempt:a}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:h,durationMode:"machine",requestCategory:"session_read",statusClass:p,attempt:a}),!u.ok)throw await N(u,"Failed to get checkout session");let y=await u.json();return this.directTelemetry?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:p}),this.directTelemetry?.performance({stage:"session_complete",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"session_read",statusClass:p}),{...y,data:this.mergeCachedDisplayData(y.data)}}catch(u){throw c&&(0,d.markSessionResponseReceived)(u),n&&this.directTelemetry?.error({...(0,d.classifyTelemetryFailure)(u,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"}),u}}cacheSessionDisplayData(e,t,n){W(e,t,n)}clearSessionDisplayData(e){Te(e)}async getVaultCapture(e,t){let n=`${this.baseUrl}\0${e}\0${t??""}`,i=O.activeVaultCaptureRequests.get(n);if(i!==void 0)return i;let o=O.pendingThreeDsAbandonReports.get(e),s=o===void 0?this.requestVaultCapture(e,t):qr(o,xr).then(()=>this.requestVaultCapture(e,t));O.activeVaultCaptureRequests.set(n,s);try{return await s}finally{O.activeVaultCaptureRequests.get(n)===s&&O.activeVaultCaptureRequests.delete(n)}}async requestVaultCapture(e,t){let n=new AbortController,i=setTimeout(()=>n.abort(),Mr);this.beginDirectTelemetryCheckout(e);let o=this.telemetryTimestamp();this.directTelemetry?.log({name:"vault.capture.requested",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card"});let s={"Content-Type":"application/json"};t&&(s["x-checkout-session-token"]=t);try{let a=await ke(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/vault/capture`,{method:"POST",headers:s,signal:n.signal},Me,c=>{this.telemetryHooks?.onRetry?.("vault_capture",c),this.directTelemetry?.log({name:"operation.retry",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card",attempt:c})});if(await Pr(a))return this.directTelemetry?.performance({stage:"vault_request",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"4xx"}),{verification:{required:!0,provider:"turnstile"}};if(!a.ok)throw await N(a,"Failed to load the secure card form");let l=await a.json();return this.directTelemetry?.performance({stage:"vault_request",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"2xx"}),this.toVaultBlock(l)}catch(a){let l=n.signal.aborted?new d.FloPayError("Timed out while loading the secure card form. Please try again.","api_error",{code:"vault_capture_timeout"}):a;throw this.reportDirectFailure(l,"VAULT_LOAD_FAILED","vault_request","vault_capture","card"),l}finally{clearTimeout(i)}}async getUnifiedCheckoutSession(e,t){let n=await this.getCheckoutSession(e,t);return this.normalizeCheckoutSessionResponse(n)}async getUnifiedCheckoutSessionForRecovery(e,t,n){let i=await this.fetchCheckoutSession(e,t,!1,n);return this.normalizeCheckoutSessionResponse(i)}normalizeCheckoutSessionResponse(e){try{let t=this.normalizeRawSession(e.data),n=e.vault;return n&&t.data.session&&(t.data.session.vault=this.toVaultBlock(n)),t}catch(t){throw(0,d.markSessionResponseReceived)(t)}}async processPayment(e,t,n){this.beginDirectTelemetryCheckout(t.sessionId);let i=t.paymentMethodCategory??"unknown";if(!t.nonce)throw this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"process_payment",paymentMethodCategory:i}),new d.FloPayError("processPayment requires `nonce` \u2014 pass the value returned from session creation.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let o=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.processing.started",stage:"processing",requestCategory:"process_payment",paymentMethodCategory:i});let{nonce:s,paymentMethodCategory:a,...l}=t,c=Ar(t.tokenizedData),u,h;try{u=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(t.sessionId)}/process`,{method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":s},body:JSON.stringify(l)}),h=u}catch(p){if(Ve(p))throw this.reportDirectFailure(p,"PAYMENT_PROCESSING_FAILED","processing","process_payment",i),p;u=await this.reconcileProcessPayment(t.sessionId,{...n,nonce:s,paymentMethodCategory:i,submittedIntentId:c})}if(!u.ok&&u.status!==202){let p=await Fr(u);return p?this.directTelemetry?.terminal({outcome:p,stage:"processing",requestCategory:"process_payment",statusClass:"4xx",paymentMethodCategory:i}):this.directTelemetry?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",requestCategory:"process_payment",statusClass:(0,d.telemetryStatusClass)(u.status),failureCategory:u.status>=500?"server_error":void 0,paymentMethodCategory:i,...(0,d.readTelemetryHttpDiagnostics)(h)}),u}try{let p=await this.resolveProcessResponse(u,t.sessionId,{...n,nonce:s,paymentMethodCategory:i,submittedIntentId:c});return this.directTelemetry?.log({name:"payment.processing.completed",stage:"processing",requestCategory:"process_payment",statusClass:(0,d.telemetryStatusClass)(p.status),paymentMethodCategory:i}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"process_payment",statusClass:(0,d.telemetryStatusClass)(p.status),paymentMethodCategory:i}),p}catch(p){throw p instanceof d.FloPayError&&p.code==="checkout_processing_timeout"||this.reportDirectFailure(p,"PAYMENT_PROCESSING_FAILED","processing","process_payment",i),p}}async patchAccountSnapshot(e,t,n,i){this.beginDirectTelemetryCheckout(e);let o=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.state_transition",stage:"processing",requestCategory:"account_snapshot"});let s=i?.timeoutMs??Er,a=new AbortController,l=()=>a.abort();i?.signal&&(i.signal.aborted?a.abort():i.signal.addEventListener("abort",l,{once:!0}));let c=setTimeout(()=>a.abort(),s);try{let u;try{u=await ke(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/account`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":t},body:JSON.stringify(n),signal:a.signal},Me,h=>{this.telemetryHooks?.onRetry?.("account_snapshot",h),this.directTelemetry?.log({name:"operation.retry",stage:"processing",requestCategory:"account_snapshot",attempt:h})})}finally{clearTimeout(c),i?.signal?.removeEventListener("abort",l)}if(!u.ok)throw await N(u,"Failed to persist account snapshot");this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"account_snapshot",statusClass:"2xx"})}catch(u){throw this.reportAccountSnapshotFailure(u,i?.telemetryMode??"blocking"),u}}async createSessionIntent(e,t,n,i){if(!t)throw new d.FloPayError("createSessionIntent requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let o=n,s=o.paymentMethodType,a=typeof s=="string"&&s.trim().toLowerCase()==="card",l=typeof s=="string"&&s.length>0&&!a&&(typeof o.paymentMethodId=="string"||o.paymentMethodId===null),c=o.provider==="stripe"&&(o.paymentMethodCategory==="wallet"||o.paymentMethodCategory==="apm")&&(o.intentKind==="payment"||o.intentKind==="setup"),u=o.provider==="paypal"&&o.paymentMethodCategory==="wallet"&&o.paymentMethodId===null&&(o.paymentMethodType==="paypal"&&o.intentKind==="payment"||o.paymentMethodType===d.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&(o.intentKind==="payment"||o.intentKind==="setup"));if(!l||!c&&!u)throw new d.FloPayError("Only wallet, APM, and PayPal session intents are supported.","validation_error",{code:"InvalidSessionIntentRequest"});let h=o.authorizationAttemptId;if(h!==void 0&&!(0,d.isUuidV4)(h))throw new d.FloPayError("authorizationAttemptId must be a v4 UUID identifying one buyer authorization attempt.","validation_error",{code:"InvalidAuthorizationAttemptId",param:"authorizationAttemptId"});let p=(0,d.isUuidV4)(h)?h:(0,d.randomUuidV4)();this.beginDirectTelemetryCheckout(e);let y=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.intent.started",stage:"processing",requestCategory:"intent_create"});let m={"Content-Type":"application/json","x-checkout-session-token":t,[d.IDEMPOTENCY_KEY_HEADER]:i?.idempotencyKey||p},g=!1;try{let v=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents`,{method:"POST",headers:m,body:JSON.stringify({...n,authorizationAttemptId:p}),signal:i?.signal});if(!v.ok){g=!0;let R=await N(v,"Failed to create checkout intent"),Z=(0,d.classifyTelemetryFailure)(R,"PAYMENT_PROCESSING_FAILED");throw pt(R.statusCode)?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"intent_create",statusClass:"4xx"}):this.directTelemetry?.error({...Z,stage:"processing",requestCategory:"intent_create"}),R}let f=await v.json();if(v.status===202&&pe(f)&&f.type==="checkout_processing")return g=!0,await this.settleProcessingSessionIntent(f,v,e,t,n);let S=f.data;if(!S||typeof S!="object")throw new d.FloPayError("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});let C=S,F=C.paymentMethodType,G=(C.paymentMethodCategory==="wallet"||C.paymentMethodCategory==="apm")&&typeof F=="string"&&F.trim().toLowerCase()!=="card"&&(typeof C.paymentMethodId=="string"||C.paymentMethodId===null)&&typeof C.providerObjectId=="string",V=C.provider==="stripe"&&(C.intentKind==="payment"||C.intentKind==="setup")&&typeof C.clientSecret=="string",x=C.provider==="paypal"&&C.paymentMethodCategory==="wallet"&&C.paymentMethodId===null&&(C.paymentMethodType==="paypal"&&C.intentKind==="payment"&&(C.providerObjectType==="order"||C.providerObjectType==="subscription")||C.paymentMethodType===d.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&C.intentKind==="payment"&&C.providerObjectType==="order"||C.paymentMethodType===d.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&C.intentKind==="setup"&&C.providerObjectType==="setup_token")&&C.clientSecret===null,I=C.provider===n.provider&&C.paymentMethodCategory===n.paymentMethodCategory&&C.paymentMethodType===n.paymentMethodType&&C.paymentMethodId===n.paymentMethodId&&C.intentKind===n.intentKind;if(!G||!V&&!x||!I)throw new d.FloPayError("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});return this.directTelemetry?.log({name:"payment.intent.completed",stage:"processing",requestCategory:"intent_create",statusClass:(0,d.telemetryStatusClass)(v.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-y),durationMode:"machine",requestCategory:"intent_create",statusClass:(0,d.telemetryStatusClass)(v.status)}),C}catch(v){throw g||this.reportDirectFailure(v,"PAYMENT_PROCESSING_FAILED","processing","intent_create"),v}}async settleProcessingSessionIntent(e,t,n,i,o){let s=this.toCheckoutProcessingPending(e,t,n);try{return{settled:!0,response:await this.resolveCheckoutProcessing(s,n,{nonce:i,paymentMethodCategory:o.provider==="paypal"?"paypal":o.paymentMethodCategory})}}catch(a){throw a instanceof d.FloPayError&&a.code==="checkout_processing_timeout"?new d.FloPayError(a.message,a.type,{code:a.code,statusCode:202,sessionId:s.sessionId,cause:a}):a}}closeThreeDsChallenge(e,t,n,i={}){if(!e||!t||!n||i.signal?.aborted)return Promise.resolve("failed");let o=this.requestThreeDsChallengeClose(e,t,n,i.signal),s=O.pendingThreeDsAbandonReports;return s.set(e,o),o.then(()=>{s.get(e)===o&&s.delete(e)}),o}async requestThreeDsChallengeClose(e,t,n,i){let o=`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/3ds/abandoned`,s={method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":t},body:JSON.stringify({providerIntentId:n})};try{let a=await ht(o,s,i);if(a!=="retry")return a;if(i?.aborted)return"failed";await Ee(Ur,i);let l=await ht(o,s,i);return l==="retry"?"failed":l}catch{return"failed"}}async reportSessionIntentDecline(e,t,n,i){if(!t)throw new d.FloPayError("reportSessionIntentDecline requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let o=n,s=o.providerDeclineReason,a=o.paymentMethodType,l=o.providerIntentId,c=typeof s=="string"&&/^[a-z0-9][a-z0-9_.:-]{0,63}$/i.test(s)&&!/^(?:pm|pi|seti|tok|src|cus|sess|sk|pk)_/i.test(s),u=typeof a=="string"&&a.length>0&&a.trim().toLowerCase()!=="card"&&c,h=o.provider==="stripe"&&(o.paymentMethodCategory==="wallet"||o.paymentMethodCategory==="apm")&&(l===void 0||typeof l=="string"&&/^pi_[a-z0-9_]{1,252}$/i.test(l)),p=o.provider==="paypal"&&o.paymentMethodCategory==="wallet"&&o.paymentMethodType==="paypal"&&l===void 0;if(!u||!h&&!p)throw new d.FloPayError("Invalid non-card decline classification.","validation_error",{code:"InvalidSessionIntentDeclineRequest"});let y=p?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:s}:{provider:"stripe",paymentMethodCategory:o.paymentMethodCategory,paymentMethodType:o.paymentMethodType,providerDeclineReason:s,...typeof l=="string"?{providerIntentId:l}:{}},m=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents/decline`,{method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":t},body:JSON.stringify(y),signal:i?.signal});if(!m.ok)throw await N(m,"Failed to report checkout decline")}async resolvePaymentMethodLayout(e,t,n,i){if(!t)throw new d.FloPayError("resolvePaymentMethodLayout requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let o=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/payment-method-layout`,{method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":t,[d.FLO_SDK_VERSION_HEADER]:d.SDK_VERSION},body:JSON.stringify(n),signal:i?.signal});if(o.status===404||o.status===405)return null;if(!o.ok)throw await N(o,"Failed to resolve the payment method layout");let s=await o.json();return(0,d.normalizePaymentMethodLayout)(s?.data)}async getPaymentsByEmail(e,t){this.beginDirectTelemetryOperation();let n=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved"});let i=t?.page??1,o=t?.limit??1,s=new URLSearchParams({email:e,page:String(i),limit:String(o),sortField:"createdAt",sortDirection:"DESC"});try{let a=await fetch(`${this.baseUrl}/v1/payments?${s.toString()}`,{method:"GET",signal:t?.signal,keepalive:!0});if(!a.ok)throw(0,d.withTelemetryHttpDiagnostics)(new d.FloPayError("Failed to fetch payments","api_error",{statusCode:a.status}),a);let l=await a.json();return this.directTelemetry?.log({name:"operation.recovery.completed",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),this.directTelemetry?.performance({stage:"recovery",durationMs:Math.max(0,this.telemetryTimestamp()-n),durationMode:"machine",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),l}catch(a){throw this.reportDirectFailure(a,"RECOVERY_FAILED","recovery","other","saved"),a}}async createAndFetchSession(e){if((0,d.isDetachedSessionEligible)(e)){let o=e.account.email?.trim();if(o&&!(0,d.isValidEmail)(o))throw new d.FloPayError("Buyer email must be valid when supplied.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"});return(await this.createDetachedSession(e)).claimed}this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp(),n=L(e.timeoutMs??12e3),i={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});try{let o=await this.createAndFetchSessionRequest(e,n.signal,i);return this.adoptDirectTelemetryCheckout(o.data.session?.id),this.directTelemetry?.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:i.statusClass}),this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:"session_create",statusClass:i.statusClass,attempt:i.attempt}),o}catch(o){throw this.reportSessionCreateFailure(o,t,i),o}finally{n.clear()}}async createAndFetchSessionRequest(e,t,n){let i=e.products??(0,d.foldIntoProducts)(e.items,e.subscriptions);(0,d.assertCaptureMethodEligible)({captureMethod:e.captureMethod,products:i});let o=(0,d.resolveSessionCurrency)(e.currency,e.items,e.subscriptions,i);if(!o)throw new d.FloPayError("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 s={clientId:e.clientId,checkoutVersion:d.SDK_VERSION,successUrl:e.successUrl,cancelUrl:e.cancelUrl,currency:o,checkoutMode:e.checkoutMode??"full",products:i.map(c=>(0,d.buildProductPayload)(c,o)),accountData:vt(e.account),couponCodes:e.couponCodes??[]};e.captureMethod==="manual"&&(s.captureMethod=e.captureMethod),e.tokenizedData&&(s.tokenizedData=e.tokenizedData),Tt(s,e);let a=await this.postCheckoutSessionCreate(s,e,t,n),l=!1;try{let c=await a.json();if(c.data&&"gateways"in c.data){this.autoCacheDisplayData(c.data.uuid,e);let p=this.mergeCachedDisplayData(c.data),y=this.normalizeRawSession(p);return c.vault&&y.data.session&&(y.data.session.vault=this.toVaultBlock(c.vault)),{...y,autoProcessingError:c.autoProcessingError,autoProcessingAttempted:c.autoProcessingAttempted,autoProcessingPending:c.autoProcessingPending}}let u=c.data?.uuid;if(!u)throw new d.FloPayError("No session ID returned","api_error",{code:"InvalidCheckoutSessionResponse"});return this.autoCacheDisplayData(u,e),this.adoptDirectTelemetryCheckout(u),l=!0,{...await this.getUnifiedCheckoutSession(u),autoProcessingError:c.autoProcessingError,autoProcessingAttempted:c.autoProcessingAttempted,autoProcessingPending:c.autoProcessingPending}}catch(c){throw l?c:(0,d.markSessionResponseReceived)(c)}}async postCheckoutSessionCreate(e,t,n,i){let o={"Content-Type":"application/json",[d.FLO_SDK_VERSION_HEADER]:d.SDK_VERSION},s=(0,d.resolveIdempotencyKey)(t.idempotencyKey);s&&(o[d.IDEMPOTENCY_KEY_HEADER]=s);let a=[];t.checkoutMode==="auto"&&a.push(d.ASYNC_AUTO_CHECKOUT_CAPABILITY),this.stripeAccountSwitch&&e.deferDataAttachment===!0&&a.push(yt),a.length>0&&(o[d.FLO_SDK_CAPABILITIES_HEADER]=a.join(", "));let l,c=!1,u=Nr(t),h=(y,m,g)=>{c||(c=!0,this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:g,attempt:y}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:Math.max(0,this.telemetryTimestamp()-m),durationMode:"machine",requestCategory:"session_create",statusClass:g,attempt:y}))},p=y=>{try{this.telemetryHooks?.onRetry?.("session_create",y),this.directTelemetry?.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:y})}catch{}};for(let y=0;y<3;y++){i.attempt=y;let m=this.telemetryTimestamp();try{u?.onAttempt?.(y)}catch{}try{l=await fetch(`${this.baseUrl}/v1/checkouts/sessions?expand=true`,{method:"POST",headers:o,body:JSON.stringify(e),signal:n})}catch(f){if(i.statusClass=n.aborted||f instanceof Error&&f.name==="AbortError"?"timeout":"network_error",n.aborted||f instanceof Error&&f.name==="AbortError"||y>=2)throw f;let S=y+1;p(S),await te(y,n);continue}let g=(0,d.telemetryStatusClass)(l.status);if(i.statusClass=g,l.status===204)throw h(y,m,g),new d.FloPayError("Session auto-completed \u2014 payment method already on file","api_error",{code:"session_auto_completed"});if(l.ok){h(y,m,g);break}let v=await N(l,"Failed to create checkout session");if(v.code===d.IDEMPOTENCY_IN_PROGRESS_CODE&&y<2){p(y+1),await te(y,n);continue}throw h(y,m,g),v}if(!l)throw new TypeError("Checkout-session creation exhausted its retry budget.");return l}async createDetachedSession(e){this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp(),n=L(e.timeoutMs??12e3),i={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let o=e.products??(0,d.foldIntoProducts)(e.items,e.subscriptions);try{(0,d.assertCaptureMethodEligible)({captureMethod:e.captureMethod,products:o})}catch(f){throw n.clear(),this.reportSessionCreateFailure(f,t,i),f}let s=(0,d.resolveSessionCurrency)(e.currency,e.items,e.subscriptions,o);if(!s)throw n.clear(),this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),new d.FloPayError("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});try{ft(e,s,o)}catch(f){throw n.clear(),this.reportSessionCreateFailure(f,t,i),f}let a,l,c=!1;try{let f=await this.postCheckoutSessionCreate(zr(e,s,o),e,n.signal,i);if(c=!0,l=await f.json(),!l.data||!("gateways"in l.data))throw new d.FloPayError("The billing API returned no session shell for a detached create. It must support `deferDataAttachment` (TeamFloPay/backend#1099).","api_error",{code:"InvalidCheckoutSessionResponse"});a=this.normalizeRawSession(this.mergeCachedDisplayData(l.data)),l.vault&&a.data.session&&(a.data.session.vault=this.toVaultBlock(l.vault))}catch(f){throw n.clear(),c&&(0,d.markSessionResponseReceived)(f),this.reportSessionCreateFailure(f,t,i),f}let u=a.data.session?.id??l.data.uuid??"",h=a.data.session?.clientSecret??l.data.nonce??"";if(!u||!h){n.clear();let f=new d.FloPayError("Checkout session shell was created without a session id or nonce.","api_error",{code:"InvalidCheckoutSessionResponse"});throw this.reportSessionCreateFailure(f,t,i),f}n.clear(),this.adoptDirectTelemetryCheckout(u),this.directTelemetry?.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",statusClass:i.statusClass,paymentMethodCategory:"card"}),this.directTelemetry?.performance({stage:"session_shell",durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:"session_create",statusClass:i.statusClass,attempt:i.attempt,paymentMethodCategory:"card"});let p=!e.account.email?.trim(),y=L(e.timeoutMs??12e3),m=this.claimCheckoutSession(u,h,p?Hr(e,s,o):ft(e,s,o),{params:e,startedAt:t,deadline:y,createAttempt:i.attempt}),g=p?void 0:m,v=(f={})=>{if(g!==void 0)return g;let S={...e,account:{...e.account,...f,email:f.email?.trim()||e.account.email?.trim()}};return(0,d.isValidEmail)(S.account.email)?(g=m.then(()=>{let C=this.telemetryTimestamp();return this.claimCheckoutSession(u,h,Kr(S.account),{params:S,startedAt:C,deadline:L(e.timeoutMs??12e3),createAttempt:0})}),g.catch(()=>{}),g):Promise.reject(new d.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}))};return m.catch(()=>{}),{shell:a,sessionId:u,nonce:h,claimed:m,claim:v}}async claimCheckoutSession(e,t,n,i){let o=i?.startedAt??this.telemetryTimestamp(),s=this.telemetryTimestamp(),a=i?.deadline??L(12e3),l=JSON.stringify(n),c="unknown",u=0,h=!1;this.directTelemetry?.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"});try{let p;for(u=0;u<3;u++){try{p=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/claim`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":t,[d.FLO_SDK_VERSION_HEADER]:d.SDK_VERSION,...this.stripeAccountSwitch?{[d.FLO_SDK_CAPABILITIES_HEADER]:yt}:{}},body:l,signal:a.signal})}catch(g){let v=a.signal.aborted||g instanceof Error&&g.name==="AbortError";if(c=v?"timeout":"network_error",v||u>=2)throw g;try{this.telemetryHooks?.onRetry?.("session_claim",u+1),this.directTelemetry?.log({name:"operation.retry",stage:"session_claim",requestCategory:"session_claim",attempt:u+1})}catch{}await te(u,a.signal);continue}if(c=(0,d.telemetryStatusClass)(p.status),p.ok)break;throw await N(p,"Failed to attach checkout session data")}if(!p)throw new TypeError("Checkout-session claim exhausted its retry budget.");h=!0;let y=await p.json();if(!y.data?.gateways)throw new d.FloPayError("The billing API returned no checkout session with gateways after claiming it.","api_error",{code:"InvalidCheckoutSessionResponse"});i?.params&&this.autoCacheDisplayData(y.data.uuid??e,i.params);let m=this.normalizeRawSession(this.mergeCachedDisplayData(y.data));return y.vault&&m.data.session&&(m.data.session.vault=this.toVaultBlock(y.vault)),this.directTelemetry?.log({name:"session.claim.completed",stage:"session_claim",requestCategory:"session_claim",statusClass:c}),this.directTelemetry?.performance({stage:"session_claim",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"session_claim",statusClass:c,attempt:u}),this.directTelemetry?.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:c}),this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"session_create",statusClass:c,attempt:i?.createAttempt??u}),m}catch(p){throw h&&(0,d.markSessionResponseReceived)(p),this.reportSessionCreateFailure(p,s,{attempt:u,statusClass:c},"session_claim"),p}finally{a.clear()}}reportSessionCreateFailure(e,t,n,i="session_create"){if(!(e instanceof d.FloPayError&&e.code==="session_auto_completed"))try{this.telemetryHooks?.onSessionCreateFailure?.(e)}catch{}let o=(0,d.classifyTelemetryFailure)(e,"CHECKOUT_SESSION_CREATE_FAILED");if(this.directTelemetry?.performance({stage:i,durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:i==="session_claim"?"session_claim":"session_create",statusClass:o.statusClass,attempt:n.attempt}),e instanceof d.FloPayError&&e.type==="validation_error"||e instanceof d.FloPayError&&pt(e.statusCode)){this.directTelemetry?.terminal({outcome:"validation_rejected",stage:i,requestCategory:i==="session_claim"?"session_claim":"session_create",...e.type==="validation_error"?{}:{statusClass:"4xx"}});return}e instanceof d.FloPayError&&e.code==="session_auto_completed"||this.directTelemetry?.error({...o,stage:i,requestCategory:i==="session_claim"?"session_claim":"session_create"})}reportThreeDsAbandoned(e){this.beginDirectTelemetryCheckout(e),this.directTelemetry?.terminal({outcome:"customer_abandoned",stage:"three_ds_handoff",paymentMethodCategory:"saved"})}beginThreeDsChallenge(e,t={}){try{return this.directTelemetry?(this.beginDirectTelemetryCheckout(e),this.directTelemetry.beginThreeDsChallenge(t)):void 0}catch{return}}async waitForCheckoutSessionCompletion(e,t){this.beginDirectTelemetryCheckout(e);let n=this.telemetryTimestamp(),i=t?.paymentMethodCategory??"saved";this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:i});let o=t?.timeoutMs??Ae,s=Date.now()+o,a=new AbortController,l=!1,c,u=setTimeout(()=>{c=setTimeout(()=>{l=!0,a.abort()},ut)},o),h=()=>a.abort(t?.signal?.reason);t?.signal?.aborted?h():t?.signal?.addEventListener("abort",h,{once:!0});let p=this.clampRetryAfterMs(t?.initialDelayMs??ct),y=0;try{if(t?.statusUrl){let m=await this.waitForCheckoutStatus(e,{initialDelayMs:p,timeoutMs:o,nonce:t.nonce,statusUrl:t.statusUrl,pollAfterAction:t.continueAfterActionRequired,signal:a.signal});if(m){let g=await this.resolveCheckoutSessionStatus(e,m,t.nonce,a.signal,()=>l);return this.reportRecoveryCompleted(n,i,t.challengeAttemptId),g}}for(;;){let m=s-Date.now();if(m<=0)throw D();if(p>0){try{y+=1,this.telemetryHooks?.onRetry?.("session_read",y),this.directTelemetry?.log({name:"operation.retry",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:i,attempt:y})}catch{}if(await Ee(Math.min(p,m),a.signal),Date.now()>=s)throw D()}let g=await this.getUnifiedCheckoutSessionForRecovery(e,t?.nonce,a.signal),v=g.data.session?.status;if(v==="authorized"||v==="complete"||v==="expired")return this.reportRecoveryCompleted(n,i,t?.challengeAttemptId),g;if(Date.now()>=s)throw D();p=this.clampRetryAfterMs(Math.max(p*2,dt))}}catch(m){let g=l&&Ve(m)?D():m;throw this.reportDirectFailure(g,"RECOVERY_FAILED","recovery","session_read",i),g}finally{clearTimeout(u),clearTimeout(c),t?.signal?.removeEventListener("abort",h)}}reportRecoveryCompleted(e,t,n){let i={stage:"recovery",requestCategory:"session_read",paymentMethodCategory:t};if(this.directTelemetry?.log({name:"operation.recovery.completed",...i}),n)try{this.directTelemetry?.beginThreeDsChallenge({attemptId:n}).record("recovery_read_completed",{evidenceBasis:"server_status"})}catch{}this.directTelemetry?.performance({...i,durationMs:Math.max(0,this.telemetryTimestamp()-e),durationMode:"machine"})}async resolveCheckoutSessionStatus(e,t,n,i,o){let s=t.latestTransactionAttempt;if(this.rememberReportedFailure(e,t),s?.result==="DECLINE"){let c=s.code===d.STORED_PAYMENT_METHOD_UNSUPPORTED_CODE;throw new d.FloPayError(c?d.STORED_PAYMENT_METHOD_UNSUPPORTED_MESSAGE:"Payment was declined. Please choose another payment method.","api_error",{code:s.code??s.declineReason??"authorization_declined",statusCode:400})}if(s?.result==="ERROR"||t.status==="voided")throw br("Payment could not be completed. Please try again.",s?.code??"payment_processing_error");let a;try{a=await this.getUnifiedCheckoutSessionForRecovery(e,n,i)}catch(c){if(!o?.()||!Ve(c))throw c;a={providers:[],mode:"tokenize",data:{},raw:t}}let l=a.data.session;return l&&s?.result==="SUCCESS"?{...a,data:{...a.data,session:{...l,status:"complete"}}}:l&&s?.result==="AUTHORIZED"?{...a,data:{...a.data,session:{...l,status:"authorized",paymentId:t.paymentId??void 0,authorizationExpiresAt:t.authorizationExpiresAt??void 0}}}:l&&t.status==="completed"?{...a,data:{...a.data,session:{...l,status:"complete"}}}:l&&t.status==="authorized"?{...a,data:{...a.data,session:{...l,status:"authorized",paymentId:t.paymentId??void 0,authorizationExpiresAt:t.authorizationExpiresAt??void 0}}}:l&&t.status==="expired"?{...a,data:{...a.data,session:{...l,status:"expired"}}}:s?.result!=="ACTION_REQUIRED"?a:s.gateway==="paypal"&&s.providerIntentId?{...a,autoProcessingError:{type:"paypal_direct_required",message:"PayPal authorization required",orderId:s.providerIntentId,checkoutMethod:"paypal"}}:s.nextActionRedirectUrl?{...a,autoProcessingError:{type:"3ds_required",message:"Additional authentication is required.",nextActionRedirectUrl:s.nextActionRedirectUrl}}:a}async waitForCheckoutStatus(e,t){let n=t.timeoutMs??Ae,i=Date.now()+n,o=this.clampRetryAfterMs(t.initialDelayMs);for(;;){let s=i-Date.now();if(s<=0||o>0&&(await Ee(Math.min(o,s),t.signal),Date.now()>=i))throw D();let a=i-Date.now();if(a<=0)throw D();let l=new AbortController,c,u=t.signal?new Promise((S,C)=>{c=C}):null,h=()=>{l.abort(t.signal?.reason),c?.(t.signal?.reason??Object.assign(new Error("The operation was aborted."),{name:"AbortError"}))};t.signal?.aborted?h():t.signal?.addEventListener("abort",h,{once:!0});let p,y=t.signal?null:new Promise((S,C)=>{p=setTimeout(()=>{C(D()),l.abort()},a+ut)}),m;try{let S=this.fetchCheckoutStatus(e,t.nonce,t.statusUrl,l.signal);m=await Promise.race([S,y,u].filter(C=>C!==null))}finally{p!==void 0&&clearTimeout(p),t.signal?.removeEventListener("abort",h)}if(!m)return null;let g=lt(m.latestTransactionAttempt)&&!this.isOwnFailedAttempt(e,m,t.submittedIntentId);if(m.status==="completed"||m.status==="authorized"||m.status==="expired"||m.status==="voided")return g?{...m,latestTransactionAttempt:null}:m;let v=m.latestTransactionAttempt?.result,f=t.pollAfterAction===!0&&v==="ACTION_REQUIRED";if(!g&&v!==void 0&&v!=="PENDING"&&!f)return m;o=this.clampRetryAfterMs(Math.max(o*2,dt))}}isOwnFailedAttempt(e,t,n){let i=t.latestTransactionAttempt?.providerIntentId??null;return n!==void 0?i===n:i===null?!0:!wr(t.uuid||e,i)}rememberReportedFailure(e,t){let n=t.latestTransactionAttempt;!lt(n)||!n.providerIntentId||Rr(t.uuid||e,n.providerIntentId)}async fetchCheckoutStatus(e,t,n,i){let o=`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/status`,s=o;if(n)try{let u=new URL(n,`${this.baseUrl}/`),h=new URL(o);u.origin===h.origin&&(s=u.toString())}catch{}let a={[d.FLO_SDK_VERSION_HEADER]:d.SDK_VERSION};t&&(a["x-checkout-session-token"]=t);let l=await ke(s,{headers:a,signal:i});if(l.status===404||l.status===405)return null;if(!l.ok)throw await N(l,"Failed to get checkout session status");let c=await l.json();return pe(c.data)&&"latestTransactionAttempt"in c.data?c.data:null}normalizeRawSession(e){let t=e.gateways??{},n=[],i={session:this.toCheckoutSession(e)},o=t.stripe;if(o?.publishableKey){n.push("stripe");let l=[e.stripeClientSecret,o.stripeClientSecret].find(c=>typeof c=="string"&&c.length>0);i.stripe={clientSecret:l??"",publishableKey:o.publishableKey??void 0,paypalPublishableKey:o.paypalPublishableKey??void 0,environment:o.environment,enabledPaymentMethods:Array.isArray(o.enabledPaymentMethods)?o.enabledPaymentMethods.filter(c=>typeof c=="string"):void 0}}let s=t.paypal;return s?.publishableKey&&(n.push("paypal"),i.paypal={publishableKey:s.publishableKey,environment:s.environment,providerObjectType:s.providerObjectType,approvalPresentation:s.approvalPresentation}),{providers:n,mode:"tokenize",...e.checkoutMetadata===void 0?{}:{checkoutMetadata:e.checkoutMetadata},data:i,raw:{data:e}}}toCheckoutSession(e){let t=e.products??[],n=typeof e.totalAmount=="number"&&Number.isFinite(e.totalAmount),i=t.reduce((c,u)=>c+(u.overrideAmount??u.totalAmount??0),0),o=n?e.totalAmount:i,s=Math.round(o*100),a=e.currency??t[0]?.currency??"USD",l="payment";return e.checkoutMode==="setup"?l="setup":t.some(c=>c.type==="subscription")&&(l="subscription"),{id:e.uuid,clientSecret:e.nonce,mode:l,status:this.toCheckoutSessionStatus(e.status),amount:s,currency:a,captureMethod:e.captureMethod,paymentId:e.paymentId,authorizationExpiresAt:e.authorizationExpiresAt,failureOutcome:(0,d.normalizeCheckoutFailureOutcome)(e.outcome)??(0,d.normalizeCheckoutFailureOutcome)(e.failureReason)??(e.status==="expired"&&e.captureMethod==="manual"?"authorization_expired":void 0),customer:{id:e.accountData.userId??void 0,email:e.accountData.email??void 0,firstName:e.accountData.firstName??void 0,lastName:e.accountData.lastName??void 0,country:e.accountData.country??void 0,city:e.accountData.city??void 0,state:e.accountData.state??void 0,zip:e.accountData.zip??void 0,gender:e.accountData.gender??void 0,line1:e.accountData.addressLine1??void 0,line2:e.accountData.addressLine2??void 0},...e.checkoutMetadata===void 0?{}:{checkoutMetadata:e.checkoutMetadata},metadata:{},checkoutMode:e.checkoutMode,...Array.isArray(e.advertisedPaymentMethods)?{advertisedPaymentMethods:e.advertisedPaymentMethods}:{},...gr(e.futureUse)?{futureUse:e.futureUse}:{},...Array.isArray(e.futureUseUnsupported)?{futureUseUnsupported:e.futureUseUnsupported.filter(fr)}:{},buyerIdentified:e.buyerIdentified,providerPaymentMethodId:typeof e.providerPaymentMethodId=="string"?e.providerPaymentMethodId:null,products:t.map(c=>({...c,totalAmount:typeof c.totalAmount=="number"?c.totalAmount:void 0,overrideAmount:typeof c.overrideAmount=="number"?c.overrideAmount:null,currency:typeof c.currency=="string"?c.currency:void 0,metadata:c.metadata??null})),successUrl:e.successUrl,cancelUrl:e.cancelUrl,coupons:e.coupons,subtotalAmount:e.subtotalAmount,discountAmount:e.discountAmount,totalAmount:e.totalAmount,createdAt:e.createdAt,gateways:e.gateways,accountData:e.accountData,tagsData:e.tagsData}}toVaultBlock(e){let t=Dr(e.verification);return{html:typeof e.html=="string"?e.html:void 0,url:typeof e.url=="string"?e.url:void 0,messageToken:typeof e.messageToken=="string"?e.messageToken:void 0,expectedOrigin:typeof e.expectedOrigin=="string"?e.expectedOrigin:void 0,...t?{verification:t}:{}}}toCheckoutSessionStatus(e){return e==="completed"?"complete":e==="authorized"?"authorized":e==="expired"?"expired":"open"}async resolveProcessResponse(e,t,n){if(e.status!==202)return e;let i=await e.json().catch(()=>null),o=this.toCheckoutProcessingPending(i,e,t);return this.resolveCheckoutProcessing(o,t,n)}async resolveCheckoutProcessing(e,t,n){let i=n?.pollTimeoutMs??Ae,o=Date.now()+i;if(e.statusUrl){let a=await this.waitForCheckoutStatus(e.sessionId,{initialDelayMs:e.retryAfterMs,timeoutMs:i,nonce:n?.nonce,statusUrl:e.statusUrl,submittedIntentId:n?.submittedIntentId});if(a)return this.toProcessResponseFromStatus(a,t,n?.nonce)}let s=await this.waitForCheckoutSessionCompletion(e.sessionId,{initialDelayMs:e.retryAfterMs,timeoutMs:o-Date.now(),nonce:n?.nonce,paymentMethodCategory:n?.paymentMethodCategory});return this.toProcessResponseFromSession(s,t)}async toProcessResponseFromStatus(e,t,n){let i=e.latestTransactionAttempt?.result,o={[vr]:Tr},s={"Content-Type":"application/json",...o};if(e.status==="completed"||i==="SUCCESS")return new Response(null,{status:204,statusText:"No Content",headers:o});if(e.status==="authorized"||i==="AUTHORIZED")return new Response(JSON.stringify({status:"authorized",paymentId:e.paymentId??void 0,sessionId:e.uuid||t,authorizationExpiresAt:e.authorizationExpiresAt??void 0}),{status:200,headers:s});if(e.status==="expired"){let a=await this.resolveCheckoutSessionStatus(t,e,n);return this.toProcessResponseFromSession(a,t)}if(this.rememberReportedFailure(t,e),i==="DECLINE"){let a=e.latestTransactionAttempt,l=a?.code===d.STORED_PAYMENT_METHOD_UNSUPPORTED_CODE,c=a?.declineReason??void 0;return new Response(JSON.stringify({type:c??"authorization_declined",message:l?d.STORED_PAYMENT_METHOD_UNSUPPORTED_MESSAGE:"Payment was declined. Please choose another payment method.",code:a?.code??c??"authorization_declined",...c?{declineCode:c}:{}}),{status:400,headers:s})}if(i==="ACTION_REQUIRED"&&e.latestTransactionAttempt?.gateway==="paypal"&&e.latestTransactionAttempt.providerIntentId)return new Response(JSON.stringify({type:"paypal_direct_required",message:"PayPal authorization required",orderId:e.latestTransactionAttempt.providerIntentId}),{status:400,headers:s});if(i==="ACTION_REQUIRED"&&e.latestTransactionAttempt?.nextActionRedirectUrl)return new Response(JSON.stringify({type:"3ds_required",message:"Additional authentication is required.",nextActionRedirectUrl:e.latestTransactionAttempt.nextActionRedirectUrl}),{status:400,headers:s});if(i==="ERROR"||e.status==="voided")return new Response(JSON.stringify({type:"unknown",code:e.latestTransactionAttempt?.code??"payment_processing_error",message:Cr(e)??"Payment could not be completed. Please try again."}),{status:500,headers:s});throw D()}async reconcileProcessPayment(e,t){let n=t?.pollTimeoutMs??Ae,i=Date.now()+n,o=null;try{o=await this.waitForCheckoutStatus(e,{initialDelayMs:0,timeoutMs:n,nonce:t?.nonce,submittedIntentId:t?.submittedIntentId})}catch(l){if(this.reportDirectFailure(l,"RECOVERY_FAILED","recovery","session_read",t?.paymentMethodCategory??"saved"),l instanceof d.FloPayError&&l.code==="checkout_processing_timeout")throw l}if(o)return this.toProcessResponseFromStatus(o,e,t?.nonce);let s=i-Date.now();if(s<=0)throw D();let a=await this.waitForCheckoutSessionCompletion(e,{initialDelayMs:0,timeoutMs:s,nonce:t?.nonce,paymentMethodCategory:t?.paymentMethodCategory});return this.toProcessResponseFromSession(a,e)}toProcessResponseFromSession(e,t){if(e.data.session?.status==="complete")return new Response(null,{status:204,statusText:"No Content"});if(e.data.session?.status==="authorized"){let n=e.data.session;return new Response(JSON.stringify({status:"authorized",paymentId:n.paymentId,sessionId:n.id||t,authorizationExpiresAt:n.authorizationExpiresAt}),{status:200,headers:{"Content-Type":"application/json"}})}if(e.data.session?.status==="expired"){let n=e.data.session.failureOutcome==="authorization_expired"||e.data.session.captureMethod==="manual";throw new d.FloPayError(n?"Authorization has expired.":"Checkout session has expired.","api_error",{code:n?"authorization_expired":"checkout_session_expired"})}throw D()}toCheckoutProcessingPending(e,t,n){let i=t.headers.get("Retry-After"),o=i===null||i.trim()===""?void 0:Number(i),s=o!==void 0&&Number.isFinite(o)?o*1e3:void 0;return{type:"checkout_processing",sessionId:K(e,"sessionId")??n,retryAfterMs:this.clampRetryAfterMs(Ir(e,"retryAfterMs")??s??ct),statusUrl:K(e,"statusUrl"),sessionUrl:K(e,"sessionUrl")}}clampRetryAfterMs(e){return Math.max(0,Math.min(e,kr))}autoCacheDisplayData(e,t){if(!e)return;let n=t.products??(0,d.foldIntoProducts)(t.items,t.subscriptions);if(n.length===0&&!t.currency)return;let i=t.products!==void 0,o=(0,d.resolveSessionCurrency)(t.currency,i?void 0:t.items,i?void 0:t.subscriptions,n);W(e,{currency:o??void 0,products:n.map(s=>({code:s.code??s.providerItemId??s.providerPlanId,type:s.type,name:s.name??s.itemName??s.providerItemName??s.subscriptionName??s.providerPlanName??null,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount,currency:s.currency??o??void 0}))})}mergeCachedDisplayData(e){let t=ve(e.uuid),n=new Map,i=s=>s?`code:${s}`:void 0;for(let s of t?.products??[]){let a=i(s.code);a&&n.set(a,s)}let o=(e.products??[]).map(s=>{let a=i(s.code),l=a?n.get(a):void 0;return{...s,name:s.name??l?.name??null,totalAmount:s.totalAmount??l?.totalAmount,overrideAmount:s.overrideAmount??l?.overrideAmount,currency:s.currency??l?.currency}});return{...e,currency:e.currency??t?.currency,products:o}}};O.activeVaultCaptureRequests=new Map,O.pendingThreeDsAbandonReports=new Map;var Q=O;function bt(r,e){let t=Q;return new t(r,e)}var _=require("@flopay/shared");var Pe=require("@flopay/shared");function _t(r){if(!r)return null;try{let e=new URL(r,window.location.href);return e.origin==="null"?null:e.origin}catch{return null}}var Ie=class{constructor(e){this.options=e;this.handlers=new Set;this.active=!1;this.readyReported=!1;this.failureReported=!1;this.startedAt=0;this.timer=null;this.detach=null}subscribe(e){return this.handlers.add(e),()=>{this.handlers.delete(e)}}begin(){this.end(),this.active=!0,this.readyReported=!1,this.failureReported=!1,this.startedAt=this.options.now();let e=(0,Pe.resolveCardFieldsTimeoutMs)(this.options.timeoutMs);this.timer=setTimeout(()=>{this.timer=null,this.reportFailure("timeout",e)},e)}watch(e){if(!this.active)return;this.detachWatchers();let t=new Set,n=[];for(let o of Array.from(e.querySelectorAll("script[src], iframe[src]"))){let s=_t(o.getAttribute("src"));if(s&&t.add(s),o.tagName==="SCRIPT"){let a=()=>this.fail("load_error");o.addEventListener("error",a),n.push(()=>o.removeEventListener("error",a))}}let i=o=>{let s=_t(o.blockedURI);s&&t.has(s)&&this.fail("blocked")};document.addEventListener("securitypolicyviolation",i),n.push(()=>document.removeEventListener("securitypolicyviolation",i)),this.detach=()=>{for(let o of n)o()}}ready(){!this.active||this.readyReported||(this.readyReported=!0,this.clearTimer(),this.detachWatchers(),this.dispatch({type:"card_fields_ready",elapsedMs:this.elapsed()}))}fail(e){this.reportFailure(e,0)}reportFailure(e,t){!this.active||this.readyReported||this.failureReported||(this.failureReported=!0,this.clearTimer(),this.dispatch({type:"card_fields_failed",reason:e,elapsedMs:Math.max(t,this.elapsed())}))}end(){this.active=!1,this.clearTimer(),this.detachWatchers()}elapsed(){return Math.max(0,Math.round(this.options.now()-this.startedAt))}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}detachWatchers(){this.detach?.(),this.detach=null}dispatch(e){try{this.options.report?.(e)}catch{}for(let t of Array.from(this.handlers))(0,Pe.invokeMerchantCallback)(()=>t(e))}};var $r=4,De="flopay-vault",Gr=3e4,Yr=_.THREE_DS_CHALLENGE_WINDOW_MS+Gr,Wr="Card authentication timed out.",St={ready:["vault.widget.ready","vault_ready"],submitting:["vault.submission.started","vault_submit"],blocked:["operation.state_transition","vault_submit"],action_required:["vault.action.required","three_ds_handoff"]};function Jr(r){return r.class==="lifecycle"?r.name:r.class==="technical_error"?r.code:r.class==="expected_outcome"?r.outcome:"sdk.performance"}function ne(r){let e={class:r.class,stage:r.stage};"code"in r&&(e.code=r.code),"provider"in r&&r.provider&&(e.provider=r.provider),"paymentMethodCategory"in r&&r.paymentMethodCategory&&(e.paymentMethodCategory=r.paymentMethodCategory),"outcome"in r&&(e.outcome=r.outcome),"durationMs"in r&&r.durationMs!==void 0&&(e.durationMs=r.durationMs),"durationMode"in r&&r.durationMode&&(e.durationMode=r.durationMode);try{globalThis.Sentry?.addBreadcrumb?.({category:"flopay.telemetry",level:r.class==="technical_error"?"error":"info",message:Jr(r),data:e})}catch{}}function he(r,e){return(0,_.buildTelemetryLogEvent)({eventId:"11111111-1111-4111-8111-111111111111",name:r,stage:e,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}var Qr=new Set(["authorization_declined","authentication_required","authorization_expired","capture_failed"]);function Xr(r){return typeof r=="string"&&Qr.has(r)?r:"unknown"}var Zr=new Set(["verification_failed","verification_expired"]);function en(r){return r==null?!0:typeof r=="string"&&Zr.has(r)}var tn="vault_mount";function rn(r){return r.failureStage===tn}function je(r,e){return r&&!rn(e)?{errorCode:"VAULT_SUBMIT_FAILED",stage:"vault_submit",failureCategory:"provider_runtime",reason:Xr(e.failureOutcome)}:{errorCode:"VAULT_LOAD_FAILED",stage:"vault_mount",failureCategory:"provider_runtime"}}function wt(r,e,t="checkout"){return t==="card_setup"?r.type==="decline"?"card_setup_declined":"card_setup_succeeded":r.type==="decline"?"payment_declined":r.outcome==="authorized"||e==="manual"?"payment_authorized":"payment_succeeded"}function nn(r,e,t,n="checkout"){let{type:i}=r;if(i==="complete"||i==="decline")return(0,_.buildTelemetryTerminalEvent)({eventId:"22222222-2222-4222-8222-222222222222",outcome:wt(r,t,n),sequence:0,provider:"pcivault",paymentMethodCategory:"card"});if(i==="error"){let a=je(e,r);return(0,_.buildTelemetryErrorEvent)({eventId:"33333333-3333-4333-8333-333333333333",...a,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}let[o,s]=St[i];return he(o,s)}function on(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===De&&(e.type==="ready"||e.type==="submitting"||e.type==="blocked"||e.type==="complete"||e.type==="decline"||e.type==="error"||e.type==="action_required")}function sn(r){if(typeof r!="object"||r===null)return;let e=r;if(typeof e.code!="string"||e.code.trim()==="")return;let t=typeof e.message=="string"&&e.message.trim()!==""?e.message:void 0;return t?{code:e.code,message:t}:{code:e.code}}function an(r){if(typeof r!="object"||r===null)return;let e=r,t=e.status;if(!(typeof e.id!="string"||e.id.trim()===""||typeof e.brand!="string"||e.brand.trim()===""||typeof e.lastFour!="string"||!/^\d{4}$/.test(e.lastFour)||typeof e.expiryMonth!="number"||!Number.isInteger(e.expiryMonth)||e.expiryMonth<1||e.expiryMonth>12||typeof e.expiryYear!="number"||!Number.isInteger(e.expiryYear)||e.expiryYear<1970||e.expiryYear>9999||t!=="pending"&&t!=="active"&&t!=="deleted"))return{id:e.id,brand:e.brand,lastFour:e.lastFour,expiryMonth:e.expiryMonth,expiryYear:e.expiryYear,status:t}}function ln(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===De&&e.type==="validation"&&Array.isArray(e.messages)}function cn(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===De&&e.type==="resize"&&typeof e.height=="number"&&Number.isFinite(e.height)}function dn(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===De&&e.type==="fields_interactive"}function un(r){let e=r.capabilities;return Array.isArray(e)&&e.includes("fields_interactive")}var mn=["number","expiry","cvv","name"];function pn(r){if(r===null||typeof r!="object")return;let e=r,t={};for(let n of mn){let i=e[n];typeof i=="string"&&(t[n]=i)}return t}var X=class{constructor(e={},t){this.provider="pcivault";this.container=null;this.messageHandler=null;this.actionOverlay=null;this.threeDsReturnHandler=null;this.actionChallenge=null;this.lastChallengeTelemetry=null;this.actionOverlayPreviousFocus=null;this.actionOverlayTimer=null;this.actionChallengeIntentId=null;this.messageToken=null;this.expectedOrigin=null;this.theme=void 0;this.submitGateBlocked=!1;this.cardFieldOrder=null;this.cardAutoFocus=!0;this.cardBrandIcons=!1;this.showCardFieldLabels=void 0;this.cardFieldLabels=void 0;this.submitLabel=void 0;this.cardFieldPlaceholders=void 0;this.mountStartedAt=0;this.vaultReadyReported=!1;this.verificationRequired=!1;this.submissionStarted=!1;this.submissionStartedAt=null;this.listeners=new Map;this.config=e,this.cardFields=new Ie({timeoutMs:e.cardFieldsTimeoutMs,now:()=>this.telemetryReporter?.now?.()??E(),report:n=>this.reportCardFields(n)}),this.ownsTelemetryReporter=!t&&e.telemetry!==!1,this.telemetryReporter=t?.reporter??(this.ownsTelemetryReporter?new A({billingApiUrl:(0,_.resolveBillingApiUrl)(e.billingApiUrl),sdkVersion:_.SDK_VERSION}):void 0)}async mount(e,t){this.ownsTelemetryReporter&&!this.telemetryReporter&&(this.telemetryReporter=new A({billingApiUrl:(0,_.resolveBillingApiUrl)(this.config.billingApiUrl),sdkVersion:_.SDK_VERSION}));let n=this.telemetryReporter;if(this.config.operation==="card_setup"&&n&&this.setupTelemetryReporter!==n){this.setupTelemetryReporter=n;try{n.beginCheckout({checkoutMode:"setup"})}catch{}}if(this.mountStartedAt=this.telemetryReporter?.now?.()??E(),this.vaultReadyReported=!1,this.submissionStarted=!1,this.submissionStartedAt=null,this.cardFields.begin(),typeof window>"u"||typeof document>"u")throw this.reportVaultLoadFailure(),this.failCardFieldsMount(),new _.FloPayError("The vault card form is only available in the browser.","api_error",{code:"card_capture_no_window"});if(!t?.html?.trim())throw this.reportVaultLoadFailure(),this.failCardFieldsMount(),new _.FloPayError("No vault capture widget HTML was provided to mount the secure card form.","api_error",{code:"card_capture_no_widget_html"});this.container=e,this.verificationRequired=t.verificationRequired===!0,this.messageToken=t.messageToken??null,this.expectedOrigin=t.expectedOrigin??this.config.expectedOrigin??null,this.theme=t.theme,t.submitLabel!==void 0&&(this.submitLabel=t.submitLabel);try{this.attachMessageListener(),this.injectWidget(e,t.html),this.cardFields.watch(e)}catch(i){throw this.reportVaultLoadFailure(),this.failCardFieldsMount(),i}this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),this.postCardBrandIcons(),this.postCardFieldLabels(),this.postCardFieldPlaceholders(),this.postSubmitLabel(),ne(he("vault.widget.mounted","vault_mount")),this.telemetryReporter?.log({name:"vault.widget.mounted",stage:"vault_mount",provider:"pcivault",paymentMethodCategory:"card"}),this.telemetryReporter?.performance?.({stage:"vault_mount",durationMs:Math.max(0,(this.telemetryReporter.now?.()??E())-this.mountStartedAt),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card"}),this.emit("ready",{sessionId:this.config.sessionId})}reportVaultLoadFailure(){this.telemetryReporter?.error({errorCode:"VAULT_LOAD_FAILED",failureCategory:"provider_runtime",stage:"vault_mount",provider:"pcivault",paymentMethodCategory:"card"})}on(e,t){let n=this.listeners.get(e);return n||(n=new Set,this.listeners.set(e,n)),n.add(t),()=>{this.listeners.get(e)?.delete(t)}}onCardFields(e){return this.cardFields.subscribe(e)}failCardFieldsMount(){this.cardFields.fail("other"),this.cardFields.end()}reportCardFields(e){let t=e.type==="card_fields_ready",n=this.config.sessionId;this.telemetryReporter?.log({name:t?"vault.fields.ready":"vault.fields.failed",stage:t?"vault_ready":"vault_mount",provider:"pcivault",paymentMethodCategory:"card",elapsedMs:e.elapsedMs,...e.type==="card_fields_failed"?{loadFailureReason:e.reason}:{},...n?{checkoutSessionId:n}:{}})}unmount(){if(this.cardFields.end(),this.actionChallenge){let{telemetry:e}=this.actionChallenge;e.record("abort_observed",{reason:"component_unmount",evidenceBasis:"signal_reason"}),e.terminal("abort",{reason:"component_unmount",evidenceBasis:"signal_reason"})}this.lastChallengeTelemetry=null,this.hideActionRequiredOverlay(),this.messageHandler&&(window.removeEventListener("message",this.messageHandler),this.messageHandler=null),this.container&&(this.container.replaceChildren(),this.container=null),this.messageToken=null,this.expectedOrigin=null,this.ownsTelemetryReporter&&(this.telemetryReporter?.destroy(),this.telemetryReporter=void 0)}injectWidget(e,t){e.innerHTML=t;let n=Array.from(e.querySelectorAll("script"));for(let i of n){let o=document.createElement("script");for(let s of Array.from(i.attributes))o.setAttribute(s.name,s.value);o.text=i.text,i.replaceWith(o)}}attachMessageListener(){if(this.messageHandler)return;let e=t=>{if(this.expectedOrigin&&t.origin!==this.expectedOrigin)return;let n=t.data;if(cn(n)){if(this.messageToken&&n.messageToken!==this.messageToken)return;this.applyHeight(n.height);return}if(ln(n)){if(this.messageToken&&n.messageToken!==this.messageToken)return;let c=n.messages.filter(u=>typeof u=="string"&&u.trim()).join(" ");this.emit("validation",{sessionId:this.config.sessionId,message:c||void 0});return}if(dn(n)){if(this.messageToken&&n.messageToken!==this.messageToken)return;let c=typeof n.sessionId=="string"?n.sessionId:void 0;if(this.config.sessionId&&c&&c!==this.config.sessionId)return;this.cardFields.ready();return}if(!on(n)||this.messageToken&&n.messageToken!==this.messageToken)return;let i=this.config.sessionId,o=typeof n.sessionId=="string"?n.sessionId:void 0;if(i&&o&&o!==i||(n.type==="complete"||n.type==="decline")&&i&&o!==i)return;let s=an(n.paymentMethod),a=sn(n.vaultOutcome),l={...n.sessionId??this.config.sessionId?{sessionId:n.sessionId??this.config.sessionId}:{},...n.outcome?{outcome:n.outcome}:{},...n.paymentId?{paymentId:n.paymentId}:{},...n.authorizationExpiresAt?{authorizationExpiresAt:n.authorizationExpiresAt}:{},...n.failureOutcome?{failureOutcome:n.failureOutcome}:{},...n.intentId?{intentId:n.intentId}:{},...n.declineReason?{declineReason:n.declineReason}:{},...n.message?{message:n.message}:{},...a?{vaultOutcome:a}:{},...s?{paymentMethod:s}:{}};n.type==="submitting"&&(this.submissionStarted=!0,this.submissionStartedAt=this.telemetryReporter?.now?.()??E()),this.isVerificationStateError(n)?(ne(he("operation.state_transition","vault_mount")),this.telemetryReporter?.log({name:"operation.state_transition",stage:"vault_mount",provider:"pcivault",paymentMethodCategory:"card"})):(ne(nn(n,this.submissionStarted,this.config.captureMethod,this.config.operation)),this.reportOutcome(n),n.type==="error"&&je(this.submissionStarted,n).errorCode==="VAULT_LOAD_FAILED"&&this.cardFields.fail("load_error")),n.type==="ready"&&(this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),this.postCardBrandIcons(),this.postCardFieldLabels(),this.postCardFieldPlaceholders(),this.postSubmitLabel(),un(n)||this.cardFields.ready()),n.type==="action_required"&&n.nextActionRedirectUrl&&(this.showActionRequiredOverlay(n.nextActionRedirectUrl),this.actionOverlay&&typeof n.intentId=="string"&&n.intentId&&(this.actionChallengeIntentId=n.intentId)),(n.type==="complete"||n.type==="decline"||n.type==="error"||n.type==="submitting")&&(this.endActionChallengeFromWidget(n.type),this.hideActionRequiredOverlay()),n.type!=="action_required"&&this.emit(n.type,l)};this.messageHandler=e,window.addEventListener("message",e)}isVerificationStateError(e){return e.type==="error"&&this.verificationRequired&&!this.submissionStarted&&en(e.failureOutcome)}reportOutcome(e){let t=this.telemetryReporter;if(!t)return;let{type:n}=e;if(n==="ready"&&!this.vaultReadyReported&&(this.vaultReadyReported=!0,t.performance({stage:"vault_ready",durationMs:Math.max(0,t.now()-this.mountStartedAt),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card",requestCategory:"provider_sdk"})),n==="complete"||n==="decline"){t.log({name:"vault.terminal",stage:"completion",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:wt(e,this.config.captureMethod,this.config.operation),provider:"pcivault",paymentMethodCategory:"card"});return}if(n==="error"){let s=je(this.submissionStarted,e);t.log({name:"vault.terminal",stage:s.stage,provider:"pcivault",paymentMethodCategory:"card"}),t.error({...s,provider:"pcivault",paymentMethodCategory:"card"});return}if(n==="action_required"){t.log({name:"vault.action.required",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"}),t.log({name:"vault.three_ds.handoff",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"});let s=this.submissionStartedAt;this.submissionStartedAt=null,s!==null&&t.performance({stage:"three_ds_handoff",durationMs:Math.max(0,t.now()-s),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:"action_required",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"});return}let[i,o]=St[n];t.log({name:i,stage:o,provider:"pcivault",paymentMethodCategory:"card"})}applyTheme(e){this.theme=e,this.postTheme()}postTheme(){this.theme!==void 0&&this.postToHostedWindow({source:"flopay-vault-host",type:"theme",theme:this.theme},this.directiveTargetOrigin())}setSubmitGate(e){this.submitGateBlocked=e,this.postSubmitGate()}postSubmitGate(){this.postToHostedWindow({source:"flopay-vault-host",type:"gate",blocked:this.submitGateBlocked},this.directiveTargetOrigin())}setCardFieldOrder(e,t){this.cardFieldOrder=e,this.cardAutoFocus=t,this.postCardFieldOrder()}postCardFieldOrder(){this.postToHostedWindow({source:"flopay-vault-host",type:"fieldOrder",order:this.cardFieldOrder,autoFocus:this.cardAutoFocus},this.directiveTargetOrigin())}setCardBrandIcons(e){this.cardBrandIcons=e===!0,this.postCardBrandIcons()}setShowCardFieldLabels(e){this.showCardFieldLabels=e===!0,this.postCardFieldLabels()}setCardFieldLabels(e){this.cardFieldLabels=(0,_.buildCardFieldLabelsPayload)(e),this.postCardFieldLabels()}postCardFieldLabels(){let e=this.showCardFieldLabels,t=this.cardFieldLabels;if(e===void 0&&t===void 0)return;let n=this.config.sessionId,{messageToken:i,expectedOrigin:o}=this;!n||!i||!o||this.postToHostedWindow({source:"flopay-vault-host",type:"cardFieldLabels",sessionId:n,messageToken:i,...e===void 0?{}:{show:e},...t===void 0?{}:{labels:{...t}}},o)}setCardFieldPlaceholders(e){let t=pn(e),n=t===void 0&&this.cardFieldPlaceholders!==void 0;this.cardFieldPlaceholders=t,this.postCardFieldPlaceholders(n?{}:t)}postCardFieldPlaceholders(e=this.cardFieldPlaceholders){let t=this.config.sessionId,{messageToken:n,expectedOrigin:i}=this;e===void 0||!t||!n||!i||this.postToHostedWindow({source:"flopay-vault-host",type:"cardFieldPlaceholders",sessionId:t,messageToken:n,placeholders:{...e}},i)}postCardBrandIcons(){this.postToHostedWindow({source:"flopay-vault-host",type:"cardBrandIcons",show:this.cardBrandIcons},this.directiveTargetOrigin())}setSubmitLabel(e){this.submitLabel=e,this.postSubmitLabel()}postSubmitLabel(){let e=this.submitLabel,t=this.config.sessionId,{messageToken:n,expectedOrigin:i}=this;e===void 0||!t||!n||!i||this.postToHostedWindow({source:"flopay-vault-host",type:"submitLabel",sessionId:t,messageToken:n,label:e},i)}hostedWindow(){return this.container?.querySelector("iframe")?.contentWindow??null}postToHostedWindow(e,t){let n=this.hostedWindow();if(n)try{n.postMessage(e,t)}catch{}}directiveTargetOrigin(){return this.expectedOrigin??"*"}emit(e,t){for(let n of this.listeners.get(e)??[])n(t)}showActionRequiredOverlay(e){if(typeof document>"u")return;if(this.actionOverlay){let m=this.actionOverlay.querySelector("iframe");m instanceof HTMLIFrameElement&&m.src!==e&&(m.src=e),this.armActionRequiredTimeout();return}this.actionOverlayPreviousFocus=document.activeElement instanceof HTMLElement?document.activeElement:null;let t=de(this.beginActionChallengeAttempt()),n=Se(e),i=!1,o=m=>{if(i)return;let g=_e(m,n);g&&(i=!0,t.record("policy_violation",{reason:g,evidenceBasis:"parent_csp_event"}))},s=()=>{t.record("pagehide_observed",{evidenceBasis:"page_lifecycle_event"})},a={telemetry:t,loaded:!1,detach:()=>{document.removeEventListener("securitypolicyviolation",o),window.removeEventListener("pagehide",s)}};this.actionChallenge=a,this.lastChallengeTelemetry=t,t.record("handoff_planned"),ue(e)==="invalid"&&t.record("action_invalid",{reason:"invalid_url"}),document.addEventListener("securitypolicyviolation",o),window.addEventListener("pagehide",s);let l=document.createElement("div");l.setAttribute("data-flopay-action-required","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 c=document.createElement("iframe");c.setAttribute("title","Card authentication"),c.setAttribute("allow","payment"),c.tabIndex=0,c.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(";"),c.addEventListener("load",()=>{a.loaded||(a.loaded=!0,t.record("iframe_load",{evidenceBasis:"iframe_load_event"}))}),c.src=e,l.appendChild(c);let u=document.createElement("button");u.type="button",u.setAttribute("aria-label","Close card authentication"),u.textContent="\xD7",u.style.cssText=["position:fixed","top:20px","right:20px","width:40px","height:40px","border:0","border-radius:9999px","background:#fff","color:#0f172a","font-size:28px","line-height:40px","cursor:pointer","box-shadow:0 4px 14px rgba(0,0,0,0.25)"].join(";"),u.addEventListener("click",()=>this.abandonActionRequiredOverlay()),l.appendChild(u),l.addEventListener("click",m=>{m.target===l&&this.abandonActionRequiredOverlay()});let h=0,p=m=>{let g=m.data,v=!!g&&typeof g=="object"&&g.source==="flopay-vault-3ds-return";if(m.source!==c.contentWindow){v&&h<$r&&(h+=1,t.record("return_rejected",{reason:"untrusted_source",evidenceBasis:"message_origin_check"}));return}v&&(t.record("trusted_return",{evidenceBasis:"message_origin_check"}),t.terminal("trusted_return",{evidenceBasis:"message_origin_check"}),ne(he("vault.three_ds.returned","three_ds_return")),this.telemetryReporter?.log({name:"vault.three_ds.returned",stage:"three_ds_return",provider:"pcivault",paymentMethodCategory:"card"}),this.hideActionRequiredOverlay())};window.addEventListener("message",p),this.threeDsReturnHandler=p,t.record("render_attempted");try{document.body.appendChild(l)}catch(m){throw t.record("render_failed"),this.hideActionRequiredOverlay(),this.actionOverlayPreviousFocus=null,m}t.record("container_attached"),t.record("navigation_assigned");let y=be(l);y&&t.record("container_visibility",{reason:y,evidenceBasis:"parent_computed_style"}),this.actionOverlay=l,c.focus(),this.armActionRequiredTimeout(),ne(he("vault.three_ds.handoff","three_ds_handoff"))}armActionRequiredTimeout(){this.actionOverlayTimer&&clearTimeout(this.actionOverlayTimer),this.actionOverlayTimer=setTimeout(()=>{this.actionOverlayTimer=null,this.actionOverlay&&this.timeOutActionRequiredOverlay()},Yr)}reportChallengeAbandoned(){ne((0,_.buildTelemetryTerminalEvent)({eventId:"77777777-7777-4777-8777-777777777777",outcome:"customer_abandoned",stage:"three_ds_handoff",sequence:0,provider:"pcivault",paymentMethodCategory:"card"})),this.telemetryReporter?.terminal({outcome:"customer_abandoned",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"})}timeOutActionRequiredOverlay(){if(this.actionChallenge){let{telemetry:e,loaded:t}=this.actionChallenge;t||e.record("load_unconfirmed",{evidenceBasis:"no_load_signal"}),e.record("timer_expired",{reason:"window_elapsed",evidenceBasis:"timer"}),e.terminal("timer",{reason:"window_elapsed",evidenceBasis:"timer"})}this.reportChallengeAbandoned(),this.closeAbandonedChallenge(),this.hideActionRequiredOverlay(),this.emit("error",{...this.config.sessionId?{sessionId:this.config.sessionId}:{},message:Wr})}abandonActionRequiredOverlay(){if(this.actionOverlay){if(this.actionChallenge){let{telemetry:e}=this.actionChallenge;e.record("cancel_requested",{reason:"buyer_cancel",evidenceBasis:"signal_reason"}),e.terminal("cancel",{reason:"buyer_cancel",evidenceBasis:"signal_reason"})}this.reportChallengeAbandoned(),this.closeAbandonedChallenge(),this.hideActionRequiredOverlay(),this.emit("challenge_dismissed",{...this.config.sessionId?{sessionId:this.config.sessionId}:{}})}}closeAbandonedChallenge(){let e=this.actionChallengeIntentId;this.actionChallengeIntentId=null;let{sessionId:t,sessionToken:n}=this.config;if(!(!e||!t||!n))try{new Q((0,_.resolveBillingApiUrl)(this.config.billingApiUrl),{telemetry:!1}).closeThreeDsChallenge(t,n,e).catch(()=>{})}catch{}}beginActionChallengeAttempt(){try{return this.telemetryReporter?.beginThreeDsChallenge?.()}catch{return}}endActionChallengeFromWidget(e){let t=this.actionChallenge,n=t?.telemetry??this.lastChallengeTelemetry;if(this.lastChallengeTelemetry=null,!!n){if(e==="submitting"){if(!t)return;n.record("abort_observed",{reason:"unspecified",evidenceBasis:"signal_reason"}),n.terminal("abort",{reason:"unspecified",evidenceBasis:"signal_reason"});return}t&&n.terminal("status_poll",{evidenceBasis:"server_status"}),e==="complete"&&n.reconcile("succeeded"),e==="decline"&&n.reconcile("declined")}}hideActionRequiredOverlay(){if(this.actionChallengeIntentId=null,this.actionChallenge){let t=this.actionChallenge;this.actionChallenge=null;try{t.detach()}catch{}t.telemetry.record("teardown")}if(this.actionOverlayTimer&&(clearTimeout(this.actionOverlayTimer),this.actionOverlayTimer=null),this.threeDsReturnHandler&&(window.removeEventListener("message",this.threeDsReturnHandler),this.threeDsReturnHandler=null),!this.actionOverlay)return;this.actionOverlay.parentNode?.removeChild(this.actionOverlay),this.actionOverlay=null;let e=this.actionOverlayPreviousFocus;this.actionOverlayPreviousFocus=null,e?.isConnected&&e.focus()}applyHeight(e){let t=this.container?.querySelector("iframe");if(!t)return;let n=Math.max(0,Math.min(Math.ceil(e),2e3));t.style.height=`${n}px`}};function Rt(r,e){let t=X;return new t(r,{reporter:e})}var At=Symbol.for("@flopay/js.telemetry.bridge.v1");function kt(r,e,t){let n=()=>e?.now()??t();Object.defineProperty(r,At,{configurable:!1,enumerable:!1,writable:!1,value:{error:o=>e?.error(o),log:o=>e?.log(o),performance:o=>e?.performance(o),terminal:o=>e?.terminal(o),now:n,elapsed:o=>Math.max(0,n()-o),setCheckoutContext:o=>e?.setCheckoutContext(o),beginCheckout:(o={})=>e?.beginCheckout(o)??n(),disable:()=>e?.disable(),subscribe:o=>e?.subscribe(o)??(()=>{}),flush:()=>e?.flush()??Promise.resolve()}})}function Et(r){return r[At]}var ye=class{now(){return this.telemetryReporter?.now?.()??E()}constructor(e,t,n){this.provider=e,this.config=t,this.telemetryReporter=n??new A({billingApiUrl:(0,M.resolveBillingApiUrl)(t.billingApiUrl),sdkVersion:M.SDK_VERSION,enabled:t.telemetry!==!1}),kt(this,this.telemetryReporter,E)}cardCapture(e){return this.telemetryReporter?.log({name:"vault.capture.requested",stage:"vault_request",provider:"pcivault",paymentMethodCategory:"card"}),this.telemetryReporter?Rt({sessionId:e?.sessionId,captureMethod:e?.captureMethod,sessionToken:e?.sessionToken,billingApiUrl:this.config.billingApiUrl,cardFieldsTimeoutMs:e?.cardFieldsTimeoutMs},this.telemetryReporter):new X({sessionId:e?.sessionId,captureMethod:e?.captureMethod,sessionToken:e?.sessionToken,billingApiUrl:this.config.billingApiUrl,cardFieldsTimeoutMs:e?.cardFieldsTimeoutMs,telemetry:!1})}async retrieveSession(e,t){if(!e)throw new M.FloPayError("sessionId is required to retrieve a session.","validation_error",{param:"sessionId"});let n=await this.retrieveUnifiedSession(e,t);if(!n.data.session)throw new M.FloPayError("Session not found","api_error");return n.data.session}async retrieveUnifiedSession(e,t){if(!e)throw new M.FloPayError("sessionId is required.","validation_error",{param:"sessionId"});let n=(0,M.resolveBillingApiUrl)(t??this.config.billingApiUrl),i=this.now();this.telemetryReporter?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let o,s,a=c=>{if(o===void 0)return;let u=o,h=s;o=void 0,s=void 0,this.telemetryReporter?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:c,attempt:h}),this.telemetryReporter?.performance({stage:"session_first_byte",durationMs:u,durationMode:"machine",requestCategory:"session_read",statusClass:c,attempt:h})},l=bt(n,{now:()=>this.telemetryReporter?.now()??E(),onFirstByte:(c,u)=>{o=c,s=u},onRetry:(c,u)=>{this.telemetryReporter?.log({name:"operation.retry",stage:c==="session_read"?"session_read":"processing",requestCategory:c,attempt:u})}});try{let c=await l.getUnifiedCheckoutSession(e);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"}),c}catch(c){let u=(0,M.classifyTelemetryFailure)(c,c instanceof M.FloPayError&&c.code==="checkout_processing_timeout"?"REQUEST_TIMEOUT":"NETWORK_REQUEST_FAILED");throw a(u.statusClass),this.telemetryReporter?.error({...u,stage:"session_read",provider:"flo",paymentMethodCategory:"unknown"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-i,durationMode:"machine",requestCategory:"session_read",statusClass:u.statusClass}),c}}getRawProvider(){return this.provider.getRawProvider()}destroy(){this.telemetryReporter?.log({name:"checkout.unmount",stage:"unmount"}),this.telemetryReporter?.destroy(),this.provider.destroy()}};function Mt(r,e,t){let n=ye;return new n(r,e,t)}var B=require("@flopay/shared");var He=require("@flopay/shared"),It=require("@stripe/stripe-js"),oe=require("@flopay/shared"),Pt=new WeakSet;function Dt(r){return r instanceof He.FloPayError&&Pt.has(r)}var ie=class{constructor(){this.name="stripe";this.stripe=null}async initialize(e){if(typeof window>"u")return;let t=await(0,It.loadStripe)(e.publishableKey,{locale:e.locale??"auto"});if(!t){let n=new He.FloPayError("Failed to initialize Stripe. Check your publishable key.","authentication_error");throw Pt.add(n),n}this.stripe=t}getRawProvider(){return this.stripe}destroy(){this.stripe=null}};var Ft=new Map;function Ke(r){return Array.isArray(r)?r.map(Ke):r&&typeof r=="object"?Object.fromEntries(Object.entries(r).filter(([,e])=>e!==void 0).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,Ke(t)])):r}function hn(r,e){return JSON.stringify([r,(0,B.resolveBillingApiUrl)(e?.billingApiUrl),e?.telemetry!==!1,e?.locale??"auto",e?.apiVersion??null,Ke(e?.appearance??null)])}var Fe=new Map;async function xt(r,e){if(!r){let a=new A({billingApiUrl:(0,B.resolveBillingApiUrl)(e?.billingApiUrl),sdkVersion:B.SDK_VERSION,enabled:e?.telemetry!==!1});throw a.error({errorCode:"CONFIGURATION_INVALID",stage:"sdk_initialize",paymentMethodCategory:"unknown"}),a.flush().catch(()=>{}).finally(()=>a.destroy()),new B.FloPayError("A publishable key is required to initialize FloPay.","validation_error",{param:"publishableKey"})}let t=hn(r,e),n=Ft.get(t);if(n)return e?.telemetry!==!1&&Et(n)?.log({name:"sdk.cache.hit",stage:"sdk_initialize"}),n;let i=Fe.get(t);if(i)return i;let o={...e,publishableKey:r},s=(async()=>{let a=new A({billingApiUrl:(0,B.resolveBillingApiUrl)(o.billingApiUrl),sdkVersion:B.SDK_VERSION,enabled:o.telemetry!==!1}),l=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 c=new ie,u=a.now();try{await c.initialize(o)}catch(y){throw a.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:Dt(y)?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"unknown"}),a.destroy(),y}let h=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:h-l,durationMode:"machine",provider:"stripe"}),a.performance({stage:"provider_ready",durationMs:h-u,durationMode:"machine",provider:"stripe"});let p=Mt(c,o,a);return Ft.set(t,p),p})();Fe.set(t,s);try{return await s}finally{Fe.get(t)===s&&Fe.delete(t)}}var $=require("@flopay/shared");var yn=4,gn=1e3,fn=1e3,Cn=15e3;function vn(r){let e=!!r?.gateways?.stripe,t=!!r?.gateways?.worldpayCorporateGateway;return e===t?"unknown":e?"stripe":"worldpay"}function Ut(r,e,t){try{return typeof r?.beginThreeDsChallenge!="function"?void 0:r.beginThreeDsChallenge(e,{provider:vn(t)})}catch{return}}function ge(r){return new $.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:r})}function Lt(){return new $.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function qt(r){return r.replace(/\/+$/,"")}function Tn(r){return r.status==="succeeded"||r.status==="authorized"||r.status==="declined"}function bn(r){if(!r||typeof r!="object")return{status:"unknown"};let e=typeof r.status=="string"?r.status:"unknown",t=typeof r.providerIntentId=="string"?r.providerIntentId:null;switch(e){case"succeeded":case"authorized":case"pending":case"timeout":return{status:e,providerIntentId:t};case"declined":return{status:"declined",providerIntentId:t,declineReason:typeof r.declineReason=="string"?r.declineReason:null,gatewayDeclineReason:typeof r.gatewayDeclineReason=="string"?r.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:t,nextActionRedirectUrl:typeof r.nextActionRedirectUrl=="string"?r.nextActionRedirectUrl:null};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}async function $e(r){if(typeof document>"u"||typeof window>"u")throw new $.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});let e=de(r.telemetry);e.record("handoff_planned");let t=ue(r.nextActionRedirectUrl);t==="missing"?e.record("action_missing",{reason:"missing_url"}):t==="invalid"&&e.record("action_invalid",{reason:"invalid_url"});let n=m=>{let g=Je(m);if(g==="buyer_cancel"){e.record("cancel_requested",{reason:g,evidenceBasis:"signal_reason"}),e.terminal("cancel",{reason:g,evidenceBasis:"signal_reason"});return}e.record("abort_observed",{reason:g,evidenceBasis:"signal_reason"}),e.terminal("abort",{reason:g,evidenceBasis:"signal_reason"})},i=m=>{(m.status==="succeeded"||m.status==="authorized"||m.status==="declined"||m.status==="timeout")&&e.reconcile(m.status)};if(r.signal?.aborted)throw n(r.signal.reason),ge();let o=`${qt(r.billingApiUrl)}/v1/checkouts/sessions/${encodeURIComponent(r.sessionId)}/3ds/complete`,s=async()=>{let m=new AbortController,g=()=>m.abort();r.signal?.aborted?m.abort():r.signal?.addEventListener("abort",g);let v=window.setTimeout(()=>m.abort(),Cn);try{let f=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":r.nonce,"content-type":"application/json",...e.attemptId?{"x-flopay-challenge-attempt":e.attemptId}:{}},body:"{}",signal:m.signal});if(!f.ok)return{status:"unknown"};let S=await f.json().catch(()=>null),C=bn(S);return i(C),C}catch{return{status:"unknown"}}finally{window.clearTimeout(v),r.signal?.removeEventListener("abort",g)}},a,l=()=>r.pollCompletionEndpoint!==!1?s():(a??(a=s()),a),c=document.activeElement instanceof HTMLElement?document.activeElement:null,u=document.createElement("div");u.setAttribute("data-flopay-auto-3ds-overlay","1"),u.setAttribute("role","dialog"),u.setAttribute("aria-modal","true"),u.setAttribute("aria-label","Card authentication"),u.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 h=document.createElement("iframe");h.setAttribute("title","Card authentication"),h.setAttribute("allow","payment"),h.tabIndex=0,h.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 p=null;try{p=new URL(r.billingApiUrl,window.location.href).origin}catch{p=null}let y=Se(r.nextActionRedirectUrl);try{let m=await new Promise((g,v)=>{let f=!1,S=0,C=0,F=0,G=!1,V=!1,x=!1,I=0,R=()=>{window.clearTimeout(S),window.clearInterval(C),window.clearTimeout(F),window.removeEventListener("message",P),window.removeEventListener("pagehide",se),document.removeEventListener("securitypolicyviolation",U),h.removeEventListener("load",Y),r.signal?.removeEventListener("abort",ae)},Z=async()=>{if(!(f||G)){G=!0;try{let w=await l();if(f||!Tn(w))return;f=!0,R(),e.terminal("status_poll",{evidenceBasis:"server_status"}),g(w)}finally{G=!1}}},se=()=>{e.record("pagehide_observed",{evidenceBasis:"page_lifecycle_event"})},U=w=>{if(x)return;let b=_e(w,y);b&&(x=!0,e.record("policy_violation",{reason:b,evidenceBasis:"parent_csp_event"}))},Y=()=>{V||(V=!0,e.record("iframe_load",{evidenceBasis:"iframe_load_event"})),r.pollCompletionEndpoint!==!1&&(window.clearTimeout(F),F=window.setTimeout(()=>{Z()},250))},ae=()=>{f||(f=!0,R(),n(r.signal?.reason),v(ge()))},z=w=>{f||I>=yn||(I+=1,e.record("return_rejected",{reason:w,evidenceBasis:"message_origin_check"}))},P=w=>{let b=w.data,j=!!b&&typeof b=="object"&&b.source==="flopay-vault-3ds-return";if(w.source!==h.contentWindow){j&&z("untrusted_source");return}if(p&&w.origin!==p){j&&z("untrusted_origin");return}j&&(f||(f=!0,R(),e.record("trusted_return",{evidenceBasis:"message_origin_check"}),e.terminal("trusted_return",{evidenceBasis:"message_origin_check"}),g(null)))};S=window.setTimeout(()=>{f||(f=!0,R(),V||e.record("load_unconfirmed",{evidenceBasis:"no_load_signal"}),e.record("timer_expired",{reason:"window_elapsed",evidenceBasis:"timer"}),e.terminal("timer",{reason:"window_elapsed",evidenceBasis:"timer"}),v(Lt()))},$.THREE_DS_CHALLENGE_WINDOW_MS),r.pollCompletionEndpoint!==!1&&(C=window.setInterval(()=>{Z()},fn)),h.addEventListener("load",Y),window.addEventListener("message",P),window.addEventListener("pagehide",se),document.addEventListener("securitypolicyviolation",U),r.signal?.addEventListener("abort",ae),h.src=r.nextActionRedirectUrl,e.record("render_attempted");try{u.appendChild(h),document.body.appendChild(u)}catch(w){throw f=!0,R(),e.record("render_failed"),w}e.record("container_attached"),e.record("navigation_assigned");let ee=be(u);ee&&e.record("container_visibility",{reason:ee,evidenceBasis:"parent_computed_style"}),h.focus(),r.signal?.aborted&&ae()});return m||await l()}finally{u.parentNode?.removeChild(u),e.record("teardown"),c?.isConnected&&c.focus()}}function Ot(r,e){try{let t=e.data.session?.status;t==="complete"?r.reconcile("succeeded"):t==="authorized"&&r.reconcile("authorized")}catch{}}function _n(r){return new $.FloPayError("Card was declined.","api_error",{code:r.declineReason??"authorization_declined",...r.gatewayDeclineReason?{declineCode:r.gatewayDeclineReason}:{}})}async function Nt(r,e){let t=`${qt(r.billingApiUrl)}/v1/checkouts/sessions/${encodeURIComponent(r.sessionId)}/status`,n=new AbortController,i=new AbortController,o=()=>{n.abort(r.signal?.reason),i.abort(r.signal?.reason)};r.signal?.aborted?o():r.signal?.addEventListener("abort",o,{once:!0});let s=de(r.telemetry),a=$e({billingApiUrl:r.billingApiUrl,sessionId:r.sessionId,nonce:r.nonce,nextActionRedirectUrl:r.nextActionRedirectUrl,signal:n.signal,pollCompletionEndpoint:!1,...r.telemetry?{telemetry:r.telemetry}:{}}),l=e.waitForCheckoutSessionCompletion(r.sessionId,{initialDelayMs:gn,nonce:r.nonce,statusUrl:t,continueAfterActionRequired:!0,timeoutMs:$.THREE_DS_CHALLENGE_WINDOW_MS+15e3,signal:i.signal,...s.attemptId?{challengeAttemptId:s.attemptId}:{}});l.catch(()=>{}),a.catch(()=>{});try{let c=await Promise.race([a,l]);if("data"in c)return s.terminal("status_poll",{evidenceBasis:"server_status"}),Ot(s,c),c;if(c.status==="declined")throw(r.createDeclineError??_n)(c);if(c.status==="timeout")throw Lt();let u=await l;return Ot(s,u),u}catch(c){throw r.signal?.aborted||c instanceof Error&&c.name==="AbortError"?ge(c):c}finally{r.signal?.removeEventListener("abort",o),n.abort(),i.abort()}}0&&(module.exports={FloPay,PaymentAPI,PciVaultCardCapture,SESSION_CREATE_TELEMETRY,StripeAdapter,beginSavedCardChallengeTelemetry,cacheSessionDisplayData,clearSessionDisplayData,completeSavedCardNextAction,createCheckoutSession,createCheckoutSessionWithRetries,createSavedCardActionAbortedError,dropThirdPartyOnlyError,getSessionDisplayData,loadCheckoutRuntime,loadFloPay,runSavedCardChallenge,toStripeAppearance,toStripeAppearanceTheme});
|
|
1
|
+
"use strict";var xe=Object.defineProperty;var Vt=Object.getOwnPropertyDescriptor;var zt=Object.getOwnPropertyNames;var jt=Object.prototype.hasOwnProperty;var Ht=(r,e)=>{for(var t in e)xe(r,t,{get:e[t],enumerable:!0})},Kt=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of zt(e))!jt.call(r,i)&&i!==t&&xe(r,i,{get:()=>e[i],enumerable:!(n=Vt(e,i))||n.enumerable});return r};var $t=r=>Kt(xe({},"__esModule",{value:!0}),r);var Sn={};Ht(Sn,{FloPay:()=>ye,PaymentAPI:()=>Q,PciVaultCardCapture:()=>X,SESSION_CREATE_TELEMETRY:()=>ze,StripeAdapter:()=>ie,beginSavedCardChallengeTelemetry:()=>Ut,cacheSessionDisplayData:()=>W,clearSessionDisplayData:()=>Te,completeSavedCardNextAction:()=>Nt,createCheckoutSession:()=>nt,createCheckoutSessionWithRetries:()=>at,createSavedCardActionAbortedError:()=>ge,dropThirdPartyOnlyError:()=>Bt.dropThirdPartyOnlyError,getSessionDisplayData:()=>ve,loadCheckoutRuntime:()=>Ge,loadFloPay:()=>xt,runSavedCardChallenge:()=>$e,toStripeAppearance:()=>oe.toStripeAppearance,toStripeAppearanceTheme:()=>oe.toStripeAppearanceTheme});module.exports=$t(Sn);var Bt=require("@flopay/shared");var Le=require("@flopay/shared"),Gt="FloPayCheckoutRuntime",Yt=1e4,Ue=new Map;function Wt(r){return typeof r=="object"&&r!==null&&typeof r.mount=="function"}function Oe(r){return new Le.FloPayError(r==="runtime_load_timeout"?"The checkout runtime did not load in time.":"The checkout runtime failed to load.","network_error",{code:r})}function Jt(r,e){return new Promise((t,n)=>{let i=document.createElement("script"),o=!1,s=u=>{o||(o=!0,clearTimeout(c),i.removeEventListener("load",a),i.removeEventListener("error",l),u instanceof Le.FloPayError?(Ue.delete(r),i.remove(),n(u)):t(u))},a=()=>{let u=Reflect.get(globalThis,Gt);s(Wt(u)?u:Oe("runtime_load_failed"))},l=()=>s(Oe("runtime_load_failed")),c=setTimeout(()=>s(Oe("runtime_load_timeout")),e);i.addEventListener("load",a),i.addEventListener("error",l),i.async=!0,i.src=r,document.head.appendChild(i)})}function Ge(r){let{runtimeUrl:e,timeoutMs:t=Yt}=r,n=Ue.get(e);if(n!==void 0)return n;let i=Jt(e,t);return Ue.set(e,i),i}var T=require("@flopay/shared");function le(r){return typeof r=="string"&&r.trim()?r:void 0}function ce(r){if(typeof r=="string")return r.trim()?r:void 0;if(Array.isArray(r))return r.filter(t=>typeof t=="string"&&t.trim().length>0).join("; ")||void 0}function L(r=12e3){let e=Number.isFinite(r)&&r>=0?r:12e3,t=new AbortController,n=setTimeout(()=>t.abort(),e);return{signal:t.signal,clear:()=>clearTimeout(n)}}function Qt(){return Object.assign(new Error("The operation was aborted."),{name:"AbortError"})}function te(r,e){let t=150*2**r,n=Math.round(t*(.75+Math.random()*.5));return new Promise((i,o)=>{let s,a=()=>e.removeEventListener("abort",l),l=()=>{s!==void 0&&clearTimeout(s),a(),o(Qt())};if(e.aborted){l();return}s=setTimeout(()=>{a(),i()},n),e.addEventListener("abort",l,{once:!0})})}var Xt="flopay_session_display:";var fe=new Map;function Ce(r){return`${Xt}${r}`}function qe(){if(typeof window>"u")return null;try{return window.sessionStorage}catch{return null}}function W(r,e,t){if(!r)return;let n=t?.ttlMs??36e5,i={data:e,expiresAt:Date.now()+n},o=qe();if(o)try{o.setItem(Ce(r),JSON.stringify(i));return}catch{}fe.set(r,i)}function ve(r){if(!r)return null;let e=qe();if(e)try{let n=e.getItem(Ce(r));if(n){let i=JSON.parse(n);if(i&&typeof i.expiresAt=="number"&&i.expiresAt>Date.now())return i.data;e.removeItem(Ce(r))}}catch{}let t=fe.get(r);if(t){if(t.expiresAt>Date.now())return t.data;fe.delete(r)}return null}function Te(r){if(!r)return;fe.delete(r);let e=qe();if(e)try{e.removeItem(Ce(r))}catch{}}var k=require("@flopay/shared");var Ne=require("@flopay/shared"),Zt=32,Ye=Symbol.for("@flopay/js.three-ds-challenge.attempts.v1");function er(){let r=globalThis,e=r[Ye];if(e instanceof Map)return e;let t=new Map;try{Object.defineProperty(r,Ye,{configurable:!0,enumerable:!1,writable:!1,value:t})}catch{}return t}function tr(r,e){let t=er(),n=t.get(r);if(n)return n;for(;t.size>=Zt;){let o=t.keys().next();if(o.done)break;t.delete(o.value)}let i={nextSequence:0,startedAt:e,terminated:!1,reconciled:new Set,provider:"unknown"};return t.set(r,i),i}var rr=new Set(["pagehide_observed","cancel_requested","abort_observed","browser_terminal"]),nr=new Set(["teardown","recovery_read_completed","provider_reconciled"]);function We(r,e={}){let t=(0,Ne.isThreeDsChallengeAttemptId)(e.attemptId)?e.attemptId.toLowerCase():r.newAttemptId(),n=()=>{try{let a=r.now();return Number.isFinite(a)?a:0}catch{return 0}},i=tr(t,n());(e.provider==="stripe"||e.provider==="worldpay")&&(i.provider=e.provider);let o=i.provider,s=(a,l)=>{if(i.terminated&&!nr.has(a))return;let c={attemptId:t,phase:a,attemptSequence:i.nextSequence,elapsedMs:Math.max(0,n()-i.startedAt),provider:o};i.nextSequence+=1,l.reason!==void 0&&(c.reason=l.reason),l.evidenceBasis!==void 0&&(c.evidenceBasis=l.evidenceBasis),l.terminalSource!==void 0&&(c.terminalSource=l.terminalSource),l.providerOutcome!==void 0&&(c.providerOutcome=l.providerOutcome);try{r.emit(c,rr.has(a))}catch{}};return{attemptId:t,record(a,l={}){a==="browser_terminal"||a==="provider_reconciled"||s(a,{reason:l.reason,evidenceBasis:l.evidenceBasis})},terminal(a,l={}){i.terminated||(s("browser_terminal",{terminalSource:a,reason:l.reason,evidenceBasis:l.evidenceBasis}),i.terminated=!0)},reconcile(a){i.reconciled.has(a)||(i.reconciled.add(a),s("provider_reconciled",{providerOutcome:a,evidenceBasis:"provider_fact"}))}}}function de(r){let e=null;try{e=(0,Ne.isThreeDsChallengeAttemptId)(r?.attemptId)?r?.attemptId??null:null}catch{e=null}return{attemptId:e,record(t,n){try{r?.record(t,n)}catch{}},terminal(t,n){try{r?.terminal(t,n)}catch{}},reconcile(t){try{r?.reconcile(t)}catch{}}}}function ue(r){if(typeof r!="string"||r.trim()==="")return"missing";try{let e=new URL(r);return e.protocol==="https:"||e.protocol==="http:"?"valid":"invalid"}catch{return"invalid"}}function Je(r){return r==="buyer_cancel"||r==="component_unmount"||r==="navigation"?r:"unspecified"}function be(r){try{if(typeof window>"u"||typeof window.getComputedStyle!="function")return null;for(let e=r;e;e=e.parentElement){let t=window.getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden"||t.visibility==="collapse"||t.opacity==="0")return"hidden"}return"visible"}catch{return null}}function _e(r,e){if(!e)return null;try{let t=r,n=String(t.effectiveDirective||t.violatedDirective||"").trim().split(/\s+/)[0],i=null;return n==="frame-src"&&(i="frame_src"),n==="child-src"&&(i="child_src"),!i||typeof t.blockedURI!="string"?null:new URL(t.blockedURI).origin===e?i:null}catch{return null}}function Se(r){try{return ue(r)==="valid"?new URL(r).origin:null}catch{return null}}var ir="/v1/sdk-telemetry/events",Re=16,Qe=64,or=1500,Xe=1e3,sr=64,ar="00000000-0000-4000-8000-000000000000",lr={technical_error:8,lifecycle:32,expected_outcome:32,performance:24},cr=48;function H(){try{return globalThis.crypto.randomUUID()}catch{let r=new Uint8Array(16);try{globalThis.crypto.getRandomValues(r)}catch{for(let t=0;t<r.length;t+=1)r[t]=Math.floor(Math.random()*256)}r[6]=(r[6]??0)&15|64,r[8]=(r[8]??0)&63|128;let e=[...r].map(t=>t.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}}function dr(r){try{return new TextEncoder().encode(r).byteLength}catch{return r.length}}function ur(r){return JSON.stringify([r.code,r.failureCategory,r.reason,r.stage,r.provider,r.attempt,r.statusClass,r.requestCategory,r.paymentMethodCategory,r.walletType,r.operationOutcome,r.checkoutMode,r.layout,r.inAppBrowser,r.appFamily,r.popupCapability,r.presentationMode,r.terminalReason])}function E(){return globalThis.performance?.now()??0}var A=class{constructor(e){this.ingestionDisabled=!1;this.queue=[];this.sequence=0;this.threeDsChallengeCount=0;this.flushTimer=null;this.flushInFlight=null;this.reportedFailures=new Map;this.checkoutContext={};this.checkoutStartedAt=null;this.destroyed=!1;this.observers=new Set;this.pageExitHandler=()=>{this.drainQueue()};this.visibilityHandler=()=>{document.visibilityState==="hidden"&&this.flush()};this.eventCounts={technical_error:0,lifecycle:0,expected_outcome:0,performance:0};this.endpoint=`${e.billingApiUrl.replace(/\/+$/,"")}${ir}`,this.sdkPackage=e.sdkPackage??"@flopay/js",this.sdkVersion=e.sdkVersion,this.correlationId=H(),this.merchantEnabled=e.enabled!==!1,this.clock=e.clock??E,this.browserTransportAvailable=typeof window<"u"&&typeof document<"u",this.browserTransportAvailable&&(window.addEventListener("pagehide",this.pageExitHandler),document.addEventListener("visibilitychange",this.visibilityHandler))}log(e){this.notify({...e,class:"lifecycle"}),this.canCollect()&&this.enqueue((0,k.buildTelemetryLogEvent)({...this.checkoutContext,...e,eventId:H(),sequence:this.sequence++}))}error(e){if(this.notify({...e,class:"technical_error"}),!this.canCollect())return;let t=(0,k.buildTelemetryErrorEvent)({...this.checkoutContext,...e,eventId:ar,sequence:0}),n=ur(t),i=this.now();this.pruneReportedFailures(i);let o=this.reportedFailures.get(n);if(o!==void 0&&i>=o&&i-o<Xe){this.log({name:"operation.deduplicated",stage:e.stage,provider:e.provider,paymentMethodCategory:e.paymentMethodCategory,attempt:e.attempt,inAppBrowser:e.inAppBrowser,appFamily:e.appFamily,popupCapability:e.popupCapability,presentationMode:e.presentationMode,terminalReason:e.terminalReason});return}this.rememberReportedFailure(n,i),this.enqueue((0,k.buildTelemetryErrorEvent)({...this.checkoutContext,...e,eventId:H(),sequence:this.sequence++}))}performance(e){this.canCollect()&&this.enqueue((0,k.buildTelemetryPerformanceEvent)({...this.checkoutContext,...e,eventId:H(),sequence:this.sequence++}))}terminal(e){if(this.canCollect()&&(this.enqueue((0,k.buildTelemetryTerminalEvent)({...this.checkoutContext,...e,eventId:H(),sequence:this.sequence++})),e.outcome!=="action_required"&&this.checkoutStartedAt!==null)){let t=this.checkoutStartedAt;this.checkoutStartedAt=null,this.performance({...e,stage:"total_journey",durationMs:Math.max(0,this.now()-t),durationMode:"total"})}}beginThreeDsChallenge(e={}){return We({now:()=>this.now(),newAttemptId:H,emit:(t,n)=>this.recordThreeDsChallenge(t,n)},e)}recordThreeDsChallenge(e,t){if(!this.canCollect()||this.threeDsChallengeCount>=cr)return;let n=(0,k.buildTelemetryLogEvent)({...this.checkoutContext,...e,name:"three_ds.challenge",stage:"three_ds_handoff",eventId:H(),sequence:this.sequence++});if(!(this.queue.length>=Qe)){if(this.threeDsChallengeCount+=1,this.queue.push(n),t){this.drainQueue();return}if(this.queue.length>=Re){this.flush();return}this.scheduleFlush()}}now(){try{return this.clock()}catch{return E()}}subscribe(e){return this.destroyed?()=>{}:(this.observers.add(e),()=>this.observers.delete(e))}notify(e){if(!this.destroyed)for(let t of this.observers)try{t(e)}catch{}}pruneReportedFailures(e){for(let[t,n]of this.reportedFailures)(e<n||e-n>=Xe)&&this.reportedFailures.delete(t)}rememberReportedFailure(e,t){for(;this.reportedFailures.size>=sr;){let n=this.reportedFailures.keys().next();if(n.done)break;this.reportedFailures.delete(n.value)}this.reportedFailures.set(e,t)}setCheckoutContext(e){this.checkoutContext={checkoutMode:e.checkoutMode,layout:e.layout}}beginCheckout(e={}){return this.canCollect()?(this.drainQueue(),this.setCheckoutContext(e),this.sequence=0,this.threeDsChallengeCount=0,this.reportedFailures.clear(),this.eventCounts={technical_error:0,lifecycle:0,expected_outcome:0,performance:0},this.checkoutStartedAt=this.now(),this.checkoutStartedAt):0}enqueue(e){if(this.canCollect()&&!(this.queue.length>=Qe||this.eventCounts[e.class]>=lr[e.class])){if(this.eventCounts[e.class]+=1,this.queue.push(e),this.queue.length>=Re){this.flush();return}this.scheduleFlush()}}canCollect(){return this.browserTransportAvailable&&this.merchantEnabled&&!this.ingestionDisabled&&!this.destroyed}async flush(){if(this.flushInFlight!==null)return this.flushInFlight;if(!this.browserTransportAvailable||this.destroyed||this.ingestionDisabled||this.queue.length===0)return;this.clearFlushTimer();let e=this.queue.splice(0,Re);return this.flushInFlight=this.sendBatch(e).finally(()=>{this.flushInFlight=null,this.queue.length>0&&this.scheduleFlush()}),this.flushInFlight}destroy(){this.destroyed||(this.drainQueue(),this.destroyed=!0,this.clearFlushTimer(),this.browserTransportAvailable&&(window.removeEventListener("pagehide",this.pageExitHandler),document.removeEventListener("visibilitychange",this.visibilityHandler)),this.queue.splice(0),this.reportedFailures.clear(),this.observers.clear())}disable(){this.merchantEnabled=!1,this.queue.splice(0),this.reportedFailures.clear(),this.clearFlushTimer()}drainQueue(){if(!(!this.browserTransportAvailable||this.destroyed||this.ingestionDisabled||this.queue.length===0))for(this.clearFlushTimer();this.queue.length>0;){let e=this.queue.splice(0,Re);this.sendBatch(e)}}async sendBatch(e){if(!this.browserTransportAvailable||this.ingestionDisabled)return;let t=(0,k.serializeTelemetryBatch)(e,{correlationId:this.correlationId,sdkPackage:this.sdkPackage,sdkVersion:this.sdkVersion,batchId:H()});if(dr(t)>k.TELEMETRY_MAX_BATCH_BYTES)return;let n=typeof AbortController>"u"?null:new AbortController,i=null;try{let o=fetch(this.endpoint,{method:"POST",headers:{"content-type":"text/plain;charset=UTF-8"},body:t,credentials:"omit",keepalive:!0,referrerPolicy:"no-referrer",signal:n?.signal}).then(async l=>{if(l.status!==202)return null;let c=null;try{c=await l.json()}catch{}return c?.status==="disabled"?"disabled":null}).catch(()=>null),s=new Promise(l=>{i=setTimeout(()=>{n?.abort(),l(null)},or)});await Promise.race([o,s])==="disabled"&&this.disableFromIngestion()}catch{}finally{i&&clearTimeout(i)}}disableFromIngestion(){this.ingestionDisabled=!0,this.queue.splice(0),this.reportedFailures.clear(),this.clearFlushTimer()}scheduleFlush(){this.flushTimer||this.destroyed||this.ingestionDisabled||(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush()},0))}clearFlushTimer(){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null)}},Ze=Symbol.for("@flopay/js.telemetry.reporter-factory.v1"),et=globalThis;et[Ze]===void 0&&Object.defineProperty(et,Ze,{configurable:!0,enumerable:!1,writable:!1,value:r=>new A(r)});var Be=5,tt=new WeakSet;function mr(r){(typeof r=="object"&&r!==null||typeof r=="function")&&tt.add(r)}function pr(r){return(typeof r=="object"&&r!==null||typeof r=="function")&&tt.has(r)}function hr(r,e){let t=e?.error,n=le(e?.code)??le(t?.code)??`http_${r}`,i=ce(e?.message)??ce(t?.message)??yr(n,r);return new T.FloPayError(i,"api_error",{code:n,statusCode:r})}function yr(r,e){switch(r){case"CouponLimitExceeded":return`Too many coupon codes \u2014 a checkout session accepts at most ${Be}.`;case"CouponCurrencyUnsupported":return"One of the applied coupons has no price configured for the cart currency.";default:return`Failed to create checkout session (HTTP ${e}).`}}async function rt(r,e,t){let{billingApiUrl:n,checkoutBaseUrl:i,items:o=[],subscriptions:s=[],products:a,account:l,successUrl:c,cancelUrl:u,checkoutMode:h="confirm",captureMethod:p,couponCodes:y=[],checkoutMetadata:m,tagsData:g,redirectParams:v={},setCookie:f=!0,clientId:S,currency:C,utmMetadata:F,idempotencyKey:G}=r,V=(0,T.resolveIdempotencyKey)(G);if(y.length>Be)throw new T.FloPayError(`Too many coupon codes \u2014 a checkout session accepts at most ${Be}.`,"validation_error",{code:"CouponLimitExceeded",param:"couponCodes"});let x=a??(0,T.foldIntoProducts)(o,s);(0,T.assertCaptureMethodEligible)({captureMethod:p,products:x});let I=(0,T.resolveSessionCurrency)(C,o,s,x);if(!I)throw new T.FloPayError("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 w={clientId:S,checkoutVersion:T.SDK_VERSION,successUrl:c,cancelUrl:u,currency:I,checkoutMode:h,products:x.map(P=>(0,T.buildProductPayload)(P,I)),accountData:{userId:l.userId,firstName:l.firstName??null,lastName:l.lastName??null,email:l.email,country:l.country??null,gender:l.gender??null,city:l.city??null,state:l.state??null,zip:l.zip??null,addressLine1:l.addressLine1??null,addressLine2:l.addressLine2??null},couponCodes:y};p==="manual"&&(w.captureMethod=p),m!==void 0&&(w.checkoutMetadata=m),g&&(w.tagsData=g),F&&F.length>0&&(w.utmMetadata=F);let Z=`${n.replace(/\/+$/,"")}/v1/checkouts/sessions`,se={"Content-Type":"application/json"};V&&(se[T.IDEMPOTENCY_KEY_HEADER]=V);let U,Y,ae={method:"POST",headers:se,body:JSON.stringify(w),signal:e},z;try{t?.startAttempt(),z=await fetch(Z,ae)}catch(P){throw mr(P),P}try{t?.record(z.status)}catch{}U=z.status;try{Y=await z.json()}catch{}if(U>=400)throw(0,T.withTelemetryHttpDiagnostics)(hr(U,Y),z);if(U===201){let P=Y?.data?.uuid,ee=Y?.data?.nonce;if(!P)throw new Error("Checkout session created but no UUID was returned by the billing API");if(!ee)throw new T.FloPayError("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"});(x.length>0||I)&&W(P,{currency:I,products:x.map(b=>({code:b.code??b.providerItemId??b.providerPlanId,type:b.type,name:b.name??b.itemName??b.providerItemName??b.subscriptionName??b.providerPlanName??null,totalAmount:b.totalAmount,overrideAmount:b.overrideAmount,currency:b.currency??I}))});let R=new URL(`${i.replace(/\/+$/,"")}/secure`);R.searchParams.set("id",P);for(let[b,j]of Object.entries(v))R.searchParams.set(b,j);if(f&&typeof window<"u"&&typeof document<"u"){let b=JSON.stringify({origin_url:u}),j=window.location.hostname.split(".").slice(-2).join(".");document.cookie=`checkout_data=${encodeURIComponent(b)}; domain=.${j}; path=/; max-age=3600; SameSite=Lax; Secure;`,document.cookie=`flopay_checkout_token=${encodeURIComponent(ee)}; domain=.${j}; path=/; max-age=3600; SameSite=Lax; Secure;`}return typeof window<"u"&&(window.location.href=R.toString()),{status:201,redirectUrl:R.toString(),nonce:ee}}return U===204?(typeof window<"u"&&(window.location.href=c),{status:204}):{status:U}}async function nt(r){let e=ot(r),t=it(e),n=L(r.timeoutMs);try{let i=await rt(r,n.signal,t);return t.commit(),st(e,i),i}catch(i){throw t.commit(),we(e,i),i}finally{n.clear(),re(e.reporter)}}function it(r){let e=!1,t=r.startedAt,n;return{startAttempt(){t=r.reporter.now()},record(i){n={status:i,durationMs:Math.max(0,r.reporter.now()-t),attempt:r.attempt}},commit(){if(e||!n)return;e=!0;let i=(0,T.telemetryStatusClass)(n.status);r.reporter.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:i,attempt:n.attempt}),r.reporter.performance({stage:"session_first_byte",durationMs:n.durationMs,durationMode:"machine",requestCategory:"session_create",statusClass:i,attempt:n.attempt})}}}function ot(r){let e=new A({billingApiUrl:r.billingApiUrl,sdkVersion:T.SDK_VERSION,enabled:r.telemetry!==!1}),t=e.now();return e.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"}),{reporter:e,startedAt:t,attempt:0}}function st(r,e){let t=(0,T.telemetryStatusClass)(e.status);r.reporter.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:t}),r.reporter.performance({stage:"session_create",durationMs:r.reporter.now()-r.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:t,attempt:r.attempt})}function we(r,e){let{reporter:t}=r,n=(0,T.classifyTelemetryFailure)(e,"CHECKOUT_SESSION_CREATE_FAILED");if(t.performance({stage:"session_create",durationMs:t.now()-r.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:n.statusClass,attempt:r.attempt}),e instanceof T.FloPayError&&e.type==="validation_error"){t.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"});return}if(n.statusClass==="4xx"){t.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create",statusClass:"4xx"});return}t.error({...n,stage:"session_create",requestCategory:"session_create"})}function re(r){r.flush().catch(()=>{}).finally(()=>r.destroy())}async function at(r){let{maxRetries:e=2,...t}=r,n=ot(r),i=it(n);if(!Number.isFinite(e)||!Number.isInteger(e)||e<0||e>=3)throw n.reporter.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),re(n.reporter),new Error(`Number of retries must be an integer between 0 and ${2}`);let o={...t,idempotencyKey:(0,T.resolveIdempotencyKey)(t.idempotencyKey)},s=L(t.timeoutMs),a;for(let l=0;l<=e;l++){n.attempt=l;try{let c=await rt(o,s.signal,i);return i.commit(),st(n,c),s.clear(),re(n.reporter),c}catch(c){a=c;let u=c instanceof Error&&c.name==="AbortError",h=pr(c),p=c instanceof T.FloPayError&&c.code===T.IDEMPOTENCY_IN_PROGRESS_CODE;if((u||h||p)&&!s.signal.aborted&&l<e){n.reporter.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:l+1});try{await te(l,s.signal)}catch(y){throw i.commit(),we(n,y),s.clear(),re(n.reporter),y}continue}throw i.commit(),we(n,c),s.clear(),re(n.reporter),c}}throw i.commit(),we(n,a),s.clear(),re(n.reporter),a??new Error("Unknown error during checkout session creation")}var M=require("@flopay/shared");var d=require("@flopay/shared");function gr(r){return r==="on_session"||r==="off_session"}function fr(r){if(!r||typeof r!="object")return!1;let e=r;return typeof e.paymentMethodType=="string"&&typeof e.reason=="string"}function Cr(r){let e=r.vaultOutcome;if(!(!e||e.code!==d.CHECKOUT_SESSION_BUYER_EMAIL_REQUIRED))return typeof e.message=="string"&&e.message.trim()!==""?e.message:void 0}var vr="x-flopay-process-result-source",Tr="status",Ct=new WeakSet;function br(r,e){let t=new d.FloPayError(r,"api_error",{code:e,statusCode:500});return Ct.add(t),t}function _r(r){return typeof r=="object"&&r!==null&&Ct.has(r)}function lt(r){return r?.result==="DECLINE"||r?.result==="ERROR"}var Sr=50,J=new Map;function Rr(r,e){return J.get(r)?.has(e)===!0}function wr(r,e){let t=J.get(r)??new Set;if(t.add(e),J.delete(r),J.set(r,t),J.size>Sr){let n=J.keys().next().value;n!==void 0&&J.delete(n)}}function Ar(r){let e=r?.threeDSecureActionResultTokenId;if(typeof e=="string"&&e.length>0)return e;if(r?.gateway==="paypal"&&r.type!=="paypal_setup_token"&&typeof r.id=="string"&&r.id.length>0)return r.id}var ct=0,dt=500,Ae=15e3,ut=15e3,kr=3e3,Er=1e4,Mr=1e4;function pe(r){return typeof r=="object"&&r!==null}function K(r,e){return le(r?.[e])}function mt(r,e){return ce(r?.[e])}function Ir(r,e){let t=r?.[e];return typeof t=="number"&&Number.isFinite(t)?t:void 0}function Ee(r,e){return e?new Promise((t,n)=>{let i=()=>{clearTimeout(o),n(e.reason??Object.assign(new Error("The operation was aborted."),{name:"AbortError"}))},o=setTimeout(()=>{e.removeEventListener("abort",i),t()},r);e.aborted?i():e.addEventListener("abort",i,{once:!0})}):new Promise(t=>setTimeout(t,r))}function Ve(r){return r instanceof Error&&r.name==="AbortError"}function D(){return new d.FloPayError(d.CHECKOUT_PROCESSING_TIMEOUT_MESSAGE,"api_error",{code:"checkout_processing_timeout"})}async function N(r,e){let t=await r.json().catch(()=>null),n=pe(t?.error)?t.error:null,i=mt(t,"message")??mt(n,"message")??e,o=K(t,"code")??K(t,"gatewayErrorCode")??K(n,"code")??`http_${r.status}`;return(0,d.withTelemetryHttpDiagnostics)(new d.FloPayError(i,"api_error",{code:o,statusCode:r.status}),r)}async function Pr(r){if(r.status!==403)return!1;let e=await r.clone().json().catch(()=>null),t=pe(e?.error)?e.error:null;return(K(e,"code")??K(t,"code"))==="verification_required"}function Dr(r){if(!(!pe(r)||typeof r.required!="boolean"))return{required:r.required,provider:"turnstile"}}async function Fr(r){let e=r.status===400?await r.clone().json().catch(()=>null):null;return(0,d.classifyPaymentRejection)(r.status,e)}function pt(r){return r===400||r===422}var Me=2;async function ke(r,e,t=Me,n,i){let o;for(let s=0;;s++)try{return i?.(s),await fetch(r,e)}catch(a){if(e?.signal?.aborted||a instanceof Error&&a.name==="AbortError")throw a;if(o=a,s>=t)throw o;try{n?.(s+1)}catch{}await Ee(150*2**s,e?.signal??void 0)}}var xr=2e3,Or=1e4,Ur=150;async function Lr(r){try{let t=(await r.json())?.data?.status;return t==="closed"||t==="not_open"?t:"failed"}catch{return"failed"}}async function ht(r,e,t){let n=new AbortController,i=()=>n.abort();t?.addEventListener("abort",i,{once:!0});let o,s=new Promise(a=>{o=setTimeout(()=>{n.abort(),a("timeout")},Or)});try{let a=await Promise.race([fetch(r,{...e,signal:n.signal}),s]);return a==="timeout"?"failed":a.status>=500?"retry":a.ok?await Lr(a):"failed"}catch{return n.signal.aborted?"failed":"retry"}finally{clearTimeout(o),t?.removeEventListener("abort",i)}}function qr(r,e){return new Promise(t=>{let n=setTimeout(t,e);r.then(()=>{clearTimeout(n),t()},()=>{clearTimeout(n),t()})})}var yt="stripe-account-switch-v1",ze=Symbol.for("@flopay/js.session-create.telemetry.v1");function Nr(r){return r[ze]}function Br(r){return"now"in r||"onFirstByte"in r||"onSessionCreateFailure"in r||"onRetry"in r}function vt(r){let e=(0,d.isCardHolderNamePlaceholder)(r.firstName,r.lastName);return{userId:r.userId,firstName:e?null:r.firstName??null,lastName:e?null:r.lastName??null,email:r.email,country:r.country??null,gender:r.gender??null,city:r.city??null,state:r.state??null,zip:r.zip??null,addressLine1:r.addressLine1??null,addressLine2:r.addressLine2??null}}function Tt(r,e){e.checkoutMetadata!==void 0&&(r.checkoutMetadata=e.checkoutMetadata),e.tagsData&&(r.tagsData=e.tagsData),e.utmMetadata&&e.utmMetadata.length>0&&(r.utmMetadata=e.utmMetadata),e.avsCheck!==void 0&&(r.avsCheck=e.avsCheck),e.checkoutType&&(r.checkoutType=e.checkoutType),e.checkoutLayout&&(r.checkoutLayout=e.checkoutLayout),e.avsConfig&&(r.avsConfig=e.avsConfig)}function gt(r){if(typeof r!="string")return;let e=r.trim();return e.length>0?e:void 0}function Vr(r){let e={};if(r.country&&(e.country=r.country),!(0,d.isCardHolderNamePlaceholder)(r.firstName,r.lastName)){let t=gt(r.firstName),n=gt(r.lastName);t&&(e.firstName=t),n&&(e.lastName=n)}return Object.keys(e).length>0?e:void 0}function zr(r,e,t){let n={clientId:r.clientId,checkoutVersion:d.SDK_VERSION,successUrl:r.successUrl,cancelUrl:r.cancelUrl,currency:e,checkoutMode:"full",deferDataAttachment:!0};r.captureMethod==="manual"&&(n.captureMethod=r.captureMethod);let i=Vr(r.account);i&&(n.accountData=i),Tt(n,r);let o=jr(t);return o&&(n.routingProducts=o),n}function jr(r){let e=new Set;for(let t of r){let n=[t.code,t.providerItemId,t.providerPlanId].map(i=>typeof i=="string"?i.trim():"").find(i=>i.length>0);n&&e.add(n)}return e.size>0?Array.from(e,t=>({code:t})):void 0}function ft(r,e,t){return{currency:e,products:t.map(n=>(0,d.buildProductPayload)(n,e)),couponCodes:r.couponCodes??[],accountData:vt(r.account)}}function Hr(r,e,t){return{currency:e,products:t.map(n=>(0,d.buildProductPayload)(n,e)),couponCodes:r.couponCodes??[]}}function Kr(r){let e={},t=(0,d.isCardHolderNamePlaceholder)(r.firstName,r.lastName);for(let[n,i]of Object.entries(r)){if(t&&n.endsWith("Name")||typeof i!="string")continue;let o=i.trim();o&&(e[n]=o)}return{accountData:e}}var O=class O{constructor(e,t={}){this.baseUrl=e.replace(/\/+$/,"");let n=Br(t);this.telemetryHooks=n?t:void 0,this.stripeAccountSwitch=!n&&t.stripeAccountSwitch===!0,this.directTelemetry=n||t.telemetry===!1?void 0:new A({billingApiUrl:this.baseUrl,sdkVersion:d.SDK_VERSION})}destroy(){this.directTelemetry?.destroy()}reportDirectFailure(e,t,n,i,o="unknown"){let s=(0,d.classifyTelemetryFailure)(e,t);this.directTelemetry?.error({...s,..._r(e)?{reason:"capture_failed"}:{},stage:n,requestCategory:i,paymentMethodCategory:o})}reportAccountSnapshotFailure(e,t){let n=(0,d.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED");if(t==="best_effort"&&n.errorCode==="REQUEST_TIMEOUT"){this.directTelemetry?.log({name:"operation.fallback",stage:"processing",requestCategory:"account_snapshot",statusClass:"timeout"});return}this.directTelemetry?.error({...n,stage:"processing",requestCategory:"account_snapshot",paymentMethodCategory:"unknown"})}telemetryTimestamp(){try{return this.telemetryHooks?.now?.()??this.directTelemetry?.now()??E()}catch{return E()}}beginDirectTelemetryCheckout(e){!this.directTelemetry||this.directTelemetryCheckoutId===e||(this.directTelemetryCheckoutId=e,this.directTelemetry.beginCheckout())}beginDirectTelemetryOperation(){this.directTelemetry&&(this.directTelemetryCheckoutId=void 0,this.directTelemetry.beginCheckout())}adoptDirectTelemetryCheckout(e){e&&(this.directTelemetryCheckoutId=e)}async getCheckoutSession(e,t){return this.fetchCheckoutSession(e,t)}async fetchCheckoutSession(e,t,n=!0,i){this.beginDirectTelemetryCheckout(e);let o=this.telemetryTimestamp(),s=o,a=0;this.directTelemetry?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let l={[d.FLO_SDK_VERSION_HEADER]:d.SDK_VERSION};t&&(l["x-checkout-session-token"]=t);let c=!1;try{let u=await ke(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}`,{headers:l,signal:i},Me,m=>{this.telemetryHooks?.onRetry?.("session_read",m),this.directTelemetry?.log({name:"operation.retry",stage:"session_read",requestCategory:"session_read",attempt:m})},m=>{a=m,s=this.telemetryTimestamp()});c=!0;let h=Math.max(0,this.telemetryTimestamp()-s);try{this.telemetryHooks?.onFirstByte?.(h,a)}catch{}let p=`${Math.floor(u.status/100)}xx`;if(this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:p,attempt:a}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:h,durationMode:"machine",requestCategory:"session_read",statusClass:p,attempt:a}),!u.ok)throw await N(u,"Failed to get checkout session");let y=await u.json();return this.directTelemetry?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:p}),this.directTelemetry?.performance({stage:"session_complete",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"session_read",statusClass:p}),{...y,data:this.mergeCachedDisplayData(y.data)}}catch(u){throw c&&(0,d.markSessionResponseReceived)(u),n&&this.directTelemetry?.error({...(0,d.classifyTelemetryFailure)(u,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"}),u}}cacheSessionDisplayData(e,t,n){W(e,t,n)}clearSessionDisplayData(e){Te(e)}async getVaultCapture(e,t){let n=`${this.baseUrl}\0${e}\0${t??""}`,i=O.activeVaultCaptureRequests.get(n);if(i!==void 0)return i;let o=O.pendingThreeDsAbandonReports.get(e),s=o===void 0?this.requestVaultCapture(e,t):qr(o,xr).then(()=>this.requestVaultCapture(e,t));O.activeVaultCaptureRequests.set(n,s);try{return await s}finally{O.activeVaultCaptureRequests.get(n)===s&&O.activeVaultCaptureRequests.delete(n)}}async requestVaultCapture(e,t){let n=new AbortController,i=setTimeout(()=>n.abort(),Mr);this.beginDirectTelemetryCheckout(e);let o=this.telemetryTimestamp();this.directTelemetry?.log({name:"vault.capture.requested",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card"});let s={"Content-Type":"application/json"};t&&(s["x-checkout-session-token"]=t);try{let a=await ke(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/vault/capture`,{method:"POST",headers:s,signal:n.signal},Me,c=>{this.telemetryHooks?.onRetry?.("vault_capture",c),this.directTelemetry?.log({name:"operation.retry",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card",attempt:c})});if(await Pr(a))return this.directTelemetry?.performance({stage:"vault_request",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"4xx"}),{verification:{required:!0,provider:"turnstile"}};if(!a.ok)throw await N(a,"Failed to load the secure card form");let l=await a.json();return this.directTelemetry?.performance({stage:"vault_request",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"2xx"}),this.toVaultBlock(l)}catch(a){let l=n.signal.aborted?new d.FloPayError("Timed out while loading the secure card form. Please try again.","api_error",{code:"vault_capture_timeout"}):a;throw this.reportDirectFailure(l,"VAULT_LOAD_FAILED","vault_request","vault_capture","card"),l}finally{clearTimeout(i)}}async getUnifiedCheckoutSession(e,t){let n=await this.getCheckoutSession(e,t);return this.normalizeCheckoutSessionResponse(n)}async getUnifiedCheckoutSessionForRecovery(e,t,n){let i=await this.fetchCheckoutSession(e,t,!1,n);return this.normalizeCheckoutSessionResponse(i)}normalizeCheckoutSessionResponse(e){try{let t=this.normalizeRawSession(e.data),n=e.vault;return n&&t.data.session&&(t.data.session.vault=this.toVaultBlock(n)),t}catch(t){throw(0,d.markSessionResponseReceived)(t)}}async processPayment(e,t,n){this.beginDirectTelemetryCheckout(t.sessionId);let i=t.paymentMethodCategory??"unknown";if(!t.nonce)throw this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"process_payment",paymentMethodCategory:i}),new d.FloPayError("processPayment requires `nonce` \u2014 pass the value returned from session creation.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let o=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.processing.started",stage:"processing",requestCategory:"process_payment",paymentMethodCategory:i});let{nonce:s,paymentMethodCategory:a,...l}=t,c=Ar(t.tokenizedData),u,h;try{u=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(t.sessionId)}/process`,{method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":s},body:JSON.stringify(l)}),h=u}catch(p){if(Ve(p))throw this.reportDirectFailure(p,"PAYMENT_PROCESSING_FAILED","processing","process_payment",i),p;u=await this.reconcileProcessPayment(t.sessionId,{...n,nonce:s,paymentMethodCategory:i,submittedIntentId:c})}if(!u.ok&&u.status!==202){let p=await Fr(u);return p?this.directTelemetry?.terminal({outcome:p,stage:"processing",requestCategory:"process_payment",statusClass:"4xx",paymentMethodCategory:i}):this.directTelemetry?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",requestCategory:"process_payment",statusClass:(0,d.telemetryStatusClass)(u.status),failureCategory:u.status>=500?"server_error":void 0,paymentMethodCategory:i,...(0,d.readTelemetryHttpDiagnostics)(h)}),u}try{let p=await this.resolveProcessResponse(u,t.sessionId,{...n,nonce:s,paymentMethodCategory:i,submittedIntentId:c});return this.directTelemetry?.log({name:"payment.processing.completed",stage:"processing",requestCategory:"process_payment",statusClass:(0,d.telemetryStatusClass)(p.status),paymentMethodCategory:i}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"process_payment",statusClass:(0,d.telemetryStatusClass)(p.status),paymentMethodCategory:i}),p}catch(p){throw p instanceof d.FloPayError&&p.code==="checkout_processing_timeout"||this.reportDirectFailure(p,"PAYMENT_PROCESSING_FAILED","processing","process_payment",i),p}}async patchAccountSnapshot(e,t,n,i){this.beginDirectTelemetryCheckout(e);let o=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.state_transition",stage:"processing",requestCategory:"account_snapshot"});let s=i?.timeoutMs??Er,a=new AbortController,l=()=>a.abort();i?.signal&&(i.signal.aborted?a.abort():i.signal.addEventListener("abort",l,{once:!0}));let c=setTimeout(()=>a.abort(),s);try{let u;try{u=await ke(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/account`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":t},body:JSON.stringify(n),signal:a.signal},Me,h=>{this.telemetryHooks?.onRetry?.("account_snapshot",h),this.directTelemetry?.log({name:"operation.retry",stage:"processing",requestCategory:"account_snapshot",attempt:h})})}finally{clearTimeout(c),i?.signal?.removeEventListener("abort",l)}if(!u.ok)throw await N(u,"Failed to persist account snapshot");this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"account_snapshot",statusClass:"2xx"})}catch(u){throw this.reportAccountSnapshotFailure(u,i?.telemetryMode??"blocking"),u}}async createSessionIntent(e,t,n,i){if(!t)throw new d.FloPayError("createSessionIntent requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let o=n,s=o.paymentMethodType,a=typeof s=="string"&&s.trim().toLowerCase()==="card",l=typeof s=="string"&&s.length>0&&!a&&(typeof o.paymentMethodId=="string"||o.paymentMethodId===null),c=o.provider==="stripe"&&(o.paymentMethodCategory==="wallet"||o.paymentMethodCategory==="apm")&&(o.intentKind==="payment"||o.intentKind==="setup"),u=o.provider==="paypal"&&o.paymentMethodCategory==="wallet"&&o.paymentMethodId===null&&(o.paymentMethodType==="paypal"&&o.intentKind==="payment"||o.paymentMethodType===d.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&(o.intentKind==="payment"||o.intentKind==="setup"));if(!l||!c&&!u)throw new d.FloPayError("Only wallet, APM, and PayPal session intents are supported.","validation_error",{code:"InvalidSessionIntentRequest"});let h=o.authorizationAttemptId;if(h!==void 0&&!(0,d.isUuidV4)(h))throw new d.FloPayError("authorizationAttemptId must be a v4 UUID identifying one buyer authorization attempt.","validation_error",{code:"InvalidAuthorizationAttemptId",param:"authorizationAttemptId"});let p=(0,d.isUuidV4)(h)?h:(0,d.randomUuidV4)();this.beginDirectTelemetryCheckout(e);let y=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.intent.started",stage:"processing",requestCategory:"intent_create"});let m={"Content-Type":"application/json","x-checkout-session-token":t,[d.IDEMPOTENCY_KEY_HEADER]:i?.idempotencyKey||p},g=!1;try{let v=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents`,{method:"POST",headers:m,body:JSON.stringify({...n,authorizationAttemptId:p}),signal:i?.signal});if(!v.ok){g=!0;let w=await N(v,"Failed to create checkout intent"),Z=(0,d.classifyTelemetryFailure)(w,"PAYMENT_PROCESSING_FAILED");throw pt(w.statusCode)?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"intent_create",statusClass:"4xx"}):this.directTelemetry?.error({...Z,stage:"processing",requestCategory:"intent_create"}),w}let f=await v.json();if(v.status===202&&pe(f)&&f.type==="checkout_processing")return g=!0,await this.settleProcessingSessionIntent(f,v,e,t,n);let S=f.data;if(!S||typeof S!="object")throw new d.FloPayError("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});let C=S,F=C.paymentMethodType,G=(C.paymentMethodCategory==="wallet"||C.paymentMethodCategory==="apm")&&typeof F=="string"&&F.trim().toLowerCase()!=="card"&&(typeof C.paymentMethodId=="string"||C.paymentMethodId===null)&&typeof C.providerObjectId=="string",V=C.provider==="stripe"&&(C.intentKind==="payment"||C.intentKind==="setup")&&typeof C.clientSecret=="string",x=C.provider==="paypal"&&C.paymentMethodCategory==="wallet"&&C.paymentMethodId===null&&(C.paymentMethodType==="paypal"&&C.intentKind==="payment"&&(C.providerObjectType==="order"||C.providerObjectType==="subscription")||C.paymentMethodType===d.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&C.intentKind==="payment"&&C.providerObjectType==="order"||C.paymentMethodType===d.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&C.intentKind==="setup"&&C.providerObjectType==="setup_token")&&C.clientSecret===null,I=C.provider===n.provider&&C.paymentMethodCategory===n.paymentMethodCategory&&C.paymentMethodType===n.paymentMethodType&&C.paymentMethodId===n.paymentMethodId&&C.intentKind===n.intentKind;if(!G||!V&&!x||!I)throw new d.FloPayError("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});return this.directTelemetry?.log({name:"payment.intent.completed",stage:"processing",requestCategory:"intent_create",statusClass:(0,d.telemetryStatusClass)(v.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-y),durationMode:"machine",requestCategory:"intent_create",statusClass:(0,d.telemetryStatusClass)(v.status)}),C}catch(v){throw g||this.reportDirectFailure(v,"PAYMENT_PROCESSING_FAILED","processing","intent_create"),v}}async settleProcessingSessionIntent(e,t,n,i,o){let s=this.toCheckoutProcessingPending(e,t,n);try{return{settled:!0,response:await this.resolveCheckoutProcessing(s,n,{nonce:i,paymentMethodCategory:o.provider==="paypal"?"paypal":o.paymentMethodCategory})}}catch(a){throw a instanceof d.FloPayError&&a.code==="checkout_processing_timeout"?new d.FloPayError(a.message,a.type,{code:a.code,statusCode:202,sessionId:s.sessionId,cause:a}):a}}closeThreeDsChallenge(e,t,n,i={}){if(!e||!t||!n||i.signal?.aborted)return Promise.resolve("failed");let o=this.requestThreeDsChallengeClose(e,t,n,i.signal),s=O.pendingThreeDsAbandonReports;return s.set(e,o),o.then(()=>{s.get(e)===o&&s.delete(e)}),o}async requestThreeDsChallengeClose(e,t,n,i){let o=`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/3ds/abandoned`,s={method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":t},body:JSON.stringify({providerIntentId:n})};try{let a=await ht(o,s,i);if(a!=="retry")return a;if(i?.aborted)return"failed";await Ee(Ur,i);let l=await ht(o,s,i);return l==="retry"?"failed":l}catch{return"failed"}}async reportSessionIntentDecline(e,t,n,i){if(!t)throw new d.FloPayError("reportSessionIntentDecline requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let o=n,s=o.providerDeclineReason,a=o.paymentMethodType,l=o.providerIntentId,c=typeof s=="string"&&/^[a-z0-9][a-z0-9_.:-]{0,63}$/i.test(s)&&!/^(?:pm|pi|seti|tok|src|cus|sess|sk|pk)_/i.test(s),u=typeof a=="string"&&a.length>0&&a.trim().toLowerCase()!=="card"&&c,h=o.provider==="stripe"&&(o.paymentMethodCategory==="wallet"||o.paymentMethodCategory==="apm")&&(l===void 0||typeof l=="string"&&/^pi_[a-z0-9_]{1,252}$/i.test(l)),p=o.provider==="paypal"&&o.paymentMethodCategory==="wallet"&&o.paymentMethodType==="paypal"&&l===void 0;if(!u||!h&&!p)throw new d.FloPayError("Invalid non-card decline classification.","validation_error",{code:"InvalidSessionIntentDeclineRequest"});let y=p?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:s}:{provider:"stripe",paymentMethodCategory:o.paymentMethodCategory,paymentMethodType:o.paymentMethodType,providerDeclineReason:s,...typeof l=="string"?{providerIntentId:l}:{}},m=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents/decline`,{method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":t},body:JSON.stringify(y),signal:i?.signal});if(!m.ok)throw await N(m,"Failed to report checkout decline")}async resolvePaymentMethodLayout(e,t,n,i){if(!t)throw new d.FloPayError("resolvePaymentMethodLayout requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let o=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/payment-method-layout`,{method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":t,[d.FLO_SDK_VERSION_HEADER]:d.SDK_VERSION},body:JSON.stringify(n),signal:i?.signal});if(o.status===404||o.status===405)return null;if(!o.ok)throw await N(o,"Failed to resolve the payment method layout");let s=await o.json();return(0,d.normalizePaymentMethodLayout)(s?.data)}async getPaymentsByEmail(e,t){this.beginDirectTelemetryOperation();let n=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved"});let i=t?.page??1,o=t?.limit??1,s=new URLSearchParams({email:e,page:String(i),limit:String(o),sortField:"createdAt",sortDirection:"DESC"});try{let a=await fetch(`${this.baseUrl}/v1/payments?${s.toString()}`,{method:"GET",signal:t?.signal,keepalive:!0});if(!a.ok)throw(0,d.withTelemetryHttpDiagnostics)(new d.FloPayError("Failed to fetch payments","api_error",{statusCode:a.status}),a);let l=await a.json();return this.directTelemetry?.log({name:"operation.recovery.completed",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),this.directTelemetry?.performance({stage:"recovery",durationMs:Math.max(0,this.telemetryTimestamp()-n),durationMode:"machine",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),l}catch(a){throw this.reportDirectFailure(a,"RECOVERY_FAILED","recovery","other","saved"),a}}async createAndFetchSession(e){if((0,d.isDetachedSessionEligible)(e)){let o=e.account.email?.trim();if(o&&!(0,d.isValidEmail)(o))throw new d.FloPayError("Buyer email must be valid when supplied.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"});return(await this.createDetachedSession(e)).claimed}this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp(),n=L(e.timeoutMs??12e3),i={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});try{let o=await this.createAndFetchSessionRequest(e,n.signal,i);return this.adoptDirectTelemetryCheckout(o.data.session?.id),this.directTelemetry?.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:i.statusClass}),this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:"session_create",statusClass:i.statusClass,attempt:i.attempt}),o}catch(o){throw this.reportSessionCreateFailure(o,t,i),o}finally{n.clear()}}async createAndFetchSessionRequest(e,t,n){let i=e.products??(0,d.foldIntoProducts)(e.items,e.subscriptions);(0,d.assertCaptureMethodEligible)({captureMethod:e.captureMethod,products:i});let o=(0,d.resolveSessionCurrency)(e.currency,e.items,e.subscriptions,i);if(!o)throw new d.FloPayError("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 s={clientId:e.clientId,checkoutVersion:d.SDK_VERSION,successUrl:e.successUrl,cancelUrl:e.cancelUrl,currency:o,checkoutMode:e.checkoutMode??"full",products:i.map(c=>(0,d.buildProductPayload)(c,o)),accountData:vt(e.account),couponCodes:e.couponCodes??[]};e.captureMethod==="manual"&&(s.captureMethod=e.captureMethod),e.tokenizedData&&(s.tokenizedData=e.tokenizedData),Tt(s,e);let a=await this.postCheckoutSessionCreate(s,e,t,n),l=!1;try{let c=await a.json();if(c.data&&"gateways"in c.data){this.autoCacheDisplayData(c.data.uuid,e);let p=this.mergeCachedDisplayData(c.data),y=this.normalizeRawSession(p);return c.vault&&y.data.session&&(y.data.session.vault=this.toVaultBlock(c.vault)),{...y,autoProcessingError:c.autoProcessingError,autoProcessingAttempted:c.autoProcessingAttempted,autoProcessingPending:c.autoProcessingPending}}let u=c.data?.uuid;if(!u)throw new d.FloPayError("No session ID returned","api_error",{code:"InvalidCheckoutSessionResponse"});return this.autoCacheDisplayData(u,e),this.adoptDirectTelemetryCheckout(u),l=!0,{...await this.getUnifiedCheckoutSession(u),autoProcessingError:c.autoProcessingError,autoProcessingAttempted:c.autoProcessingAttempted,autoProcessingPending:c.autoProcessingPending}}catch(c){throw l?c:(0,d.markSessionResponseReceived)(c)}}async postCheckoutSessionCreate(e,t,n,i){let o={"Content-Type":"application/json",[d.FLO_SDK_VERSION_HEADER]:d.SDK_VERSION},s=(0,d.resolveIdempotencyKey)(t.idempotencyKey);s&&(o[d.IDEMPOTENCY_KEY_HEADER]=s);let a=[];t.checkoutMode==="auto"&&a.push(d.ASYNC_AUTO_CHECKOUT_CAPABILITY),this.stripeAccountSwitch&&e.deferDataAttachment===!0&&a.push(yt),a.length>0&&(o[d.FLO_SDK_CAPABILITIES_HEADER]=a.join(", "));let l,c=!1,u=Nr(t),h=(y,m,g)=>{c||(c=!0,this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:g,attempt:y}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:Math.max(0,this.telemetryTimestamp()-m),durationMode:"machine",requestCategory:"session_create",statusClass:g,attempt:y}))},p=y=>{try{this.telemetryHooks?.onRetry?.("session_create",y),this.directTelemetry?.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:y})}catch{}};for(let y=0;y<3;y++){i.attempt=y;let m=this.telemetryTimestamp();try{u?.onAttempt?.(y)}catch{}try{l=await fetch(`${this.baseUrl}/v1/checkouts/sessions?expand=true`,{method:"POST",headers:o,body:JSON.stringify(e),signal:n})}catch(f){if(i.statusClass=n.aborted||f instanceof Error&&f.name==="AbortError"?"timeout":"network_error",n.aborted||f instanceof Error&&f.name==="AbortError"||y>=2)throw f;let S=y+1;p(S),await te(y,n);continue}let g=(0,d.telemetryStatusClass)(l.status);if(i.statusClass=g,l.status===204)throw h(y,m,g),new d.FloPayError("Session auto-completed \u2014 payment method already on file","api_error",{code:"session_auto_completed"});if(l.ok){h(y,m,g);break}let v=await N(l,"Failed to create checkout session");if(v.code===d.IDEMPOTENCY_IN_PROGRESS_CODE&&y<2){p(y+1),await te(y,n);continue}throw h(y,m,g),v}if(!l)throw new TypeError("Checkout-session creation exhausted its retry budget.");return l}async createDetachedSession(e){this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp(),n=L(e.timeoutMs??12e3),i={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let o=e.products??(0,d.foldIntoProducts)(e.items,e.subscriptions);try{(0,d.assertCaptureMethodEligible)({captureMethod:e.captureMethod,products:o})}catch(f){throw n.clear(),this.reportSessionCreateFailure(f,t,i),f}let s=(0,d.resolveSessionCurrency)(e.currency,e.items,e.subscriptions,o);if(!s)throw n.clear(),this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),new d.FloPayError("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});try{ft(e,s,o)}catch(f){throw n.clear(),this.reportSessionCreateFailure(f,t,i),f}let a,l,c=!1;try{let f=await this.postCheckoutSessionCreate(zr(e,s,o),e,n.signal,i);if(c=!0,l=await f.json(),!l.data||!("gateways"in l.data))throw new d.FloPayError("The billing API returned no session shell for a detached create. It must support `deferDataAttachment` (TeamFloPay/backend#1099).","api_error",{code:"InvalidCheckoutSessionResponse"});a=this.normalizeRawSession(this.mergeCachedDisplayData(l.data)),l.vault&&a.data.session&&(a.data.session.vault=this.toVaultBlock(l.vault))}catch(f){throw n.clear(),c&&(0,d.markSessionResponseReceived)(f),this.reportSessionCreateFailure(f,t,i),f}let u=a.data.session?.id??l.data.uuid??"",h=a.data.session?.clientSecret??l.data.nonce??"";if(!u||!h){n.clear();let f=new d.FloPayError("Checkout session shell was created without a session id or nonce.","api_error",{code:"InvalidCheckoutSessionResponse"});throw this.reportSessionCreateFailure(f,t,i),f}n.clear(),this.adoptDirectTelemetryCheckout(u),this.directTelemetry?.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",statusClass:i.statusClass,paymentMethodCategory:"card"}),this.directTelemetry?.performance({stage:"session_shell",durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:"session_create",statusClass:i.statusClass,attempt:i.attempt,paymentMethodCategory:"card"});let p=!e.account.email?.trim(),y=L(e.timeoutMs??12e3),m=this.claimCheckoutSession(u,h,p?Hr(e,s,o):ft(e,s,o),{params:e,startedAt:t,deadline:y,createAttempt:i.attempt}),g=p?void 0:m,v=(f={})=>{if(g!==void 0)return g;let S={...e,account:{...e.account,...f,email:f.email?.trim()||e.account.email?.trim()}};return(0,d.isValidEmail)(S.account.email)?(g=m.then(()=>{let C=this.telemetryTimestamp();return this.claimCheckoutSession(u,h,Kr(S.account),{params:S,startedAt:C,deadline:L(e.timeoutMs??12e3),createAttempt:0})}),g.catch(()=>{}),g):Promise.reject(new d.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}))};return m.catch(()=>{}),{shell:a,sessionId:u,nonce:h,claimed:m,claim:v}}async claimCheckoutSession(e,t,n,i){let o=i?.startedAt??this.telemetryTimestamp(),s=this.telemetryTimestamp(),a=i?.deadline??L(12e3),l=JSON.stringify(n),c="unknown",u=0,h=!1;this.directTelemetry?.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"});try{let p;for(u=0;u<3;u++){try{p=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/claim`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":t,[d.FLO_SDK_VERSION_HEADER]:d.SDK_VERSION,...this.stripeAccountSwitch?{[d.FLO_SDK_CAPABILITIES_HEADER]:yt}:{}},body:l,signal:a.signal})}catch(g){let v=a.signal.aborted||g instanceof Error&&g.name==="AbortError";if(c=v?"timeout":"network_error",v||u>=2)throw g;try{this.telemetryHooks?.onRetry?.("session_claim",u+1),this.directTelemetry?.log({name:"operation.retry",stage:"session_claim",requestCategory:"session_claim",attempt:u+1})}catch{}await te(u,a.signal);continue}if(c=(0,d.telemetryStatusClass)(p.status),p.ok)break;throw await N(p,"Failed to attach checkout session data")}if(!p)throw new TypeError("Checkout-session claim exhausted its retry budget.");h=!0;let y=await p.json();if(!y.data?.gateways)throw new d.FloPayError("The billing API returned no checkout session with gateways after claiming it.","api_error",{code:"InvalidCheckoutSessionResponse"});i?.params&&this.autoCacheDisplayData(y.data.uuid??e,i.params);let m=this.normalizeRawSession(this.mergeCachedDisplayData(y.data));return y.vault&&m.data.session&&(m.data.session.vault=this.toVaultBlock(y.vault)),this.directTelemetry?.log({name:"session.claim.completed",stage:"session_claim",requestCategory:"session_claim",statusClass:c}),this.directTelemetry?.performance({stage:"session_claim",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"session_claim",statusClass:c,attempt:u}),this.directTelemetry?.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:c}),this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"session_create",statusClass:c,attempt:i?.createAttempt??u}),m}catch(p){throw h&&(0,d.markSessionResponseReceived)(p),this.reportSessionCreateFailure(p,s,{attempt:u,statusClass:c},"session_claim"),p}finally{a.clear()}}reportSessionCreateFailure(e,t,n,i="session_create"){if(!(e instanceof d.FloPayError&&e.code==="session_auto_completed"))try{this.telemetryHooks?.onSessionCreateFailure?.(e)}catch{}let o=(0,d.classifyTelemetryFailure)(e,"CHECKOUT_SESSION_CREATE_FAILED");if(this.directTelemetry?.performance({stage:i,durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:i==="session_claim"?"session_claim":"session_create",statusClass:o.statusClass,attempt:n.attempt}),e instanceof d.FloPayError&&e.type==="validation_error"||e instanceof d.FloPayError&&pt(e.statusCode)){this.directTelemetry?.terminal({outcome:"validation_rejected",stage:i,requestCategory:i==="session_claim"?"session_claim":"session_create",...e.type==="validation_error"?{}:{statusClass:"4xx"}});return}e instanceof d.FloPayError&&e.code==="session_auto_completed"||this.directTelemetry?.error({...o,stage:i,requestCategory:i==="session_claim"?"session_claim":"session_create"})}reportThreeDsAbandoned(e){this.beginDirectTelemetryCheckout(e),this.directTelemetry?.terminal({outcome:"customer_abandoned",stage:"three_ds_handoff",paymentMethodCategory:"saved"})}beginThreeDsChallenge(e,t={}){try{return this.directTelemetry?(this.beginDirectTelemetryCheckout(e),this.directTelemetry.beginThreeDsChallenge(t)):void 0}catch{return}}async waitForCheckoutSessionCompletion(e,t){this.beginDirectTelemetryCheckout(e);let n=this.telemetryTimestamp(),i=t?.paymentMethodCategory??"saved";this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:i});let o=t?.timeoutMs??Ae,s=Date.now()+o,a=new AbortController,l=!1,c,u=setTimeout(()=>{c=setTimeout(()=>{l=!0,a.abort()},ut)},o),h=()=>a.abort(t?.signal?.reason);t?.signal?.aborted?h():t?.signal?.addEventListener("abort",h,{once:!0});let p=this.clampRetryAfterMs(t?.initialDelayMs??ct),y=0;try{if(t?.statusUrl){let m=await this.waitForCheckoutStatus(e,{initialDelayMs:p,timeoutMs:o,nonce:t.nonce,statusUrl:t.statusUrl,pollAfterAction:t.continueAfterActionRequired,signal:a.signal});if(m){let g=await this.resolveCheckoutSessionStatus(e,m,t.nonce,a.signal,()=>l);return this.reportRecoveryCompleted(n,i,t.challengeAttemptId),g}}for(;;){let m=s-Date.now();if(m<=0)throw D();if(p>0){try{y+=1,this.telemetryHooks?.onRetry?.("session_read",y),this.directTelemetry?.log({name:"operation.retry",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:i,attempt:y})}catch{}if(await Ee(Math.min(p,m),a.signal),Date.now()>=s)throw D()}let g=await this.getUnifiedCheckoutSessionForRecovery(e,t?.nonce,a.signal),v=g.data.session?.status;if(v==="authorized"||v==="complete"||v==="expired")return this.reportRecoveryCompleted(n,i,t?.challengeAttemptId),g;if(Date.now()>=s)throw D();p=this.clampRetryAfterMs(Math.max(p*2,dt))}}catch(m){let g=l&&Ve(m)?D():m;throw this.reportDirectFailure(g,"RECOVERY_FAILED","recovery","session_read",i),g}finally{clearTimeout(u),clearTimeout(c),t?.signal?.removeEventListener("abort",h)}}reportRecoveryCompleted(e,t,n){let i={stage:"recovery",requestCategory:"session_read",paymentMethodCategory:t};if(this.directTelemetry?.log({name:"operation.recovery.completed",...i}),n)try{this.directTelemetry?.beginThreeDsChallenge({attemptId:n}).record("recovery_read_completed",{evidenceBasis:"server_status"})}catch{}this.directTelemetry?.performance({...i,durationMs:Math.max(0,this.telemetryTimestamp()-e),durationMode:"machine"})}async resolveCheckoutSessionStatus(e,t,n,i,o){let s=t.latestTransactionAttempt;if(this.rememberReportedFailure(e,t),s?.result==="DECLINE"){let c=s.code===d.STORED_PAYMENT_METHOD_UNSUPPORTED_CODE;throw new d.FloPayError(c?d.STORED_PAYMENT_METHOD_UNSUPPORTED_MESSAGE:"Payment was declined. Please choose another payment method.","api_error",{code:s.code??s.declineReason??"authorization_declined",statusCode:400})}if(s?.result==="ERROR"||t.status==="voided")throw br("Payment could not be completed. Please try again.",s?.code??"payment_processing_error");let a;try{a=await this.getUnifiedCheckoutSessionForRecovery(e,n,i)}catch(c){if(!o?.()||!Ve(c))throw c;a={providers:[],mode:"tokenize",data:{},raw:t}}let l=a.data.session;return l&&s?.result==="SUCCESS"?{...a,data:{...a.data,session:{...l,status:"complete"}}}:l&&s?.result==="AUTHORIZED"?{...a,data:{...a.data,session:{...l,status:"authorized",paymentId:t.paymentId??void 0,authorizationExpiresAt:t.authorizationExpiresAt??void 0}}}:l&&t.status==="completed"?{...a,data:{...a.data,session:{...l,status:"complete"}}}:l&&t.status==="authorized"?{...a,data:{...a.data,session:{...l,status:"authorized",paymentId:t.paymentId??void 0,authorizationExpiresAt:t.authorizationExpiresAt??void 0}}}:l&&t.status==="expired"?{...a,data:{...a.data,session:{...l,status:"expired"}}}:s?.result!=="ACTION_REQUIRED"?a:s.gateway==="paypal"&&s.providerIntentId?{...a,autoProcessingError:{type:"paypal_direct_required",message:"PayPal authorization required",orderId:s.providerIntentId,checkoutMethod:"paypal"}}:s.nextActionRedirectUrl?{...a,autoProcessingError:{type:"3ds_required",message:"Additional authentication is required.",nextActionRedirectUrl:s.nextActionRedirectUrl}}:a}async waitForCheckoutStatus(e,t){let n=t.timeoutMs??Ae,i=Date.now()+n,o=this.clampRetryAfterMs(t.initialDelayMs);for(;;){let s=i-Date.now();if(s<=0||o>0&&(await Ee(Math.min(o,s),t.signal),Date.now()>=i))throw D();let a=i-Date.now();if(a<=0)throw D();let l=new AbortController,c,u=t.signal?new Promise((S,C)=>{c=C}):null,h=()=>{l.abort(t.signal?.reason),c?.(t.signal?.reason??Object.assign(new Error("The operation was aborted."),{name:"AbortError"}))};t.signal?.aborted?h():t.signal?.addEventListener("abort",h,{once:!0});let p,y=t.signal?null:new Promise((S,C)=>{p=setTimeout(()=>{C(D()),l.abort()},a+ut)}),m;try{let S=this.fetchCheckoutStatus(e,t.nonce,t.statusUrl,l.signal);m=await Promise.race([S,y,u].filter(C=>C!==null))}finally{p!==void 0&&clearTimeout(p),t.signal?.removeEventListener("abort",h)}if(!m)return null;let g=lt(m.latestTransactionAttempt)&&!this.isOwnFailedAttempt(e,m,t.submittedIntentId);if(m.status==="completed"||m.status==="authorized"||m.status==="expired"||m.status==="voided")return g?{...m,latestTransactionAttempt:null}:m;let v=m.latestTransactionAttempt?.result,f=t.pollAfterAction===!0&&v==="ACTION_REQUIRED";if(!g&&v!==void 0&&v!=="PENDING"&&!f)return m;o=this.clampRetryAfterMs(Math.max(o*2,dt))}}isOwnFailedAttempt(e,t,n){let i=t.latestTransactionAttempt?.providerIntentId??null;return n!==void 0?i===n:i===null?!0:!Rr(t.uuid||e,i)}rememberReportedFailure(e,t){let n=t.latestTransactionAttempt;!lt(n)||!n.providerIntentId||wr(t.uuid||e,n.providerIntentId)}async fetchCheckoutStatus(e,t,n,i){let o=`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/status`,s=o;if(n)try{let u=new URL(n,`${this.baseUrl}/`),h=new URL(o);u.origin===h.origin&&(s=u.toString())}catch{}let a={[d.FLO_SDK_VERSION_HEADER]:d.SDK_VERSION};t&&(a["x-checkout-session-token"]=t);let l=await ke(s,{headers:a,signal:i});if(l.status===404||l.status===405)return null;if(!l.ok)throw await N(l,"Failed to get checkout session status");let c=await l.json();return pe(c.data)&&"latestTransactionAttempt"in c.data?c.data:null}normalizeRawSession(e){let t=e.gateways??{},n=[],i={session:this.toCheckoutSession(e)},o=t.stripe;if(o?.publishableKey){n.push("stripe");let l=[e.stripeClientSecret,o.stripeClientSecret].find(c=>typeof c=="string"&&c.length>0);i.stripe={clientSecret:l??"",publishableKey:o.publishableKey??void 0,paypalPublishableKey:o.paypalPublishableKey??void 0,environment:o.environment,enabledPaymentMethods:Array.isArray(o.enabledPaymentMethods)?o.enabledPaymentMethods.filter(c=>typeof c=="string"):void 0}}let s=t.paypal;return s?.publishableKey&&(n.push("paypal"),i.paypal={publishableKey:s.publishableKey,environment:s.environment,providerObjectType:s.providerObjectType,approvalPresentation:s.approvalPresentation}),{providers:n,mode:"tokenize",...e.checkoutMetadata===void 0?{}:{checkoutMetadata:e.checkoutMetadata},data:i,raw:{data:e}}}toCheckoutSession(e){let t=e.products??[],n=typeof e.totalAmount=="number"&&Number.isFinite(e.totalAmount),i=t.reduce((c,u)=>c+(u.overrideAmount??u.totalAmount??0),0),o=n?e.totalAmount:i,s=Math.round(o*100),a=e.currency??t[0]?.currency??"USD",l="payment";return e.checkoutMode==="setup"?l="setup":t.some(c=>c.type==="subscription")&&(l="subscription"),{id:e.uuid,clientSecret:e.nonce,mode:l,status:this.toCheckoutSessionStatus(e.status),amount:s,currency:a,captureMethod:e.captureMethod,paymentId:e.paymentId,authorizationExpiresAt:e.authorizationExpiresAt,failureOutcome:(0,d.normalizeCheckoutFailureOutcome)(e.outcome)??(0,d.normalizeCheckoutFailureOutcome)(e.failureReason)??(e.status==="expired"&&e.captureMethod==="manual"?"authorization_expired":void 0),customer:{id:e.accountData.userId??void 0,email:e.accountData.email??void 0,firstName:e.accountData.firstName??void 0,lastName:e.accountData.lastName??void 0,country:e.accountData.country??void 0,city:e.accountData.city??void 0,state:e.accountData.state??void 0,zip:e.accountData.zip??void 0,gender:e.accountData.gender??void 0,line1:e.accountData.addressLine1??void 0,line2:e.accountData.addressLine2??void 0},...e.checkoutMetadata===void 0?{}:{checkoutMetadata:e.checkoutMetadata},metadata:{},checkoutMode:e.checkoutMode,...Array.isArray(e.advertisedPaymentMethods)?{advertisedPaymentMethods:e.advertisedPaymentMethods}:{},...gr(e.futureUse)?{futureUse:e.futureUse}:{},...Array.isArray(e.futureUseUnsupported)?{futureUseUnsupported:e.futureUseUnsupported.filter(fr)}:{},buyerIdentified:e.buyerIdentified,providerPaymentMethodId:typeof e.providerPaymentMethodId=="string"?e.providerPaymentMethodId:null,products:t.map(c=>({...c,totalAmount:typeof c.totalAmount=="number"?c.totalAmount:void 0,overrideAmount:typeof c.overrideAmount=="number"?c.overrideAmount:null,currency:typeof c.currency=="string"?c.currency:void 0,metadata:c.metadata??null})),successUrl:e.successUrl,cancelUrl:e.cancelUrl,coupons:e.coupons,subtotalAmount:e.subtotalAmount,discountAmount:e.discountAmount,totalAmount:e.totalAmount,createdAt:e.createdAt,gateways:e.gateways,accountData:e.accountData,tagsData:e.tagsData}}toVaultBlock(e){let t=Dr(e.verification);return{html:typeof e.html=="string"?e.html:void 0,url:typeof e.url=="string"?e.url:void 0,messageToken:typeof e.messageToken=="string"?e.messageToken:void 0,expectedOrigin:typeof e.expectedOrigin=="string"?e.expectedOrigin:void 0,...t?{verification:t}:{}}}toCheckoutSessionStatus(e){return e==="completed"?"complete":e==="authorized"?"authorized":e==="expired"?"expired":"open"}async resolveProcessResponse(e,t,n){if(e.status!==202)return e;let i=await e.json().catch(()=>null),o=this.toCheckoutProcessingPending(i,e,t);return this.resolveCheckoutProcessing(o,t,n)}async resolveCheckoutProcessing(e,t,n){let i=n?.pollTimeoutMs??Ae,o=Date.now()+i;if(e.statusUrl){let a=await this.waitForCheckoutStatus(e.sessionId,{initialDelayMs:e.retryAfterMs,timeoutMs:i,nonce:n?.nonce,statusUrl:e.statusUrl,submittedIntentId:n?.submittedIntentId});if(a)return this.toProcessResponseFromStatus(a,t,n?.nonce)}let s=await this.waitForCheckoutSessionCompletion(e.sessionId,{initialDelayMs:e.retryAfterMs,timeoutMs:o-Date.now(),nonce:n?.nonce,paymentMethodCategory:n?.paymentMethodCategory});return this.toProcessResponseFromSession(s,t)}async toProcessResponseFromStatus(e,t,n){let i=e.latestTransactionAttempt?.result,o={[vr]:Tr},s={"Content-Type":"application/json",...o};if(e.status==="completed"||i==="SUCCESS")return new Response(null,{status:204,statusText:"No Content",headers:o});if(e.status==="authorized"||i==="AUTHORIZED")return new Response(JSON.stringify({status:"authorized",paymentId:e.paymentId??void 0,sessionId:e.uuid||t,authorizationExpiresAt:e.authorizationExpiresAt??void 0}),{status:200,headers:s});if(e.status==="expired"){let a=await this.resolveCheckoutSessionStatus(t,e,n);return this.toProcessResponseFromSession(a,t)}if(this.rememberReportedFailure(t,e),i==="DECLINE"){let a=e.latestTransactionAttempt,l=a?.code===d.STORED_PAYMENT_METHOD_UNSUPPORTED_CODE,c=a?.declineReason??void 0;return new Response(JSON.stringify({type:c??"authorization_declined",message:l?d.STORED_PAYMENT_METHOD_UNSUPPORTED_MESSAGE:"Payment was declined. Please choose another payment method.",code:a?.code??c??"authorization_declined",...c?{declineCode:c}:{}}),{status:400,headers:s})}if(i==="ACTION_REQUIRED"&&e.latestTransactionAttempt?.gateway==="paypal"&&e.latestTransactionAttempt.providerIntentId)return new Response(JSON.stringify({type:"paypal_direct_required",message:"PayPal authorization required",orderId:e.latestTransactionAttempt.providerIntentId}),{status:400,headers:s});if(i==="ACTION_REQUIRED"&&e.latestTransactionAttempt?.nextActionRedirectUrl)return new Response(JSON.stringify({type:"3ds_required",message:"Additional authentication is required.",nextActionRedirectUrl:e.latestTransactionAttempt.nextActionRedirectUrl}),{status:400,headers:s});if(i==="ERROR"||e.status==="voided")return new Response(JSON.stringify({type:"unknown",code:e.latestTransactionAttempt?.code??"payment_processing_error",message:Cr(e)??"Payment could not be completed. Please try again."}),{status:500,headers:s});throw D()}async reconcileProcessPayment(e,t){let n=t?.pollTimeoutMs??Ae,i=Date.now()+n,o=null;try{o=await this.waitForCheckoutStatus(e,{initialDelayMs:0,timeoutMs:n,nonce:t?.nonce,submittedIntentId:t?.submittedIntentId})}catch(l){if(this.reportDirectFailure(l,"RECOVERY_FAILED","recovery","session_read",t?.paymentMethodCategory??"saved"),l instanceof d.FloPayError&&l.code==="checkout_processing_timeout")throw l}if(o)return this.toProcessResponseFromStatus(o,e,t?.nonce);let s=i-Date.now();if(s<=0)throw D();let a=await this.waitForCheckoutSessionCompletion(e,{initialDelayMs:0,timeoutMs:s,nonce:t?.nonce,paymentMethodCategory:t?.paymentMethodCategory});return this.toProcessResponseFromSession(a,e)}toProcessResponseFromSession(e,t){if(e.data.session?.status==="complete")return new Response(null,{status:204,statusText:"No Content"});if(e.data.session?.status==="authorized"){let n=e.data.session;return new Response(JSON.stringify({status:"authorized",paymentId:n.paymentId,sessionId:n.id||t,authorizationExpiresAt:n.authorizationExpiresAt}),{status:200,headers:{"Content-Type":"application/json"}})}if(e.data.session?.status==="expired"){let n=e.data.session.failureOutcome==="authorization_expired"||e.data.session.captureMethod==="manual";throw new d.FloPayError(n?"Authorization has expired.":"Checkout session has expired.","api_error",{code:n?"authorization_expired":"checkout_session_expired"})}throw D()}toCheckoutProcessingPending(e,t,n){let i=t.headers.get("Retry-After"),o=i===null||i.trim()===""?void 0:Number(i),s=o!==void 0&&Number.isFinite(o)?o*1e3:void 0;return{type:"checkout_processing",sessionId:K(e,"sessionId")??n,retryAfterMs:this.clampRetryAfterMs(Ir(e,"retryAfterMs")??s??ct),statusUrl:K(e,"statusUrl"),sessionUrl:K(e,"sessionUrl")}}clampRetryAfterMs(e){return Math.max(0,Math.min(e,kr))}autoCacheDisplayData(e,t){if(!e)return;let n=t.products??(0,d.foldIntoProducts)(t.items,t.subscriptions);if(n.length===0&&!t.currency)return;let i=t.products!==void 0,o=(0,d.resolveSessionCurrency)(t.currency,i?void 0:t.items,i?void 0:t.subscriptions,n);W(e,{currency:o??void 0,products:n.map(s=>({code:s.code??s.providerItemId??s.providerPlanId,type:s.type,name:s.name??s.itemName??s.providerItemName??s.subscriptionName??s.providerPlanName??null,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount,currency:s.currency??o??void 0}))})}mergeCachedDisplayData(e){let t=ve(e.uuid),n=new Map,i=s=>s?`code:${s}`:void 0;for(let s of t?.products??[]){let a=i(s.code);a&&n.set(a,s)}let o=(e.products??[]).map(s=>{let a=i(s.code),l=a?n.get(a):void 0;return{...s,name:s.name??l?.name??null,totalAmount:s.totalAmount??l?.totalAmount,overrideAmount:s.overrideAmount??l?.overrideAmount,currency:s.currency??l?.currency}});return{...e,currency:e.currency??t?.currency,products:o}}};O.activeVaultCaptureRequests=new Map,O.pendingThreeDsAbandonReports=new Map;var Q=O;function bt(r,e){let t=Q;return new t(r,e)}var _=require("@flopay/shared");var Pe=require("@flopay/shared");function _t(r){if(!r)return null;try{let e=new URL(r,window.location.href);return e.origin==="null"?null:e.origin}catch{return null}}var Ie=class{constructor(e){this.options=e;this.handlers=new Set;this.active=!1;this.readyReported=!1;this.failureReported=!1;this.startedAt=0;this.timer=null;this.detach=null}subscribe(e){return this.handlers.add(e),()=>{this.handlers.delete(e)}}begin(){this.end(),this.active=!0,this.readyReported=!1,this.failureReported=!1,this.startedAt=this.options.now();let e=(0,Pe.resolveCardFieldsTimeoutMs)(this.options.timeoutMs);this.timer=setTimeout(()=>{this.timer=null,this.reportFailure("timeout",e)},e)}watch(e){if(!this.active)return;this.detachWatchers();let t=new Set,n=[];for(let o of Array.from(e.querySelectorAll("script[src], iframe[src]"))){let s=_t(o.getAttribute("src"));if(s&&t.add(s),o.tagName==="SCRIPT"){let a=()=>this.fail("load_error");o.addEventListener("error",a),n.push(()=>o.removeEventListener("error",a))}}let i=o=>{let s=_t(o.blockedURI);s&&t.has(s)&&this.fail("blocked")};document.addEventListener("securitypolicyviolation",i),n.push(()=>document.removeEventListener("securitypolicyviolation",i)),this.detach=()=>{for(let o of n)o()}}ready(){!this.active||this.readyReported||(this.readyReported=!0,this.clearTimer(),this.detachWatchers(),this.dispatch({type:"card_fields_ready",elapsedMs:this.elapsed()}))}fail(e){this.reportFailure(e,0)}reportFailure(e,t){!this.active||this.readyReported||this.failureReported||(this.failureReported=!0,this.clearTimer(),this.dispatch({type:"card_fields_failed",reason:e,elapsedMs:Math.max(t,this.elapsed())}))}end(){this.active=!1,this.clearTimer(),this.detachWatchers()}elapsed(){return Math.max(0,Math.round(this.options.now()-this.startedAt))}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}detachWatchers(){this.detach?.(),this.detach=null}dispatch(e){try{this.options.report?.(e)}catch{}for(let t of Array.from(this.handlers))(0,Pe.invokeMerchantCallback)(()=>t(e))}};var $r=4,De="flopay-vault",Gr=3e4,Yr=_.THREE_DS_CHALLENGE_WINDOW_MS+Gr,Wr="Card authentication timed out.",St={ready:["vault.widget.ready","vault_ready"],submitting:["vault.submission.started","vault_submit"],blocked:["operation.state_transition","vault_submit"],action_required:["vault.action.required","three_ds_handoff"]};function Jr(r){return r.class==="lifecycle"?r.name:r.class==="technical_error"?r.code:r.class==="expected_outcome"?r.outcome:"sdk.performance"}function ne(r){let e={class:r.class,stage:r.stage};"code"in r&&(e.code=r.code),"provider"in r&&r.provider&&(e.provider=r.provider),"paymentMethodCategory"in r&&r.paymentMethodCategory&&(e.paymentMethodCategory=r.paymentMethodCategory),"outcome"in r&&(e.outcome=r.outcome),"durationMs"in r&&r.durationMs!==void 0&&(e.durationMs=r.durationMs),"durationMode"in r&&r.durationMode&&(e.durationMode=r.durationMode);try{globalThis.Sentry?.addBreadcrumb?.({category:"flopay.telemetry",level:r.class==="technical_error"?"error":"info",message:Jr(r),data:e})}catch{}}function he(r,e){return(0,_.buildTelemetryLogEvent)({eventId:"11111111-1111-4111-8111-111111111111",name:r,stage:e,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}var Qr=new Set(["authorization_declined","authentication_required","authorization_expired","capture_failed"]);function Xr(r){return typeof r=="string"&&Qr.has(r)?r:"unknown"}var Zr=new Set(["verification_failed","verification_expired"]);function en(r){return r==null?!0:typeof r=="string"&&Zr.has(r)}var tn="vault_mount";function rn(r){return r.failureStage===tn}function je(r,e){return r&&!rn(e)?{errorCode:"VAULT_SUBMIT_FAILED",stage:"vault_submit",failureCategory:"provider_runtime",reason:Xr(e.failureOutcome)}:{errorCode:"VAULT_LOAD_FAILED",stage:"vault_mount",failureCategory:"provider_runtime"}}function Rt(r,e,t="checkout"){return t==="card_setup"?r.type==="decline"?"card_setup_declined":"card_setup_succeeded":r.type==="decline"?"payment_declined":r.outcome==="authorized"||e==="manual"?"payment_authorized":"payment_succeeded"}function nn(r,e,t,n="checkout"){let{type:i}=r;if(i==="complete"||i==="decline")return(0,_.buildTelemetryTerminalEvent)({eventId:"22222222-2222-4222-8222-222222222222",outcome:Rt(r,t,n),sequence:0,provider:"pcivault",paymentMethodCategory:"card"});if(i==="error"){let a=je(e,r);return(0,_.buildTelemetryErrorEvent)({eventId:"33333333-3333-4333-8333-333333333333",...a,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}let[o,s]=St[i];return he(o,s)}function on(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===De&&(e.type==="ready"||e.type==="submitting"||e.type==="blocked"||e.type==="complete"||e.type==="decline"||e.type==="error"||e.type==="action_required")}function sn(r){if(typeof r!="object"||r===null)return;let e=r;if(typeof e.code!="string"||e.code.trim()==="")return;let t=typeof e.message=="string"&&e.message.trim()!==""?e.message:void 0;return t?{code:e.code,message:t}:{code:e.code}}function an(r){if(typeof r!="object"||r===null)return;let e=r,t=e.status;if(!(typeof e.id!="string"||e.id.trim()===""||typeof e.brand!="string"||e.brand.trim()===""||typeof e.lastFour!="string"||!/^\d{4}$/.test(e.lastFour)||typeof e.expiryMonth!="number"||!Number.isInteger(e.expiryMonth)||e.expiryMonth<1||e.expiryMonth>12||typeof e.expiryYear!="number"||!Number.isInteger(e.expiryYear)||e.expiryYear<1970||e.expiryYear>9999||t!=="pending"&&t!=="active"&&t!=="deleted"))return{id:e.id,brand:e.brand,lastFour:e.lastFour,expiryMonth:e.expiryMonth,expiryYear:e.expiryYear,status:t}}function ln(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===De&&e.type==="validation"&&Array.isArray(e.messages)}function cn(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===De&&e.type==="resize"&&typeof e.height=="number"&&Number.isFinite(e.height)}function dn(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===De&&e.type==="fields_interactive"}function un(r){let e=r.capabilities;return Array.isArray(e)&&e.includes("fields_interactive")}var mn=["number","expiry","cvv","name"];function pn(r){if(r===null||typeof r!="object")return;let e=r,t={};for(let n of mn){let i=e[n];typeof i=="string"&&(t[n]=i)}return t}var X=class{constructor(e={},t){this.provider="pcivault";this.container=null;this.messageHandler=null;this.actionOverlay=null;this.threeDsReturnHandler=null;this.actionChallenge=null;this.lastChallengeTelemetry=null;this.actionOverlayPreviousFocus=null;this.actionOverlayTimer=null;this.actionChallengeIntentId=null;this.messageToken=null;this.expectedOrigin=null;this.theme=void 0;this.submitGateBlocked=!1;this.cardFieldOrder=null;this.cardAutoFocus=!0;this.cardBrandIcons=!1;this.showCardFieldLabels=void 0;this.cardFieldLabels=void 0;this.submitLabel=void 0;this.cardFieldPlaceholders=void 0;this.mountStartedAt=0;this.vaultReadyReported=!1;this.verificationRequired=!1;this.submissionStarted=!1;this.submissionStartedAt=null;this.listeners=new Map;this.config=e,this.cardFields=new Ie({timeoutMs:e.cardFieldsTimeoutMs,now:()=>this.telemetryReporter?.now?.()??E(),report:n=>this.reportCardFields(n)}),this.ownsTelemetryReporter=!t&&e.telemetry!==!1,this.telemetryReporter=t?.reporter??(this.ownsTelemetryReporter?new A({billingApiUrl:(0,_.resolveBillingApiUrl)(e.billingApiUrl),sdkVersion:_.SDK_VERSION}):void 0)}async mount(e,t){this.ownsTelemetryReporter&&!this.telemetryReporter&&(this.telemetryReporter=new A({billingApiUrl:(0,_.resolveBillingApiUrl)(this.config.billingApiUrl),sdkVersion:_.SDK_VERSION}));let n=this.telemetryReporter;if(this.config.operation==="card_setup"&&n&&this.setupTelemetryReporter!==n){this.setupTelemetryReporter=n;try{n.beginCheckout({checkoutMode:"setup"})}catch{}}if(this.mountStartedAt=this.telemetryReporter?.now?.()??E(),this.vaultReadyReported=!1,this.submissionStarted=!1,this.submissionStartedAt=null,this.cardFields.begin(),typeof window>"u"||typeof document>"u")throw this.reportVaultLoadFailure(),this.failCardFieldsMount(),new _.FloPayError("The vault card form is only available in the browser.","api_error",{code:"card_capture_no_window"});if(!t?.html?.trim())throw this.reportVaultLoadFailure(),this.failCardFieldsMount(),new _.FloPayError("No vault capture widget HTML was provided to mount the secure card form.","api_error",{code:"card_capture_no_widget_html"});this.container=e,this.verificationRequired=t.verificationRequired===!0,this.messageToken=t.messageToken??null,this.expectedOrigin=t.expectedOrigin??this.config.expectedOrigin??null,this.theme=t.theme,t.submitLabel!==void 0&&(this.submitLabel=t.submitLabel);try{this.attachMessageListener(),this.injectWidget(e,t.html),this.cardFields.watch(e)}catch(i){throw this.reportVaultLoadFailure(),this.failCardFieldsMount(),i}this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),this.postCardBrandIcons(),this.postCardFieldLabels(),this.postCardFieldPlaceholders(),this.postSubmitLabel(),ne(he("vault.widget.mounted","vault_mount")),this.telemetryReporter?.log({name:"vault.widget.mounted",stage:"vault_mount",provider:"pcivault",paymentMethodCategory:"card"}),this.telemetryReporter?.performance?.({stage:"vault_mount",durationMs:Math.max(0,(this.telemetryReporter.now?.()??E())-this.mountStartedAt),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card"}),this.emit("ready",{sessionId:this.config.sessionId})}reportVaultLoadFailure(){this.telemetryReporter?.error({errorCode:"VAULT_LOAD_FAILED",failureCategory:"provider_runtime",stage:"vault_mount",provider:"pcivault",paymentMethodCategory:"card"})}on(e,t){let n=this.listeners.get(e);return n||(n=new Set,this.listeners.set(e,n)),n.add(t),()=>{this.listeners.get(e)?.delete(t)}}onCardFields(e){return this.cardFields.subscribe(e)}failCardFieldsMount(){this.cardFields.fail("other"),this.cardFields.end()}reportCardFields(e){let t=e.type==="card_fields_ready",n=this.config.sessionId;this.telemetryReporter?.log({name:t?"vault.fields.ready":"vault.fields.failed",stage:t?"vault_ready":"vault_mount",provider:"pcivault",paymentMethodCategory:"card",elapsedMs:e.elapsedMs,...e.type==="card_fields_failed"?{loadFailureReason:e.reason}:{},...n?{checkoutSessionId:n}:{}})}unmount(){if(this.cardFields.end(),this.actionChallenge){let{telemetry:e}=this.actionChallenge;e.record("abort_observed",{reason:"component_unmount",evidenceBasis:"signal_reason"}),e.terminal("abort",{reason:"component_unmount",evidenceBasis:"signal_reason"})}this.lastChallengeTelemetry=null,this.hideActionRequiredOverlay(),this.messageHandler&&(window.removeEventListener("message",this.messageHandler),this.messageHandler=null),this.container&&(this.container.replaceChildren(),this.container=null),this.messageToken=null,this.expectedOrigin=null,this.ownsTelemetryReporter&&(this.telemetryReporter?.destroy(),this.telemetryReporter=void 0)}injectWidget(e,t){e.innerHTML=t;let n=Array.from(e.querySelectorAll("script"));for(let i of n){let o=document.createElement("script");for(let s of Array.from(i.attributes))o.setAttribute(s.name,s.value);o.text=i.text,i.replaceWith(o)}}attachMessageListener(){if(this.messageHandler)return;let e=t=>{if(this.expectedOrigin&&t.origin!==this.expectedOrigin)return;let n=t.data;if(cn(n)){if(this.messageToken&&n.messageToken!==this.messageToken)return;this.applyHeight(n.height);return}if(ln(n)){if(this.messageToken&&n.messageToken!==this.messageToken)return;let c=n.messages.filter(u=>typeof u=="string"&&u.trim()).join(" ");this.emit("validation",{sessionId:this.config.sessionId,message:c||void 0});return}if(dn(n)){if(this.messageToken&&n.messageToken!==this.messageToken)return;let c=typeof n.sessionId=="string"?n.sessionId:void 0;if(this.config.sessionId&&c&&c!==this.config.sessionId)return;this.cardFields.ready();return}if(!on(n)||this.messageToken&&n.messageToken!==this.messageToken)return;let i=this.config.sessionId,o=typeof n.sessionId=="string"?n.sessionId:void 0;if(i&&o&&o!==i||(n.type==="complete"||n.type==="decline")&&i&&o!==i)return;let s=an(n.paymentMethod),a=sn(n.vaultOutcome),l={...n.sessionId??this.config.sessionId?{sessionId:n.sessionId??this.config.sessionId}:{},...n.outcome?{outcome:n.outcome}:{},...n.paymentId?{paymentId:n.paymentId}:{},...n.authorizationExpiresAt?{authorizationExpiresAt:n.authorizationExpiresAt}:{},...n.failureOutcome?{failureOutcome:n.failureOutcome}:{},...n.intentId?{intentId:n.intentId}:{},...n.declineReason?{declineReason:n.declineReason}:{},...n.message?{message:n.message}:{},...a?{vaultOutcome:a}:{},...s?{paymentMethod:s}:{}};n.type==="submitting"&&(this.submissionStarted=!0,this.submissionStartedAt=this.telemetryReporter?.now?.()??E()),this.isVerificationStateError(n)?(ne(he("operation.state_transition","vault_mount")),this.telemetryReporter?.log({name:"operation.state_transition",stage:"vault_mount",provider:"pcivault",paymentMethodCategory:"card"})):(ne(nn(n,this.submissionStarted,this.config.captureMethod,this.config.operation)),this.reportOutcome(n),n.type==="error"&&je(this.submissionStarted,n).errorCode==="VAULT_LOAD_FAILED"&&this.cardFields.fail("load_error")),n.type==="ready"&&(this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),this.postCardBrandIcons(),this.postCardFieldLabels(),this.postCardFieldPlaceholders(),this.postSubmitLabel(),un(n)||this.cardFields.ready()),n.type==="action_required"&&n.nextActionRedirectUrl&&(this.showActionRequiredOverlay(n.nextActionRedirectUrl),this.actionOverlay&&typeof n.intentId=="string"&&n.intentId&&(this.actionChallengeIntentId=n.intentId)),(n.type==="complete"||n.type==="decline"||n.type==="error"||n.type==="submitting")&&(this.endActionChallengeFromWidget(n.type),this.hideActionRequiredOverlay()),n.type!=="action_required"&&this.emit(n.type,l)};this.messageHandler=e,window.addEventListener("message",e)}isVerificationStateError(e){return e.type==="error"&&this.verificationRequired&&!this.submissionStarted&&en(e.failureOutcome)}reportOutcome(e){let t=this.telemetryReporter;if(!t)return;let{type:n}=e;if(n==="ready"&&!this.vaultReadyReported&&(this.vaultReadyReported=!0,t.performance({stage:"vault_ready",durationMs:Math.max(0,t.now()-this.mountStartedAt),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card",requestCategory:"provider_sdk"})),n==="complete"||n==="decline"){t.log({name:"vault.terminal",stage:"completion",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:Rt(e,this.config.captureMethod,this.config.operation),provider:"pcivault",paymentMethodCategory:"card"});return}if(n==="error"){let s=je(this.submissionStarted,e);t.log({name:"vault.terminal",stage:s.stage,provider:"pcivault",paymentMethodCategory:"card"}),t.error({...s,provider:"pcivault",paymentMethodCategory:"card"});return}if(n==="action_required"){t.log({name:"vault.action.required",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"}),t.log({name:"vault.three_ds.handoff",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"});let s=this.submissionStartedAt;this.submissionStartedAt=null,s!==null&&t.performance({stage:"three_ds_handoff",durationMs:Math.max(0,t.now()-s),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:"action_required",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"});return}let[i,o]=St[n];t.log({name:i,stage:o,provider:"pcivault",paymentMethodCategory:"card"})}applyTheme(e){this.theme=e,this.postTheme()}postTheme(){this.theme!==void 0&&this.postToHostedWindow({source:"flopay-vault-host",type:"theme",theme:this.theme},this.directiveTargetOrigin())}setSubmitGate(e){this.submitGateBlocked=e,this.postSubmitGate()}postSubmitGate(){this.postToHostedWindow({source:"flopay-vault-host",type:"gate",blocked:this.submitGateBlocked},this.directiveTargetOrigin())}setCardFieldOrder(e,t){this.cardFieldOrder=e,this.cardAutoFocus=t,this.postCardFieldOrder()}postCardFieldOrder(){this.postToHostedWindow({source:"flopay-vault-host",type:"fieldOrder",order:this.cardFieldOrder,autoFocus:this.cardAutoFocus},this.directiveTargetOrigin())}setCardBrandIcons(e){this.cardBrandIcons=e===!0,this.postCardBrandIcons()}setShowCardFieldLabels(e){this.showCardFieldLabels=e===!0,this.postCardFieldLabels()}setCardFieldLabels(e){this.cardFieldLabels=(0,_.buildCardFieldLabelsPayload)(e),this.postCardFieldLabels()}postCardFieldLabels(){let e=this.showCardFieldLabels,t=this.cardFieldLabels;if(e===void 0&&t===void 0)return;let n=this.config.sessionId,{messageToken:i,expectedOrigin:o}=this;!n||!i||!o||this.postToHostedWindow({source:"flopay-vault-host",type:"cardFieldLabels",sessionId:n,messageToken:i,...e===void 0?{}:{show:e},...t===void 0?{}:{labels:{...t}}},o)}setCardFieldPlaceholders(e){let t=pn(e),n=t===void 0&&this.cardFieldPlaceholders!==void 0;this.cardFieldPlaceholders=t,this.postCardFieldPlaceholders(n?{}:t)}postCardFieldPlaceholders(e=this.cardFieldPlaceholders){let t=this.config.sessionId,{messageToken:n,expectedOrigin:i}=this;e===void 0||!t||!n||!i||this.postToHostedWindow({source:"flopay-vault-host",type:"cardFieldPlaceholders",sessionId:t,messageToken:n,placeholders:{...e}},i)}postCardBrandIcons(){this.postToHostedWindow({source:"flopay-vault-host",type:"cardBrandIcons",show:this.cardBrandIcons},this.directiveTargetOrigin())}setSubmitLabel(e){this.submitLabel=e,this.postSubmitLabel()}postSubmitLabel(){let e=this.submitLabel,t=this.config.sessionId,{messageToken:n,expectedOrigin:i}=this;e===void 0||!t||!n||!i||this.postToHostedWindow({source:"flopay-vault-host",type:"submitLabel",sessionId:t,messageToken:n,label:e},i)}hostedWindow(){return this.container?.querySelector("iframe")?.contentWindow??null}postToHostedWindow(e,t){let n=this.hostedWindow();if(n)try{n.postMessage(e,t)}catch{}}directiveTargetOrigin(){return this.expectedOrigin??"*"}emit(e,t){for(let n of this.listeners.get(e)??[])n(t)}showActionRequiredOverlay(e){if(typeof document>"u")return;if(this.actionOverlay){let m=this.actionOverlay.querySelector("iframe");m instanceof HTMLIFrameElement&&m.src!==e&&(m.src=e),this.armActionRequiredTimeout();return}this.actionOverlayPreviousFocus=document.activeElement instanceof HTMLElement?document.activeElement:null;let t=de(this.beginActionChallengeAttempt()),n=Se(e),i=!1,o=m=>{if(i)return;let g=_e(m,n);g&&(i=!0,t.record("policy_violation",{reason:g,evidenceBasis:"parent_csp_event"}))},s=()=>{t.record("pagehide_observed",{evidenceBasis:"page_lifecycle_event"})},a={telemetry:t,loaded:!1,detach:()=>{document.removeEventListener("securitypolicyviolation",o),window.removeEventListener("pagehide",s)}};this.actionChallenge=a,this.lastChallengeTelemetry=t,t.record("handoff_planned"),ue(e)==="invalid"&&t.record("action_invalid",{reason:"invalid_url"}),document.addEventListener("securitypolicyviolation",o),window.addEventListener("pagehide",s);let l=document.createElement("div");l.setAttribute("data-flopay-action-required","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 c=document.createElement("iframe");c.setAttribute("title","Card authentication"),c.setAttribute("allow","payment"),c.tabIndex=0,c.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(";"),c.addEventListener("load",()=>{a.loaded||(a.loaded=!0,t.record("iframe_load",{evidenceBasis:"iframe_load_event"}))}),c.src=e,l.appendChild(c);let u=document.createElement("button");u.type="button",u.setAttribute("aria-label","Close card authentication"),u.textContent="\xD7",u.style.cssText=["position:fixed","top:20px","right:20px","width:40px","height:40px","border:0","border-radius:9999px","background:#fff","color:#0f172a","font-size:28px","line-height:40px","cursor:pointer","box-shadow:0 4px 14px rgba(0,0,0,0.25)"].join(";"),u.addEventListener("click",()=>this.abandonActionRequiredOverlay()),l.appendChild(u),l.addEventListener("click",m=>{m.target===l&&this.abandonActionRequiredOverlay()});let h=0,p=m=>{let g=m.data,v=!!g&&typeof g=="object"&&g.source==="flopay-vault-3ds-return";if(m.source!==c.contentWindow){v&&h<$r&&(h+=1,t.record("return_rejected",{reason:"untrusted_source",evidenceBasis:"message_origin_check"}));return}v&&(t.record("trusted_return",{evidenceBasis:"message_origin_check"}),t.terminal("trusted_return",{evidenceBasis:"message_origin_check"}),ne(he("vault.three_ds.returned","three_ds_return")),this.telemetryReporter?.log({name:"vault.three_ds.returned",stage:"three_ds_return",provider:"pcivault",paymentMethodCategory:"card"}),this.hideActionRequiredOverlay())};window.addEventListener("message",p),this.threeDsReturnHandler=p,t.record("render_attempted");try{document.body.appendChild(l)}catch(m){throw t.record("render_failed"),this.hideActionRequiredOverlay(),this.actionOverlayPreviousFocus=null,m}t.record("container_attached"),t.record("navigation_assigned");let y=be(l);y&&t.record("container_visibility",{reason:y,evidenceBasis:"parent_computed_style"}),this.actionOverlay=l,c.focus(),this.armActionRequiredTimeout(),ne(he("vault.three_ds.handoff","three_ds_handoff"))}armActionRequiredTimeout(){this.actionOverlayTimer&&clearTimeout(this.actionOverlayTimer),this.actionOverlayTimer=setTimeout(()=>{this.actionOverlayTimer=null,this.actionOverlay&&this.timeOutActionRequiredOverlay()},Yr)}reportChallengeAbandoned(){ne((0,_.buildTelemetryTerminalEvent)({eventId:"77777777-7777-4777-8777-777777777777",outcome:"customer_abandoned",stage:"three_ds_handoff",sequence:0,provider:"pcivault",paymentMethodCategory:"card"})),this.telemetryReporter?.terminal({outcome:"customer_abandoned",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"})}timeOutActionRequiredOverlay(){if(this.actionChallenge){let{telemetry:e,loaded:t}=this.actionChallenge;t||e.record("load_unconfirmed",{evidenceBasis:"no_load_signal"}),e.record("timer_expired",{reason:"window_elapsed",evidenceBasis:"timer"}),e.terminal("timer",{reason:"window_elapsed",evidenceBasis:"timer"})}this.reportChallengeAbandoned(),this.closeAbandonedChallenge(),this.hideActionRequiredOverlay(),this.emit("error",{...this.config.sessionId?{sessionId:this.config.sessionId}:{},message:Wr})}abandonActionRequiredOverlay(){if(this.actionOverlay){if(this.actionChallenge){let{telemetry:e}=this.actionChallenge;e.record("cancel_requested",{reason:"buyer_cancel",evidenceBasis:"signal_reason"}),e.terminal("cancel",{reason:"buyer_cancel",evidenceBasis:"signal_reason"})}this.reportChallengeAbandoned(),this.closeAbandonedChallenge(),this.hideActionRequiredOverlay(),this.emit("challenge_dismissed",{...this.config.sessionId?{sessionId:this.config.sessionId}:{}})}}closeAbandonedChallenge(){let e=this.actionChallengeIntentId;this.actionChallengeIntentId=null;let{sessionId:t,sessionToken:n}=this.config;if(!(!e||!t||!n))try{new Q((0,_.resolveBillingApiUrl)(this.config.billingApiUrl),{telemetry:!1}).closeThreeDsChallenge(t,n,e).catch(()=>{})}catch{}}beginActionChallengeAttempt(){try{return this.telemetryReporter?.beginThreeDsChallenge?.()}catch{return}}endActionChallengeFromWidget(e){let t=this.actionChallenge,n=t?.telemetry??this.lastChallengeTelemetry;if(this.lastChallengeTelemetry=null,!!n){if(e==="submitting"){if(!t)return;n.record("abort_observed",{reason:"unspecified",evidenceBasis:"signal_reason"}),n.terminal("abort",{reason:"unspecified",evidenceBasis:"signal_reason"});return}t&&n.terminal("status_poll",{evidenceBasis:"server_status"}),e==="complete"&&n.reconcile("succeeded"),e==="decline"&&n.reconcile("declined")}}hideActionRequiredOverlay(){if(this.actionChallengeIntentId=null,this.actionChallenge){let t=this.actionChallenge;this.actionChallenge=null;try{t.detach()}catch{}t.telemetry.record("teardown")}if(this.actionOverlayTimer&&(clearTimeout(this.actionOverlayTimer),this.actionOverlayTimer=null),this.threeDsReturnHandler&&(window.removeEventListener("message",this.threeDsReturnHandler),this.threeDsReturnHandler=null),!this.actionOverlay)return;this.actionOverlay.parentNode?.removeChild(this.actionOverlay),this.actionOverlay=null;let e=this.actionOverlayPreviousFocus;this.actionOverlayPreviousFocus=null,e?.isConnected&&e.focus()}applyHeight(e){let t=this.container?.querySelector("iframe");if(!t)return;let n=Math.max(0,Math.min(Math.ceil(e),2e3));t.style.height=`${n}px`}};function wt(r,e){let t=X;return new t(r,{reporter:e})}var At=Symbol.for("@flopay/js.telemetry.bridge.v1");function kt(r,e,t){let n=()=>e?.now()??t();Object.defineProperty(r,At,{configurable:!1,enumerable:!1,writable:!1,value:{error:o=>e?.error(o),log:o=>e?.log(o),performance:o=>e?.performance(o),terminal:o=>e?.terminal(o),now:n,elapsed:o=>Math.max(0,n()-o),setCheckoutContext:o=>e?.setCheckoutContext(o),beginCheckout:(o={})=>e?.beginCheckout(o)??n(),disable:()=>e?.disable(),subscribe:o=>e?.subscribe(o)??(()=>{}),flush:()=>e?.flush()??Promise.resolve()}})}function Et(r){return r[At]}var ye=class{now(){return this.telemetryReporter?.now?.()??E()}constructor(e,t,n){this.provider=e,this.config=t,this.telemetryReporter=n??new A({billingApiUrl:(0,M.resolveBillingApiUrl)(t.billingApiUrl),sdkVersion:M.SDK_VERSION,enabled:t.telemetry!==!1}),kt(this,this.telemetryReporter,E)}cardCapture(e){return this.telemetryReporter?.log({name:"vault.capture.requested",stage:"vault_request",provider:"pcivault",paymentMethodCategory:"card"}),this.telemetryReporter?wt({sessionId:e?.sessionId,captureMethod:e?.captureMethod,sessionToken:e?.sessionToken,billingApiUrl:this.config.billingApiUrl,cardFieldsTimeoutMs:e?.cardFieldsTimeoutMs},this.telemetryReporter):new X({sessionId:e?.sessionId,captureMethod:e?.captureMethod,sessionToken:e?.sessionToken,billingApiUrl:this.config.billingApiUrl,cardFieldsTimeoutMs:e?.cardFieldsTimeoutMs,telemetry:!1})}async retrieveSession(e,t){if(!e)throw new M.FloPayError("sessionId is required to retrieve a session.","validation_error",{param:"sessionId"});let n=await this.retrieveUnifiedSession(e,t);if(!n.data.session)throw new M.FloPayError("Session not found","api_error");return n.data.session}async retrieveUnifiedSession(e,t){if(!e)throw new M.FloPayError("sessionId is required.","validation_error",{param:"sessionId"});let n=(0,M.resolveBillingApiUrl)(t??this.config.billingApiUrl),i=this.now();this.telemetryReporter?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let o,s,a=c=>{if(o===void 0)return;let u=o,h=s;o=void 0,s=void 0,this.telemetryReporter?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:c,attempt:h}),this.telemetryReporter?.performance({stage:"session_first_byte",durationMs:u,durationMode:"machine",requestCategory:"session_read",statusClass:c,attempt:h})},l=bt(n,{now:()=>this.telemetryReporter?.now()??E(),onFirstByte:(c,u)=>{o=c,s=u},onRetry:(c,u)=>{this.telemetryReporter?.log({name:"operation.retry",stage:c==="session_read"?"session_read":"processing",requestCategory:c,attempt:u})}});try{let c=await l.getUnifiedCheckoutSession(e);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"}),c}catch(c){let u=(0,M.classifyTelemetryFailure)(c,c instanceof M.FloPayError&&c.code==="checkout_processing_timeout"?"REQUEST_TIMEOUT":"NETWORK_REQUEST_FAILED");throw a(u.statusClass),this.telemetryReporter?.error({...u,stage:"session_read",provider:"flo",paymentMethodCategory:"unknown"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-i,durationMode:"machine",requestCategory:"session_read",statusClass:u.statusClass}),c}}getRawProvider(){return this.provider.getRawProvider()}destroy(){this.telemetryReporter?.log({name:"checkout.unmount",stage:"unmount"}),this.telemetryReporter?.destroy(),this.provider.destroy()}};function Mt(r,e,t){let n=ye;return new n(r,e,t)}var B=require("@flopay/shared");var He=require("@flopay/shared"),It=require("@stripe/stripe-js"),oe=require("@flopay/shared"),Pt=new WeakSet;function Dt(r){return r instanceof He.FloPayError&&Pt.has(r)}var ie=class{constructor(){this.name="stripe";this.stripe=null}async initialize(e){if(typeof window>"u")return;let t=await(0,It.loadStripe)(e.publishableKey,{locale:e.locale??"auto"});if(!t){let n=new He.FloPayError("Failed to initialize Stripe. Check your publishable key.","authentication_error");throw Pt.add(n),n}this.stripe=t}getRawProvider(){return this.stripe}destroy(){this.stripe=null}};var Ft=new Map;function Ke(r){return Array.isArray(r)?r.map(Ke):r&&typeof r=="object"?Object.fromEntries(Object.entries(r).filter(([,e])=>e!==void 0).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,Ke(t)])):r}function hn(r,e){return JSON.stringify([r,(0,B.resolveBillingApiUrl)(e?.billingApiUrl),e?.telemetry!==!1,e?.locale??"auto",e?.apiVersion??null,Ke(e?.appearance??null)])}var Fe=new Map;async function xt(r,e){if(!r){let a=new A({billingApiUrl:(0,B.resolveBillingApiUrl)(e?.billingApiUrl),sdkVersion:B.SDK_VERSION,enabled:e?.telemetry!==!1});throw a.error({errorCode:"CONFIGURATION_INVALID",stage:"sdk_initialize",paymentMethodCategory:"unknown"}),a.flush().catch(()=>{}).finally(()=>a.destroy()),new B.FloPayError("A publishable key is required to initialize FloPay.","validation_error",{param:"publishableKey"})}let t=hn(r,e),n=Ft.get(t);if(n)return e?.telemetry!==!1&&Et(n)?.log({name:"sdk.cache.hit",stage:"sdk_initialize"}),n;let i=Fe.get(t);if(i)return i;let o={...e,publishableKey:r},s=(async()=>{let a=new A({billingApiUrl:(0,B.resolveBillingApiUrl)(o.billingApiUrl),sdkVersion:B.SDK_VERSION,enabled:o.telemetry!==!1}),l=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 c=new ie,u=a.now();try{await c.initialize(o)}catch(y){throw a.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:Dt(y)?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"unknown"}),a.destroy(),y}let h=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:h-l,durationMode:"machine",provider:"stripe"}),a.performance({stage:"provider_ready",durationMs:h-u,durationMode:"machine",provider:"stripe"});let p=Mt(c,o,a);return Ft.set(t,p),p})();Fe.set(t,s);try{return await s}finally{Fe.get(t)===s&&Fe.delete(t)}}var $=require("@flopay/shared");var yn=4,gn=1e3,fn=1e3,Cn=15e3;function vn(r){let e=!!r?.gateways?.stripe,t=!!r?.gateways?.worldpayCorporateGateway;return e===t?"unknown":e?"stripe":"worldpay"}function Ut(r,e,t){try{return typeof r?.beginThreeDsChallenge!="function"?void 0:r.beginThreeDsChallenge(e,{provider:vn(t)})}catch{return}}function ge(r){return new $.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:r})}function Lt(){return new $.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function qt(r){return r.replace(/\/+$/,"")}function Tn(r){return r.status==="succeeded"||r.status==="authorized"||r.status==="declined"}function bn(r){if(!r||typeof r!="object")return{status:"unknown"};let e=typeof r.status=="string"?r.status:"unknown",t=typeof r.providerIntentId=="string"?r.providerIntentId:null;switch(e){case"succeeded":case"authorized":case"pending":case"timeout":return{status:e,providerIntentId:t};case"declined":return{status:"declined",providerIntentId:t,declineReason:typeof r.declineReason=="string"?r.declineReason:null,gatewayDeclineReason:typeof r.gatewayDeclineReason=="string"?r.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:t,nextActionRedirectUrl:typeof r.nextActionRedirectUrl=="string"?r.nextActionRedirectUrl:null};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}async function $e(r){if(typeof document>"u"||typeof window>"u")throw new $.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});let e=de(r.telemetry);e.record("handoff_planned");let t=ue(r.nextActionRedirectUrl);t==="missing"?e.record("action_missing",{reason:"missing_url"}):t==="invalid"&&e.record("action_invalid",{reason:"invalid_url"});let n=m=>{let g=Je(m);if(g==="buyer_cancel"){e.record("cancel_requested",{reason:g,evidenceBasis:"signal_reason"}),e.terminal("cancel",{reason:g,evidenceBasis:"signal_reason"});return}e.record("abort_observed",{reason:g,evidenceBasis:"signal_reason"}),e.terminal("abort",{reason:g,evidenceBasis:"signal_reason"})},i=m=>{(m.status==="succeeded"||m.status==="authorized"||m.status==="declined"||m.status==="timeout")&&e.reconcile(m.status)};if(r.signal?.aborted)throw n(r.signal.reason),ge();let o=`${qt(r.billingApiUrl)}/v1/checkouts/sessions/${encodeURIComponent(r.sessionId)}/3ds/complete`,s=async()=>{let m=new AbortController,g=()=>m.abort();r.signal?.aborted?m.abort():r.signal?.addEventListener("abort",g);let v=window.setTimeout(()=>m.abort(),Cn);try{let f=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":r.nonce,"content-type":"application/json",...e.attemptId?{"x-flopay-challenge-attempt":e.attemptId}:{}},body:"{}",signal:m.signal});if(!f.ok)return{status:"unknown"};let S=await f.json().catch(()=>null),C=bn(S);return i(C),C}catch{return{status:"unknown"}}finally{window.clearTimeout(v),r.signal?.removeEventListener("abort",g)}},a,l=()=>r.pollCompletionEndpoint!==!1?s():(a??(a=s()),a),c=document.activeElement instanceof HTMLElement?document.activeElement:null,u=document.createElement("div");u.setAttribute("data-flopay-auto-3ds-overlay","1"),u.setAttribute("role","dialog"),u.setAttribute("aria-modal","true"),u.setAttribute("aria-label","Card authentication"),u.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 h=document.createElement("iframe");h.setAttribute("title","Card authentication"),h.setAttribute("allow","payment"),h.tabIndex=0,h.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 p=null;try{p=new URL(r.billingApiUrl,window.location.href).origin}catch{p=null}let y=Se(r.nextActionRedirectUrl);try{let m=await new Promise((g,v)=>{let f=!1,S=0,C=0,F=0,G=!1,V=!1,x=!1,I=0,w=()=>{window.clearTimeout(S),window.clearInterval(C),window.clearTimeout(F),window.removeEventListener("message",P),window.removeEventListener("pagehide",se),document.removeEventListener("securitypolicyviolation",U),h.removeEventListener("load",Y),r.signal?.removeEventListener("abort",ae)},Z=async()=>{if(!(f||G)){G=!0;try{let R=await l();if(f||!Tn(R))return;f=!0,w(),e.terminal("status_poll",{evidenceBasis:"server_status"}),g(R)}finally{G=!1}}},se=()=>{e.record("pagehide_observed",{evidenceBasis:"page_lifecycle_event"})},U=R=>{if(x)return;let b=_e(R,y);b&&(x=!0,e.record("policy_violation",{reason:b,evidenceBasis:"parent_csp_event"}))},Y=()=>{V||(V=!0,e.record("iframe_load",{evidenceBasis:"iframe_load_event"})),r.pollCompletionEndpoint!==!1&&(window.clearTimeout(F),F=window.setTimeout(()=>{Z()},250))},ae=()=>{f||(f=!0,w(),n(r.signal?.reason),v(ge()))},z=R=>{f||I>=yn||(I+=1,e.record("return_rejected",{reason:R,evidenceBasis:"message_origin_check"}))},P=R=>{let b=R.data,j=!!b&&typeof b=="object"&&b.source==="flopay-vault-3ds-return";if(R.source!==h.contentWindow){j&&z("untrusted_source");return}if(p&&R.origin!==p){j&&z("untrusted_origin");return}j&&(f||(f=!0,w(),e.record("trusted_return",{evidenceBasis:"message_origin_check"}),e.terminal("trusted_return",{evidenceBasis:"message_origin_check"}),g(null)))};S=window.setTimeout(()=>{f||(f=!0,w(),V||e.record("load_unconfirmed",{evidenceBasis:"no_load_signal"}),e.record("timer_expired",{reason:"window_elapsed",evidenceBasis:"timer"}),e.terminal("timer",{reason:"window_elapsed",evidenceBasis:"timer"}),v(Lt()))},$.THREE_DS_CHALLENGE_WINDOW_MS),r.pollCompletionEndpoint!==!1&&(C=window.setInterval(()=>{Z()},fn)),h.addEventListener("load",Y),window.addEventListener("message",P),window.addEventListener("pagehide",se),document.addEventListener("securitypolicyviolation",U),r.signal?.addEventListener("abort",ae),h.src=r.nextActionRedirectUrl,e.record("render_attempted");try{u.appendChild(h),document.body.appendChild(u)}catch(R){throw f=!0,w(),e.record("render_failed"),R}e.record("container_attached"),e.record("navigation_assigned");let ee=be(u);ee&&e.record("container_visibility",{reason:ee,evidenceBasis:"parent_computed_style"}),h.focus(),r.signal?.aborted&&ae()});return m||await l()}finally{u.parentNode?.removeChild(u),e.record("teardown"),c?.isConnected&&c.focus()}}function Ot(r,e){try{let t=e.data.session?.status;t==="complete"?r.reconcile("succeeded"):t==="authorized"&&r.reconcile("authorized")}catch{}}function _n(r){return new $.FloPayError("Card was declined.","api_error",{code:r.declineReason??"authorization_declined",...r.gatewayDeclineReason?{declineCode:r.gatewayDeclineReason}:{}})}async function Nt(r,e){let t=`${qt(r.billingApiUrl)}/v1/checkouts/sessions/${encodeURIComponent(r.sessionId)}/status`,n=new AbortController,i=new AbortController,o=()=>{n.abort(r.signal?.reason),i.abort(r.signal?.reason)};r.signal?.aborted?o():r.signal?.addEventListener("abort",o,{once:!0});let s=de(r.telemetry),a=$e({billingApiUrl:r.billingApiUrl,sessionId:r.sessionId,nonce:r.nonce,nextActionRedirectUrl:r.nextActionRedirectUrl,signal:n.signal,pollCompletionEndpoint:!1,...r.telemetry?{telemetry:r.telemetry}:{}}),l=e.waitForCheckoutSessionCompletion(r.sessionId,{initialDelayMs:gn,nonce:r.nonce,statusUrl:t,continueAfterActionRequired:!0,timeoutMs:$.THREE_DS_CHALLENGE_WINDOW_MS+15e3,signal:i.signal,...s.attemptId?{challengeAttemptId:s.attemptId}:{}});l.catch(()=>{}),a.catch(()=>{});try{let c=await Promise.race([a,l]);if("data"in c)return s.terminal("status_poll",{evidenceBasis:"server_status"}),Ot(s,c),c;if(c.status==="declined")throw(r.createDeclineError??_n)(c);if(c.status==="timeout")throw Lt();let u=await l;return Ot(s,u),u}catch(c){throw r.signal?.aborted||c instanceof Error&&c.name==="AbortError"?ge(c):c}finally{r.signal?.removeEventListener("abort",o),n.abort(),i.abort()}}0&&(module.exports={FloPay,PaymentAPI,PciVaultCardCapture,SESSION_CREATE_TELEMETRY,StripeAdapter,beginSavedCardChallengeTelemetry,cacheSessionDisplayData,clearSessionDisplayData,completeSavedCardNextAction,createCheckoutSession,createCheckoutSessionWithRetries,createSavedCardActionAbortedError,dropThirdPartyOnlyError,getSessionDisplayData,loadCheckoutRuntime,loadFloPay,runSavedCardChallenge,toStripeAppearance,toStripeAppearanceTheme});
|
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, CheckoutRuntimeEvent, CheckoutRuntimeEventName, CheckoutRuntimeHandle, CheckoutRuntimeMountOptions, CheckoutRuntimeUpdateOptions, } from './checkout-runtime/contract.js';
|
|
3
|
+
export type { CheckoutRuntime, CheckoutRuntimeAutomaticPayment, CheckoutRuntimeEvent, CheckoutRuntimeEventName, CheckoutRuntimeHandle, CheckoutRuntimeLayout, CheckoutRuntimeMountOptions, 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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@flopay/js",
|
|
3
|
-
"version": "1.20.
|
|
3
|
+
"version": "1.20.8",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"sideEffects": false,
|
|
6
6
|
"publishConfig": {
|
|
@@ -31,7 +31,7 @@
|
|
|
31
31
|
"dist"
|
|
32
32
|
],
|
|
33
33
|
"dependencies": {
|
|
34
|
-
"@flopay/shared": "1.20.
|
|
34
|
+
"@flopay/shared": "1.20.8",
|
|
35
35
|
"@stripe/stripe-js": "^10.3.0"
|
|
36
36
|
},
|
|
37
37
|
"devDependencies": {
|