@flopay/js 1.18.0 → 1.18.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/card-setup.cjs +1 -1
- package/dist/card-setup.mjs +1 -1
- package/dist/chunk-GJQVTUPW.mjs +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +2 -2
- package/dist/chunk-WTVYMDK5.mjs +0 -1
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var Fe=Object.defineProperty;var xt=Object.getOwnPropertyDescriptor;var Ot=Object.getOwnPropertyNames;var Ut=Object.prototype.hasOwnProperty;var qt=(r,e)=>{for(var t in e)Fe(r,t,{get:e[t],enumerable:!0})},Lt=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ot(e))!Ut.call(r,o)&&o!==t&&Fe(r,o,{get:()=>e[o],enumerable:!(n=xt(e,o))||n.enumerable});return r};var Nt=r=>Lt(Fe({},"__esModule",{value:!0}),r);var on={};qt(on,{FloPay:()=>ye,PaymentAPI:()=>pe,PciVaultCardCapture:()=>Q,SESSION_CREATE_TELEMETRY:()=>Ne,StripeAdapter:()=>ne,beginSavedCardChallengeTelemetry:()=>Mt,cacheSessionDisplayData:()=>Y,clearSessionDisplayData:()=>Te,completeSavedCardNextAction:()=>Dt,createCheckoutSession:()=>Ze,createCheckoutSessionWithRetries:()=>nt,createSavedCardActionAbortedError:()=>ge,dropThirdPartyOnlyError:()=>Ft.dropThirdPartyOnlyError,getSessionDisplayData:()=>ve,loadFloPay:()=>kt,runSavedCardChallenge:()=>je,toStripeAppearance:()=>oe.toStripeAppearance,toStripeAppearanceTheme:()=>oe.toStripeAppearanceTheme});module.exports=Nt(on);var Ft=require("@flopay/shared");var T=require("@flopay/shared");function ae(r){return typeof r=="string"&&r.trim()?r:void 0}function le(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 U(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 Bt(){return Object.assign(new Error("The operation was aborted."),{name:"AbortError"})}function ee(r,e){let t=150*2**r,n=Math.round(t*(.75+Math.random()*.5));return new Promise((o,i)=>{let s,a=()=>e.removeEventListener("abort",c),c=()=>{s!==void 0&&clearTimeout(s),a(),i(Bt())};if(e.aborted){c();return}s=setTimeout(()=>{a(),o()},n),e.addEventListener("abort",c,{once:!0})})}var Vt="flopay_session_display:";var fe=new Map;function Ce(r){return`${Vt}${r}`}function xe(){if(typeof window>"u")return null;try{return window.sessionStorage}catch{return null}}function Y(r,e,t){if(!r)return;let n=t?.ttlMs??36e5,o={data:e,expiresAt:Date.now()+n},i=xe();if(i)try{i.setItem(Ce(r),JSON.stringify(o));return}catch{}fe.set(r,o)}function ve(r){if(!r)return null;let e=xe();if(e)try{let n=e.getItem(Ce(r));if(n){let o=JSON.parse(n);if(o&&typeof o.expiresAt=="number"&&o.expiresAt>Date.now())return o.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=xe();if(e)try{e.removeItem(Ce(r))}catch{}}var k=require("@flopay/shared");var Oe=require("@flopay/shared"),zt=32,He=Symbol.for("@flopay/js.three-ds-challenge.attempts.v1");function jt(){let r=globalThis,e=r[He];if(e instanceof Map)return e;let t=new Map;try{Object.defineProperty(r,He,{configurable:!0,enumerable:!1,writable:!1,value:t})}catch{}return t}function Ht(r,e){let t=jt(),n=t.get(r);if(n)return n;for(;t.size>=zt;){let i=t.keys().next();if(i.done)break;t.delete(i.value)}let o={nextSequence:0,startedAt:e,terminated:!1,reconciled:new Set,provider:"unknown"};return t.set(r,o),o}var Kt=new Set(["pagehide_observed","cancel_requested","abort_observed","browser_terminal"]),$t=new Set(["teardown","recovery_read_completed","provider_reconciled"]);function Ke(r,e={}){let t=(0,Oe.isThreeDsChallengeAttemptId)(e.attemptId)?e.attemptId.toLowerCase():r.newAttemptId(),n=()=>{try{let a=r.now();return Number.isFinite(a)?a:0}catch{return 0}},o=Ht(t,n());(e.provider==="stripe"||e.provider==="worldpay")&&(o.provider=e.provider);let i=o.provider,s=(a,c)=>{if(o.terminated&&!$t.has(a))return;let l={attemptId:t,phase:a,attemptSequence:o.nextSequence,elapsedMs:Math.max(0,n()-o.startedAt),provider:i};o.nextSequence+=1,c.reason!==void 0&&(l.reason=c.reason),c.evidenceBasis!==void 0&&(l.evidenceBasis=c.evidenceBasis),c.terminalSource!==void 0&&(l.terminalSource=c.terminalSource),c.providerOutcome!==void 0&&(l.providerOutcome=c.providerOutcome);try{r.emit(l,Kt.has(a))}catch{}};return{attemptId:t,record(a,c={}){a==="browser_terminal"||a==="provider_reconciled"||s(a,{reason:c.reason,evidenceBasis:c.evidenceBasis})},terminal(a,c={}){o.terminated||(s("browser_terminal",{terminalSource:a,reason:c.reason,evidenceBasis:c.evidenceBasis}),o.terminated=!0)},reconcile(a){o.reconciled.has(a)||(o.reconciled.add(a),s("provider_reconciled",{providerOutcome:a,evidenceBasis:"provider_fact"}))}}}function ce(r){let e=null;try{e=(0,Oe.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 de(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 $e(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],o=null;return n==="frame-src"&&(o="frame_src"),n==="child-src"&&(o="child_src"),!o||typeof t.blockedURI!="string"?null:new URL(t.blockedURI).origin===e?o:null}catch{return null}}function Se(r){try{return de(r)==="valid"?new URL(r).origin:null}catch{return null}}var Gt="/v1/sdk-telemetry/events",we=16,Ge=64,Yt=1500,Ye=1e3,Wt=64,Jt="00000000-0000-4000-8000-000000000000",Qt={technical_error:8,lifecycle:32,expected_outcome:32,performance:24},Xt=48;function j(){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 Zt(r){try{return new TextEncoder().encode(r).byteLength}catch{return r.length}}function er(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(/\/+$/,"")}${Gt}`,this.sdkPackage=e.sdkPackage??"@flopay/js",this.sdkVersion=e.sdkVersion,this.correlationId=j(),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:j(),sequence:this.sequence++}))}error(e){if(this.notify({...e,class:"technical_error"}),!this.canCollect())return;let t=(0,k.buildTelemetryErrorEvent)({...this.checkoutContext,...e,eventId:Jt,sequence:0}),n=er(t),o=this.now();this.pruneReportedFailures(o);let i=this.reportedFailures.get(n);if(i!==void 0&&o>=i&&o-i<Ye){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,o),this.enqueue((0,k.buildTelemetryErrorEvent)({...this.checkoutContext,...e,eventId:j(),sequence:this.sequence++}))}performance(e){this.canCollect()&&this.enqueue((0,k.buildTelemetryPerformanceEvent)({...this.checkoutContext,...e,eventId:j(),sequence:this.sequence++}))}terminal(e){if(this.canCollect()&&(this.enqueue((0,k.buildTelemetryTerminalEvent)({...this.checkoutContext,...e,eventId:j(),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 Ke({now:()=>this.now(),newAttemptId:j,emit:(t,n)=>this.recordThreeDsChallenge(t,n)},e)}recordThreeDsChallenge(e,t){if(!this.canCollect()||this.threeDsChallengeCount>=Xt)return;let n=(0,k.buildTelemetryLogEvent)({...this.checkoutContext,...e,name:"three_ds.challenge",stage:"three_ds_handoff",eventId:j(),sequence:this.sequence++});if(!(this.queue.length>=Ge)){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>=Ye)&&this.reportedFailures.delete(t)}rememberReportedFailure(e,t){for(;this.reportedFailures.size>=Wt;){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>=Ge||this.eventCounts[e.class]>=Qt[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:j()});if(Zt(t)>k.TELEMETRY_MAX_BATCH_BYTES)return;let n=typeof AbortController>"u"?null:new AbortController,o=null;try{let i=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 c=>{if(c.status!==202)return null;let l=null;try{l=await c.json()}catch{}return l?.status==="disabled"?"disabled":null}).catch(()=>null),s=new Promise(c=>{o=setTimeout(()=>{n?.abort(),c(null)},Yt)});await Promise.race([i,s])==="disabled"&&this.disableFromIngestion()}catch{}finally{o&&clearTimeout(o)}}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)}},We=Symbol.for("@flopay/js.telemetry.reporter-factory.v1"),Je=globalThis;Je[We]===void 0&&Object.defineProperty(Je,We,{configurable:!0,enumerable:!1,writable:!1,value:r=>new A(r)});var Ue=5,Qe=new WeakSet;function tr(r){(typeof r=="object"&&r!==null||typeof r=="function")&&Qe.add(r)}function rr(r){return(typeof r=="object"&&r!==null||typeof r=="function")&&Qe.has(r)}function nr(r,e){let t=e?.error,n=ae(e?.code)??ae(t?.code)??`http_${r}`,o=le(e?.message)??le(t?.message)??or(n,r);return new T.FloPayError(o,"api_error",{code:n,statusCode:r})}function or(r,e){switch(r){case"CouponLimitExceeded":return`Too many coupon codes \u2014 a checkout session accepts at most ${Ue}.`;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 Xe(r,e,t){let{billingApiUrl:n,checkoutBaseUrl:o,items:i=[],subscriptions:s=[],products:a,account:c,successUrl:l,cancelUrl:u,checkoutMode:h="confirm",captureMethod:m,couponCodes:f=[],checkoutMetadata:p,tagsData:y,redirectParams:v={},setCookie:C=!0,clientId:_,currency:g,utmMetadata:F,idempotencyKey:$}=r,B=(0,T.resolveIdempotencyKey)($);if(f.length>Ue)throw new T.FloPayError(`Too many coupon codes \u2014 a checkout session accepts at most ${Ue}.`,"validation_error",{code:"CouponLimitExceeded",param:"couponCodes"});let x=a??(0,T.foldIntoProducts)(i,s);(0,T.assertCaptureMethodEligible)({captureMethod:m,products:x});let I=(0,T.resolveSessionCurrency)(g,i,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:_,checkoutVersion:T.SDK_VERSION,successUrl:l,cancelUrl:u,currency:I,checkoutMode:h,products:x.map(P=>(0,T.buildProductPayload)(P,I)),accountData:{userId:c.userId,firstName:c.firstName??null,lastName:c.lastName??null,email:c.email,country:c.country??null,gender:c.gender??null,city:c.city??null,state:c.state??null,zip:c.zip??null,addressLine1:c.addressLine1??null,addressLine2:c.addressLine2??null},couponCodes:f};m==="manual"&&(R.captureMethod=m),p!==void 0&&(R.checkoutMetadata=p),y&&(R.tagsData=y),F&&F.length>0&&(R.utmMetadata=F);let X=`${n.replace(/\/+$/,"")}/v1/checkouts/sessions`,ie={"Content-Type":"application/json"};B&&(ie[T.IDEMPOTENCY_KEY_HEADER]=B);let O,G,se={method:"POST",headers:ie,body:JSON.stringify(R),signal:e},V;try{t?.startAttempt(),V=await fetch(X,se)}catch(P){throw tr(P),P}try{t?.record(V.status)}catch{}O=V.status;try{G=await V.json()}catch{}if(O>=400)throw(0,T.withTelemetryHttpDiagnostics)(nr(O,G),V);if(O===201){let P=G?.data?.uuid,Z=G?.data?.nonce;if(!P)throw new Error("Checkout session created but no UUID was returned by the billing API");if(!Z)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)&&Y(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(`${o.replace(/\/+$/,"")}/secure`);w.searchParams.set("id",P);for(let[b,z]of Object.entries(v))w.searchParams.set(b,z);if(C&&typeof window<"u"&&typeof document<"u"){let b=JSON.stringify({origin_url:u}),z=window.location.hostname.split(".").slice(-2).join(".");document.cookie=`checkout_data=${encodeURIComponent(b)}; domain=.${z}; path=/; max-age=3600; SameSite=Lax; Secure;`,document.cookie=`flopay_checkout_token=${encodeURIComponent(Z)}; domain=.${z}; path=/; max-age=3600; SameSite=Lax; Secure;`}return typeof window<"u"&&(window.location.href=w.toString()),{status:201,redirectUrl:w.toString(),nonce:Z}}return O===204?(typeof window<"u"&&(window.location.href=l),{status:204}):{status:O}}async function Ze(r){let e=tt(r),t=et(e),n=U(r.timeoutMs);try{let o=await Xe(r,n.signal,t);return t.commit(),rt(e,o),o}catch(o){throw t.commit(),Re(e,o),o}finally{n.clear(),te(e.reporter)}}function et(r){let e=!1,t=r.startedAt,n;return{startAttempt(){t=r.reporter.now()},record(o){n={status:o,durationMs:Math.max(0,r.reporter.now()-t),attempt:r.attempt}},commit(){if(e||!n)return;e=!0;let o=(0,T.telemetryStatusClass)(n.status);r.reporter.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:o,attempt:n.attempt}),r.reporter.performance({stage:"session_first_byte",durationMs:n.durationMs,durationMode:"machine",requestCategory:"session_create",statusClass:o,attempt:n.attempt})}}}function tt(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 rt(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 te(r){r.flush().catch(()=>{}).finally(()=>r.destroy())}async function nt(r){let{maxRetries:e=2,...t}=r,n=tt(r),o=et(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"}),te(n.reporter),new Error(`Number of retries must be an integer between 0 and ${2}`);let i={...t,idempotencyKey:(0,T.resolveIdempotencyKey)(t.idempotencyKey)},s=U(t.timeoutMs),a;for(let c=0;c<=e;c++){n.attempt=c;try{let l=await Xe(i,s.signal,o);return o.commit(),rt(n,l),s.clear(),te(n.reporter),l}catch(l){a=l;let u=l instanceof Error&&l.name==="AbortError",h=rr(l),m=l instanceof T.FloPayError&&l.code===T.IDEMPOTENCY_IN_PROGRESS_CODE;if((u||h||m)&&!s.signal.aborted&&c<e){n.reporter.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:c+1});try{await ee(c,s.signal)}catch(f){throw o.commit(),Re(n,f),s.clear(),te(n.reporter),f}continue}throw o.commit(),Re(n,l),s.clear(),te(n.reporter),l}}throw o.commit(),Re(n,a),s.clear(),te(n.reporter),a??new Error("Unknown error during checkout session creation")}var M=require("@flopay/shared");var d=require("@flopay/shared");function ir(r){return r==="on_session"||r==="off_session"}function sr(r){if(!r||typeof r!="object")return!1;let e=r;return typeof e.paymentMethodType=="string"&&typeof e.reason=="string"}function ar(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 lr="x-flopay-process-result-source",cr="status",ut=new WeakSet;function dr(r,e){let t=new d.FloPayError(r,"api_error",{code:e,statusCode:500});return ut.add(t),t}function ur(r){return typeof r=="object"&&r!==null&&ut.has(r)}function ot(r){return r?.result==="DECLINE"||r?.result==="ERROR"}var mr=50,W=new Map;function pr(r,e){return W.get(r)?.has(e)===!0}function hr(r,e){let t=W.get(r)??new Set;if(t.add(e),W.delete(r),W.set(r,t),W.size>mr){let n=W.keys().next().value;n!==void 0&&W.delete(n)}}function yr(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 it=0,st=500,Ae=15e3,at=15e3,gr=3e3,fr=1e4,Cr=1e4;function me(r){return typeof r=="object"&&r!==null}function H(r,e){return ae(r?.[e])}function lt(r,e){return le(r?.[e])}function vr(r,e){let t=r?.[e];return typeof t=="number"&&Number.isFinite(t)?t:void 0}function Le(r,e){return e?new Promise((t,n)=>{let o=()=>{clearTimeout(i),n(e.reason??Object.assign(new Error("The operation was aborted."),{name:"AbortError"}))},i=setTimeout(()=>{e.removeEventListener("abort",o),t()},r);e.aborted?o():e.addEventListener("abort",o,{once:!0})}):new Promise(t=>setTimeout(t,r))}function qe(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 L(r,e){let t=await r.json().catch(()=>null),n=me(t?.error)?t.error:null,o=lt(t,"message")??lt(n,"message")??e,i=H(t,"code")??H(t,"gatewayErrorCode")??H(n,"code")??`http_${r.status}`;return(0,d.withTelemetryHttpDiagnostics)(new d.FloPayError(o,"api_error",{code:i,statusCode:r.status}),r)}async function Tr(r){if(r.status!==403)return!1;let e=await r.clone().json().catch(()=>null),t=me(e?.error)?e.error:null;return(H(e,"code")??H(t,"code"))==="verification_required"}function br(r){if(!(!me(r)||typeof r.required!="boolean"))return{required:r.required,provider:"turnstile"}}async function _r(r){let e=r.status===400?await r.clone().json().catch(()=>null):null;return(0,d.classifyPaymentRejection)(r.status,e)}function ct(r){return r===400||r===422}var Ee=2;async function ke(r,e,t=Ee,n,o){let i;for(let s=0;;s++)try{return o?.(s),await fetch(r,e)}catch(a){if(e?.signal?.aborted||a instanceof Error&&a.name==="AbortError")throw a;if(i=a,s>=t)throw i;try{n?.(s+1)}catch{}await Le(150*2**s,e?.signal??void 0)}}var Ne=Symbol.for("@flopay/js.session-create.telemetry.v1");function Sr(r){return r[Ne]}function wr(r){return"now"in r||"onFirstByte"in r||"onSessionCreateFailure"in r||"onRetry"in r}function mt(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 pt(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 Rr(r,e){let t={clientId:r.clientId,checkoutVersion:d.SDK_VERSION,successUrl:r.successUrl,cancelUrl:r.cancelUrl,currency:e,checkoutMode:"full",deferDataAttachment:!0};return r.captureMethod==="manual"&&(t.captureMethod=r.captureMethod),r.account.country&&(t.accountData={country:r.account.country}),pt(t,r),t}function dt(r,e,t){return{currency:e,products:t.map(n=>(0,d.buildProductPayload)(n,e)),couponCodes:r.couponCodes??[],accountData:mt(r.account)}}function Ar(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,o]of Object.entries(r)){if(t&&n.endsWith("Name")||typeof o!="string")continue;let i=o.trim();i&&(e[n]=i)}return{accountData:e}}var J=class J{constructor(e,t={}){this.baseUrl=e.replace(/\/+$/,"");let n=wr(t);this.telemetryHooks=n?t:void 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,o,i="unknown"){let s=(0,d.classifyTelemetryFailure)(e,t);this.directTelemetry?.error({...s,...ur(e)?{reason:"capture_failed"}:{},stage:n,requestCategory:o,paymentMethodCategory:i})}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,o){this.beginDirectTelemetryCheckout(e);let i=this.telemetryTimestamp(),s=i,a=0;this.directTelemetry?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let c={[d.FLO_SDK_VERSION_HEADER]:d.SDK_VERSION};t&&(c["x-checkout-session-token"]=t);let l=!1;try{let u=await ke(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}`,{headers:c,signal:o},Ee,p=>{this.telemetryHooks?.onRetry?.("session_read",p),this.directTelemetry?.log({name:"operation.retry",stage:"session_read",requestCategory:"session_read",attempt:p})},p=>{a=p,s=this.telemetryTimestamp()});l=!0;let h=Math.max(0,this.telemetryTimestamp()-s);try{this.telemetryHooks?.onFirstByte?.(h,a)}catch{}let m=`${Math.floor(u.status/100)}xx`;if(this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:m,attempt:a}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:h,durationMode:"machine",requestCategory:"session_read",statusClass:m,attempt:a}),!u.ok)throw await L(u,"Failed to get checkout session");let f=await u.json();return this.directTelemetry?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:m}),this.directTelemetry?.performance({stage:"session_complete",durationMs:Math.max(0,this.telemetryTimestamp()-i),durationMode:"machine",requestCategory:"session_read",statusClass:m}),{...f,data:this.mergeCachedDisplayData(f.data)}}catch(u){throw l&&(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){Y(e,t,n)}clearSessionDisplayData(e){Te(e)}async getVaultCapture(e,t){let n=`${this.baseUrl}\0${e}\0${t??""}`,o=J.activeVaultCaptureRequests.get(n);if(o!==void 0)return o;let i=this.requestVaultCapture(e,t);J.activeVaultCaptureRequests.set(n,i);try{return await i}finally{J.activeVaultCaptureRequests.get(n)===i&&J.activeVaultCaptureRequests.delete(n)}}async requestVaultCapture(e,t){let n=new AbortController,o=setTimeout(()=>n.abort(),Cr);this.beginDirectTelemetryCheckout(e);let i=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},Ee,l=>{this.telemetryHooks?.onRetry?.("vault_capture",l),this.directTelemetry?.log({name:"operation.retry",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card",attempt:l})});if(await Tr(a))return this.directTelemetry?.performance({stage:"vault_request",durationMs:Math.max(0,this.telemetryTimestamp()-i),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"4xx"}),{verification:{required:!0,provider:"turnstile"}};if(!a.ok)throw await L(a,"Failed to load the secure card form");let c=await a.json();return this.directTelemetry?.performance({stage:"vault_request",durationMs:Math.max(0,this.telemetryTimestamp()-i),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"2xx"}),this.toVaultBlock(c)}catch(a){let c=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(c,"VAULT_LOAD_FAILED","vault_request","vault_capture","card"),c}finally{clearTimeout(o)}}async getUnifiedCheckoutSession(e,t){let n=await this.getCheckoutSession(e,t);return this.normalizeCheckoutSessionResponse(n)}async getUnifiedCheckoutSessionForRecovery(e,t,n){let o=await this.fetchCheckoutSession(e,t,!1,n);return this.normalizeCheckoutSessionResponse(o)}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 o=t.paymentMethodCategory??"unknown";if(!t.nonce)throw this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"process_payment",paymentMethodCategory:o}),new d.FloPayError("processPayment requires `nonce` \u2014 pass the value returned from session creation.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let i=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.processing.started",stage:"processing",requestCategory:"process_payment",paymentMethodCategory:o});let{nonce:s,paymentMethodCategory:a,...c}=t,l=yr(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(c)}),h=u}catch(m){if(qe(m))throw this.reportDirectFailure(m,"PAYMENT_PROCESSING_FAILED","processing","process_payment",o),m;u=await this.reconcileProcessPayment(t.sessionId,{...n,nonce:s,paymentMethodCategory:o,submittedIntentId:l})}if(!u.ok&&u.status!==202){let m=await _r(u);return m?this.directTelemetry?.terminal({outcome:m,stage:"processing",requestCategory:"process_payment",statusClass:"4xx",paymentMethodCategory:o}):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:o,...(0,d.readTelemetryHttpDiagnostics)(h)}),u}try{let m=await this.resolveProcessResponse(u,t.sessionId,{...n,nonce:s,paymentMethodCategory:o,submittedIntentId:l});return this.directTelemetry?.log({name:"payment.processing.completed",stage:"processing",requestCategory:"process_payment",statusClass:(0,d.telemetryStatusClass)(m.status),paymentMethodCategory:o}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-i),durationMode:"machine",requestCategory:"process_payment",statusClass:(0,d.telemetryStatusClass)(m.status),paymentMethodCategory:o}),m}catch(m){throw m instanceof d.FloPayError&&m.code==="checkout_processing_timeout"||this.reportDirectFailure(m,"PAYMENT_PROCESSING_FAILED","processing","process_payment",o),m}}async patchAccountSnapshot(e,t,n,o){this.beginDirectTelemetryCheckout(e);let i=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.state_transition",stage:"processing",requestCategory:"account_snapshot"});let s=o?.timeoutMs??fr,a=new AbortController,c=()=>a.abort();o?.signal&&(o.signal.aborted?a.abort():o.signal.addEventListener("abort",c,{once:!0}));let l=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},Ee,h=>{this.telemetryHooks?.onRetry?.("account_snapshot",h),this.directTelemetry?.log({name:"operation.retry",stage:"processing",requestCategory:"account_snapshot",attempt:h})})}finally{clearTimeout(l),o?.signal?.removeEventListener("abort",c)}if(!u.ok)throw await L(u,"Failed to persist account snapshot");this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-i),durationMode:"machine",requestCategory:"account_snapshot",statusClass:"2xx"})}catch(u){throw this.reportAccountSnapshotFailure(u,o?.telemetryMode??"blocking"),u}}async createSessionIntent(e,t,n,o){if(!t)throw new d.FloPayError("createSessionIntent requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let i=n,s=i.paymentMethodType,a=typeof s=="string"&&s.trim().toLowerCase()==="card",c=typeof s=="string"&&s.length>0&&!a&&(typeof i.paymentMethodId=="string"||i.paymentMethodId===null),l=i.provider==="stripe"&&(i.paymentMethodCategory==="wallet"||i.paymentMethodCategory==="apm")&&(i.intentKind==="payment"||i.intentKind==="setup"),u=i.provider==="paypal"&&i.paymentMethodCategory==="wallet"&&i.paymentMethodId===null&&(i.paymentMethodType==="paypal"&&i.intentKind==="payment"||i.paymentMethodType===d.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&(i.intentKind==="payment"||i.intentKind==="setup"));if(!c||!l&&!u)throw new d.FloPayError("Only wallet, APM, and PayPal session intents are supported.","validation_error",{code:"InvalidSessionIntentRequest"});let h=i.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 m=(0,d.isUuidV4)(h)?h:(0,d.randomUuidV4)();this.beginDirectTelemetryCheckout(e);let f=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.intent.started",stage:"processing",requestCategory:"intent_create"});let p={"Content-Type":"application/json","x-checkout-session-token":t,[d.IDEMPOTENCY_KEY_HEADER]:o?.idempotencyKey||m},y=!1;try{let v=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents`,{method:"POST",headers:p,body:JSON.stringify({...n,authorizationAttemptId:m}),signal:o?.signal});if(!v.ok){y=!0;let R=await L(v,"Failed to create checkout intent"),X=(0,d.classifyTelemetryFailure)(R,"PAYMENT_PROCESSING_FAILED");throw ct(R.statusCode)?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"intent_create",statusClass:"4xx"}):this.directTelemetry?.error({...X,stage:"processing",requestCategory:"intent_create"}),R}let C=await v.json();if(v.status===202&&me(C)&&C.type==="checkout_processing")return y=!0,await this.settleProcessingSessionIntent(C,v,e,t,n);let _=C.data;if(!_||typeof _!="object")throw new d.FloPayError("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});let g=_,F=g.paymentMethodType,$=(g.paymentMethodCategory==="wallet"||g.paymentMethodCategory==="apm")&&typeof F=="string"&&F.trim().toLowerCase()!=="card"&&(typeof g.paymentMethodId=="string"||g.paymentMethodId===null)&&typeof g.providerObjectId=="string",B=g.provider==="stripe"&&(g.intentKind==="payment"||g.intentKind==="setup")&&typeof g.clientSecret=="string",x=g.provider==="paypal"&&g.paymentMethodCategory==="wallet"&&g.paymentMethodId===null&&(g.paymentMethodType==="paypal"&&g.intentKind==="payment"&&(g.providerObjectType==="order"||g.providerObjectType==="subscription")||g.paymentMethodType===d.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&g.intentKind==="payment"&&g.providerObjectType==="order"||g.paymentMethodType===d.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&g.intentKind==="setup"&&g.providerObjectType==="setup_token")&&g.clientSecret===null,I=g.provider===n.provider&&g.paymentMethodCategory===n.paymentMethodCategory&&g.paymentMethodType===n.paymentMethodType&&g.paymentMethodId===n.paymentMethodId&&g.intentKind===n.intentKind;if(!$||!B&&!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()-f),durationMode:"machine",requestCategory:"intent_create",statusClass:(0,d.telemetryStatusClass)(v.status)}),g}catch(v){throw y||this.reportDirectFailure(v,"PAYMENT_PROCESSING_FAILED","processing","intent_create"),v}}async settleProcessingSessionIntent(e,t,n,o,i){let s=this.toCheckoutProcessingPending(e,t,n);try{return{settled:!0,response:await this.resolveCheckoutProcessing(s,n,{nonce:o,paymentMethodCategory:i.provider==="paypal"?"paypal":i.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}}async reportSessionIntentDecline(e,t,n,o){if(!t)throw new d.FloPayError("reportSessionIntentDecline requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let i=n,s=i.providerDeclineReason,a=i.paymentMethodType,c=i.providerIntentId,l=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"&&l,h=i.provider==="stripe"&&(i.paymentMethodCategory==="wallet"||i.paymentMethodCategory==="apm")&&(c===void 0||typeof c=="string"&&/^pi_[a-z0-9_]{1,252}$/i.test(c)),m=i.provider==="paypal"&&i.paymentMethodCategory==="wallet"&&i.paymentMethodType==="paypal"&&c===void 0;if(!u||!h&&!m)throw new d.FloPayError("Invalid non-card decline classification.","validation_error",{code:"InvalidSessionIntentDeclineRequest"});let f=m?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:s}:{provider:"stripe",paymentMethodCategory:i.paymentMethodCategory,paymentMethodType:i.paymentMethodType,providerDeclineReason:s,...typeof c=="string"?{providerIntentId:c}:{}},p=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(f),signal:o?.signal});if(!p.ok)throw await L(p,"Failed to report checkout decline")}async resolvePaymentMethodLayout(e,t,n,o){if(!t)throw new d.FloPayError("resolvePaymentMethodLayout requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let i=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:o?.signal});if(i.status===404||i.status===405)return null;if(!i.ok)throw await L(i,"Failed to resolve the payment method layout");let s=await i.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 o=t?.page??1,i=t?.limit??1,s=new URLSearchParams({email:e,page:String(o),limit:String(i),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 c=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"}),c}catch(a){throw this.reportDirectFailure(a,"RECOVERY_FAILED","recovery","other","saved"),a}}async createAndFetchSession(e){if((0,d.isDetachedSessionEligible)(e)){let i=e.account.email?.trim();if(i&&!(0,d.isValidEmail)(i))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=U(e.timeoutMs??12e3),o={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});try{let i=await this.createAndFetchSessionRequest(e,n.signal,o);return this.adoptDirectTelemetryCheckout(i.data.session?.id),this.directTelemetry?.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:o.statusClass}),this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:"session_create",statusClass:o.statusClass,attempt:o.attempt}),i}catch(i){throw this.reportSessionCreateFailure(i,t,o),i}finally{n.clear()}}async createAndFetchSessionRequest(e,t,n){let o=e.products??(0,d.foldIntoProducts)(e.items,e.subscriptions);(0,d.assertCaptureMethodEligible)({captureMethod:e.captureMethod,products:o});let i=(0,d.resolveSessionCurrency)(e.currency,e.items,e.subscriptions,o);if(!i)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:i,checkoutMode:e.checkoutMode??"full",products:o.map(l=>(0,d.buildProductPayload)(l,i)),accountData:mt(e.account),couponCodes:e.couponCodes??[]};e.captureMethod==="manual"&&(s.captureMethod=e.captureMethod),e.tokenizedData&&(s.tokenizedData=e.tokenizedData),pt(s,e);let a=await this.postCheckoutSessionCreate(s,e,t,n),c=!1;try{let l=await a.json();if(l.data&&"gateways"in l.data){this.autoCacheDisplayData(l.data.uuid,e);let m=this.mergeCachedDisplayData(l.data),f=this.normalizeRawSession(m);return l.vault&&f.data.session&&(f.data.session.vault=this.toVaultBlock(l.vault)),{...f,autoProcessingError:l.autoProcessingError,autoProcessingAttempted:l.autoProcessingAttempted,autoProcessingPending:l.autoProcessingPending}}let u=l.data?.uuid;if(!u)throw new d.FloPayError("No session ID returned","api_error",{code:"InvalidCheckoutSessionResponse"});return this.autoCacheDisplayData(u,e),this.adoptDirectTelemetryCheckout(u),c=!0,{...await this.getUnifiedCheckoutSession(u),autoProcessingError:l.autoProcessingError,autoProcessingAttempted:l.autoProcessingAttempted,autoProcessingPending:l.autoProcessingPending}}catch(l){throw c?l:(0,d.markSessionResponseReceived)(l)}}async postCheckoutSessionCreate(e,t,n,o){let i={"Content-Type":"application/json",[d.FLO_SDK_VERSION_HEADER]:d.SDK_VERSION},s=(0,d.resolveIdempotencyKey)(t.idempotencyKey);s&&(i[d.IDEMPOTENCY_KEY_HEADER]=s),t.checkoutMode==="auto"&&(i[d.FLO_SDK_CAPABILITIES_HEADER]=d.ASYNC_AUTO_CHECKOUT_CAPABILITY);let a,c=!1,l=Sr(t),u=(m,f,p)=>{c||(c=!0,this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:p,attempt:m}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:Math.max(0,this.telemetryTimestamp()-f),durationMode:"machine",requestCategory:"session_create",statusClass:p,attempt:m}))},h=m=>{try{this.telemetryHooks?.onRetry?.("session_create",m),this.directTelemetry?.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:m})}catch{}};for(let m=0;m<3;m++){o.attempt=m;let f=this.telemetryTimestamp();try{l?.onAttempt?.(m)}catch{}try{a=await fetch(`${this.baseUrl}/v1/checkouts/sessions?expand=true`,{method:"POST",headers:i,body:JSON.stringify(e),signal:n})}catch(v){if(o.statusClass=n.aborted||v instanceof Error&&v.name==="AbortError"?"timeout":"network_error",n.aborted||v instanceof Error&&v.name==="AbortError"||m>=2)throw v;let C=m+1;h(C),await ee(m,n);continue}let p=(0,d.telemetryStatusClass)(a.status);if(o.statusClass=p,a.status===204)throw u(m,f,p),new d.FloPayError("Session auto-completed \u2014 payment method already on file","api_error",{code:"session_auto_completed"});if(a.ok){u(m,f,p);break}let y=await L(a,"Failed to create checkout session");if(y.code===d.IDEMPOTENCY_IN_PROGRESS_CODE&&m<2){h(m+1),await ee(m,n);continue}throw u(m,f,p),y}if(!a)throw new TypeError("Checkout-session creation exhausted its retry budget.");return a}async createDetachedSession(e){this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp(),n=U(e.timeoutMs??12e3),o={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let i=e.products??(0,d.foldIntoProducts)(e.items,e.subscriptions);try{(0,d.assertCaptureMethodEligible)({captureMethod:e.captureMethod,products:i})}catch(C){throw n.clear(),this.reportSessionCreateFailure(C,t,o),C}let s=(0,d.resolveSessionCurrency)(e.currency,e.items,e.subscriptions,i);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{dt(e,s,i)}catch(C){throw n.clear(),this.reportSessionCreateFailure(C,t,o),C}let a,c,l=!1;try{let C=await this.postCheckoutSessionCreate(Rr(e,s),e,n.signal,o);if(l=!0,c=await C.json(),!c.data||!("gateways"in c.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(c.data)),c.vault&&a.data.session&&(a.data.session.vault=this.toVaultBlock(c.vault))}catch(C){throw n.clear(),l&&(0,d.markSessionResponseReceived)(C),this.reportSessionCreateFailure(C,t,o),C}let u=a.data.session?.id??c.data.uuid??"",h=a.data.session?.clientSecret??c.data.nonce??"";if(!u||!h){n.clear();let C=new d.FloPayError("Checkout session shell was created without a session id or nonce.","api_error",{code:"InvalidCheckoutSessionResponse"});throw this.reportSessionCreateFailure(C,t,o),C}n.clear(),this.adoptDirectTelemetryCheckout(u),this.directTelemetry?.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",statusClass:o.statusClass,paymentMethodCategory:"card"}),this.directTelemetry?.performance({stage:"session_shell",durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:"session_create",statusClass:o.statusClass,attempt:o.attempt,paymentMethodCategory:"card"});let m=!e.account.email?.trim(),f=U(e.timeoutMs??12e3),p=this.claimCheckoutSession(u,h,m?Ar(e,s,i):dt(e,s,i),{params:e,startedAt:t,deadline:f,createAttempt:o.attempt}),y=m?void 0:p,v=(C={})=>{if(y!==void 0)return y;let _={...e,account:{...e.account,...C,email:C.email?.trim()||e.account.email?.trim()}};return(0,d.isValidEmail)(_.account.email)?(y=p.then(()=>{let g=this.telemetryTimestamp();return this.claimCheckoutSession(u,h,kr(_.account),{params:_,startedAt:g,deadline:U(e.timeoutMs??12e3),createAttempt:0})}),y.catch(()=>{}),y):Promise.reject(new d.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}))};return p.catch(()=>{}),{shell:a,sessionId:u,nonce:h,claimed:p,claim:v}}async claimCheckoutSession(e,t,n,o){let i=o?.startedAt??this.telemetryTimestamp(),s=this.telemetryTimestamp(),a=o?.deadline??U(12e3),c=JSON.stringify(n),l="unknown",u=0,h=!1;this.directTelemetry?.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"});try{let m;for(u=0;u<3;u++){try{m=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},body:c,signal:a.signal})}catch(y){let v=a.signal.aborted||y instanceof Error&&y.name==="AbortError";if(l=v?"timeout":"network_error",v||u>=2)throw y;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 ee(u,a.signal);continue}if(l=(0,d.telemetryStatusClass)(m.status),m.ok)break;throw await L(m,"Failed to attach checkout session data")}if(!m)throw new TypeError("Checkout-session claim exhausted its retry budget.");h=!0;let f=await m.json();if(!f.data?.gateways)throw new d.FloPayError("The billing API returned no checkout session with gateways after claiming it.","api_error",{code:"InvalidCheckoutSessionResponse"});o?.params&&this.autoCacheDisplayData(f.data.uuid??e,o.params);let p=this.normalizeRawSession(this.mergeCachedDisplayData(f.data));return f.vault&&p.data.session&&(p.data.session.vault=this.toVaultBlock(f.vault)),this.directTelemetry?.log({name:"session.claim.completed",stage:"session_claim",requestCategory:"session_claim",statusClass:l}),this.directTelemetry?.performance({stage:"session_claim",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"session_claim",statusClass:l,attempt:u}),this.directTelemetry?.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:l}),this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-i),durationMode:"machine",requestCategory:"session_create",statusClass:l,attempt:o?.createAttempt??u}),p}catch(m){throw h&&(0,d.markSessionResponseReceived)(m),this.reportSessionCreateFailure(m,s,{attempt:u,statusClass:l},"session_claim"),m}finally{a.clear()}}reportSessionCreateFailure(e,t,n,o="session_create"){if(!(e instanceof d.FloPayError&&e.code==="session_auto_completed"))try{this.telemetryHooks?.onSessionCreateFailure?.(e)}catch{}let i=(0,d.classifyTelemetryFailure)(e,"CHECKOUT_SESSION_CREATE_FAILED");if(this.directTelemetry?.performance({stage:o,durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:o==="session_claim"?"session_claim":"session_create",statusClass:i.statusClass,attempt:n.attempt}),e instanceof d.FloPayError&&e.type==="validation_error"||e instanceof d.FloPayError&&ct(e.statusCode)){this.directTelemetry?.terminal({outcome:"validation_rejected",stage:o,requestCategory:o==="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({...i,stage:o,requestCategory:o==="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(),o=t?.paymentMethodCategory??"saved";this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:o});let i=t?.timeoutMs??Ae,s=Date.now()+i,a=new AbortController,c=!1,l,u=setTimeout(()=>{l=setTimeout(()=>{c=!0,a.abort()},at)},i),h=()=>a.abort(t?.signal?.reason);t?.signal?.aborted?h():t?.signal?.addEventListener("abort",h,{once:!0});let m=this.clampRetryAfterMs(t?.initialDelayMs??it),f=0;try{if(t?.statusUrl){let p=await this.waitForCheckoutStatus(e,{initialDelayMs:m,timeoutMs:i,nonce:t.nonce,statusUrl:t.statusUrl,pollAfterAction:t.continueAfterActionRequired,signal:a.signal});if(p){let y=await this.resolveCheckoutSessionStatus(e,p,t.nonce,a.signal,()=>c);return this.reportRecoveryCompleted(n,o,t.challengeAttemptId),y}}for(;;){let p=s-Date.now();if(p<=0)throw D();if(m>0){try{f+=1,this.telemetryHooks?.onRetry?.("session_read",f),this.directTelemetry?.log({name:"operation.retry",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:o,attempt:f})}catch{}if(await Le(Math.min(m,p),a.signal),Date.now()>=s)throw D()}let y=await this.getUnifiedCheckoutSessionForRecovery(e,t?.nonce,a.signal),v=y.data.session?.status;if(v==="authorized"||v==="complete"||v==="expired")return this.reportRecoveryCompleted(n,o,t?.challengeAttemptId),y;if(Date.now()>=s)throw D();m=this.clampRetryAfterMs(Math.max(m*2,st))}}catch(p){let y=c&&qe(p)?D():p;throw this.reportDirectFailure(y,"RECOVERY_FAILED","recovery","session_read",o),y}finally{clearTimeout(u),clearTimeout(l),t?.signal?.removeEventListener("abort",h)}}reportRecoveryCompleted(e,t,n){let o={stage:"recovery",requestCategory:"session_read",paymentMethodCategory:t};if(this.directTelemetry?.log({name:"operation.recovery.completed",...o}),n)try{this.directTelemetry?.beginThreeDsChallenge({attemptId:n}).record("recovery_read_completed",{evidenceBasis:"server_status"})}catch{}this.directTelemetry?.performance({...o,durationMs:Math.max(0,this.telemetryTimestamp()-e),durationMode:"machine"})}async resolveCheckoutSessionStatus(e,t,n,o,i){let s=t.latestTransactionAttempt;if(this.rememberReportedFailure(e,t),s?.result==="DECLINE"){let l=s.code===d.STORED_PAYMENT_METHOD_UNSUPPORTED_CODE;throw new d.FloPayError(l?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 dr("Payment could not be completed. Please try again.",s?.code??"payment_processing_error");let a;try{a=await this.getUnifiedCheckoutSessionForRecovery(e,n,o)}catch(l){if(!i?.()||!qe(l))throw l;a={providers:[],mode:"tokenize",data:{},raw:t}}let c=a.data.session;return c&&s?.result==="SUCCESS"?{...a,data:{...a.data,session:{...c,status:"complete"}}}:c&&s?.result==="AUTHORIZED"?{...a,data:{...a.data,session:{...c,status:"authorized",paymentId:t.paymentId??void 0,authorizationExpiresAt:t.authorizationExpiresAt??void 0}}}:c&&t.status==="completed"?{...a,data:{...a.data,session:{...c,status:"complete"}}}:c&&t.status==="authorized"?{...a,data:{...a.data,session:{...c,status:"authorized",paymentId:t.paymentId??void 0,authorizationExpiresAt:t.authorizationExpiresAt??void 0}}}:c&&t.status==="expired"?{...a,data:{...a.data,session:{...c,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,o=Date.now()+n,i=this.clampRetryAfterMs(t.initialDelayMs);for(;;){let s=o-Date.now();if(s<=0||i>0&&(await Le(Math.min(i,s),t.signal),Date.now()>=o))throw D();let a=o-Date.now();if(a<=0)throw D();let c=new AbortController,l,u=t.signal?new Promise((_,g)=>{l=g}):null,h=()=>{c.abort(t.signal?.reason),l?.(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 m,f=t.signal?null:new Promise((_,g)=>{m=setTimeout(()=>{g(D()),c.abort()},a+at)}),p;try{let _=this.fetchCheckoutStatus(e,t.nonce,t.statusUrl,c.signal);p=await Promise.race([_,f,u].filter(g=>g!==null))}finally{m!==void 0&&clearTimeout(m),t.signal?.removeEventListener("abort",h)}if(!p)return null;let y=ot(p.latestTransactionAttempt)&&!this.isOwnFailedAttempt(e,p,t.submittedIntentId);if(p.status==="completed"||p.status==="authorized"||p.status==="expired"||p.status==="voided")return y?{...p,latestTransactionAttempt:null}:p;let v=p.latestTransactionAttempt?.result,C=t.pollAfterAction===!0&&v==="ACTION_REQUIRED";if(!y&&v!==void 0&&v!=="PENDING"&&!C)return p;i=this.clampRetryAfterMs(Math.max(i*2,st))}}isOwnFailedAttempt(e,t,n){let o=t.latestTransactionAttempt?.providerIntentId??null;return n!==void 0?o===n:o===null?!0:!pr(t.uuid||e,o)}rememberReportedFailure(e,t){let n=t.latestTransactionAttempt;!ot(n)||!n.providerIntentId||hr(t.uuid||e,n.providerIntentId)}async fetchCheckoutStatus(e,t,n,o){let i=`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/status`,s=i;if(n)try{let u=new URL(n,`${this.baseUrl}/`),h=new URL(i);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 c=await ke(s,{headers:a,signal:o});if(c.status===404||c.status===405)return null;if(!c.ok)throw await L(c,"Failed to get checkout session status");let l=await c.json();return me(l.data)&&"latestTransactionAttempt"in l.data?l.data:null}normalizeRawSession(e){let t=e.gateways??{},n=[],o={session:this.toCheckoutSession(e)},i=t.stripe;if(i?.publishableKey){n.push("stripe");let c=[e.stripeClientSecret,i.stripeClientSecret].find(l=>typeof l=="string"&&l.length>0);o.stripe={clientSecret:c??"",publishableKey:i.publishableKey??void 0,paypalPublishableKey:i.paypalPublishableKey??void 0,environment:i.environment,enabledPaymentMethods:Array.isArray(i.enabledPaymentMethods)?i.enabledPaymentMethods.filter(l=>typeof l=="string"):void 0}}let s=t.paypal;return s?.publishableKey&&(n.push("paypal"),o.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:o,raw:{data:e}}}toCheckoutSession(e){let t=e.products??[],n=typeof e.totalAmount=="number"&&Number.isFinite(e.totalAmount),o=t.reduce((l,u)=>l+(u.overrideAmount??u.totalAmount??0),0),i=n?e.totalAmount:o,s=Math.round(i*100),a=e.currency??t[0]?.currency??"USD",c="payment";return e.checkoutMode==="setup"?c="setup":t.some(l=>l.type==="subscription")&&(c="subscription"),{id:e.uuid,clientSecret:e.nonce,mode:c,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}:{},...ir(e.futureUse)?{futureUse:e.futureUse}:{},...Array.isArray(e.futureUseUnsupported)?{futureUseUnsupported:e.futureUseUnsupported.filter(sr)}:{},buyerIdentified:e.buyerIdentified,providerPaymentMethodId:typeof e.providerPaymentMethodId=="string"?e.providerPaymentMethodId:null,products:t.map(l=>({...l,totalAmount:typeof l.totalAmount=="number"?l.totalAmount:void 0,overrideAmount:typeof l.overrideAmount=="number"?l.overrideAmount:null,currency:typeof l.currency=="string"?l.currency:void 0,metadata:l.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=br(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 o=await e.json().catch(()=>null),i=this.toCheckoutProcessingPending(o,e,t);return this.resolveCheckoutProcessing(i,t,n)}async resolveCheckoutProcessing(e,t,n){let o=n?.pollTimeoutMs??Ae,i=Date.now()+o;if(e.statusUrl){let a=await this.waitForCheckoutStatus(e.sessionId,{initialDelayMs:e.retryAfterMs,timeoutMs:o,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:i-Date.now(),nonce:n?.nonce,paymentMethodCategory:n?.paymentMethodCategory});return this.toProcessResponseFromSession(s,t)}async toProcessResponseFromStatus(e,t,n){let o=e.latestTransactionAttempt?.result,i={[lr]:cr},s={"Content-Type":"application/json",...i};if(e.status==="completed"||o==="SUCCESS")return new Response(null,{status:204,statusText:"No Content",headers:i});if(e.status==="authorized"||o==="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),o==="DECLINE"){let a=e.latestTransactionAttempt,c=a?.code===d.STORED_PAYMENT_METHOD_UNSUPPORTED_CODE,l=a?.declineReason??void 0;return new Response(JSON.stringify({type:l??"authorization_declined",message:c?d.STORED_PAYMENT_METHOD_UNSUPPORTED_MESSAGE:"Payment was declined. Please choose another payment method.",code:a?.code??l??"authorization_declined",...l?{declineCode:l}:{}}),{status:400,headers:s})}if(o==="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(o==="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(o==="ERROR"||e.status==="voided")return new Response(JSON.stringify({type:"unknown",code:e.latestTransactionAttempt?.code??"payment_processing_error",message:ar(e)??"Payment could not be completed. Please try again."}),{status:500,headers:s});throw D()}async reconcileProcessPayment(e,t){let n=t?.pollTimeoutMs??Ae,o=Date.now()+n,i=null;try{i=await this.waitForCheckoutStatus(e,{initialDelayMs:0,timeoutMs:n,nonce:t?.nonce,submittedIntentId:t?.submittedIntentId})}catch(c){if(this.reportDirectFailure(c,"RECOVERY_FAILED","recovery","session_read",t?.paymentMethodCategory??"saved"),c instanceof d.FloPayError&&c.code==="checkout_processing_timeout")throw c}if(i)return this.toProcessResponseFromStatus(i,e,t?.nonce);let s=o-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 o=t.headers.get("Retry-After"),i=o===null||o.trim()===""?void 0:Number(o),s=i!==void 0&&Number.isFinite(i)?i*1e3:void 0;return{type:"checkout_processing",sessionId:H(e,"sessionId")??n,retryAfterMs:this.clampRetryAfterMs(vr(e,"retryAfterMs")??s??it),statusUrl:H(e,"statusUrl"),sessionUrl:H(e,"sessionUrl")}}clampRetryAfterMs(e){return Math.max(0,Math.min(e,gr))}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 o=t.products!==void 0,i=(0,d.resolveSessionCurrency)(t.currency,o?void 0:t.items,o?void 0:t.subscriptions,n);Y(e,{currency:i??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??i??void 0}))})}mergeCachedDisplayData(e){let t=ve(e.uuid),n=new Map,o=s=>s?`code:${s}`:void 0;for(let s of t?.products??[]){let a=o(s.code);a&&n.set(a,s)}let i=(e.products??[]).map(s=>{let a=o(s.code),c=a?n.get(a):void 0;return{...s,name:s.name??c?.name??null,totalAmount:s.totalAmount??c?.totalAmount,overrideAmount:s.overrideAmount??c?.overrideAmount,currency:s.currency??c?.currency}});return{...e,currency:e.currency??t?.currency,products:i}}};J.activeVaultCaptureRequests=new Map;var pe=J;function ht(r,e){let t=pe;return new t(r,e)}var S=require("@flopay/shared");var Ie=require("@flopay/shared");function yt(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 Me=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,Ie.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 i of Array.from(e.querySelectorAll("script[src], iframe[src]"))){let s=yt(i.getAttribute("src"));if(s&&t.add(s),i.tagName==="SCRIPT"){let a=()=>this.fail("load_error");i.addEventListener("error",a),n.push(()=>i.removeEventListener("error",a))}}let o=i=>{let s=yt(i.blockedURI);s&&t.has(s)&&this.fail("blocked")};document.addEventListener("securitypolicyviolation",o),n.push(()=>document.removeEventListener("securitypolicyviolation",o)),this.detach=()=>{for(let i of n)i()}}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,Ie.invokeMerchantCallback)(()=>t(e))}};var Er=4,Pe="flopay-vault",Mr=3e4,Ir=S.THREE_DS_CHALLENGE_WINDOW_MS+Mr,Pr="Card authentication timed out.",gt={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 Dr(r){return r.class==="lifecycle"?r.name:r.class==="technical_error"?r.code:r.class==="expected_outcome"?r.outcome:"sdk.performance"}function re(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:Dr(r),data:e})}catch{}}function he(r,e){return(0,S.buildTelemetryLogEvent)({eventId:"11111111-1111-4111-8111-111111111111",name:r,stage:e,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}var Fr=new Set(["authorization_declined","authentication_required","authorization_expired","capture_failed"]);function xr(r){return typeof r=="string"&&Fr.has(r)?r:"unknown"}var Or=new Set(["verification_failed","verification_expired"]);function Ur(r){return r==null?!0:typeof r=="string"&&Or.has(r)}var qr="vault_mount";function Lr(r){return r.failureStage===qr}function Be(r,e){return r&&!Lr(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 ft(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 Nr(r,e,t,n="checkout"){let{type:o}=r;if(o==="complete"||o==="decline")return(0,S.buildTelemetryTerminalEvent)({eventId:"22222222-2222-4222-8222-222222222222",outcome:ft(r,t,n),sequence:0,provider:"pcivault",paymentMethodCategory:"card"});if(o==="error"){let a=Be(e,r);return(0,S.buildTelemetryErrorEvent)({eventId:"33333333-3333-4333-8333-333333333333",...a,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}let[i,s]=gt[o];return he(i,s)}function Br(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===Pe&&(e.type==="ready"||e.type==="submitting"||e.type==="blocked"||e.type==="complete"||e.type==="decline"||e.type==="error"||e.type==="action_required")}function Vr(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 zr(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 jr(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===Pe&&e.type==="validation"&&Array.isArray(e.messages)}function Hr(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===Pe&&e.type==="resize"&&typeof e.height=="number"&&Number.isFinite(e.height)}function Kr(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===Pe&&e.type==="fields_interactive"}function $r(r){let e=r.capabilities;return Array.isArray(e)&&e.includes("fields_interactive")}var Gr=["number","expiry","cvv","name"];function Yr(r){if(r===null||typeof r!="object")return;let e=r,t={};for(let n of Gr){let o=e[n];typeof o=="string"&&(t[n]=o)}return t}var Q=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.messageToken=null;this.expectedOrigin=null;this.theme=void 0;this.submitGateBlocked=!1;this.cardFieldOrder=null;this.cardAutoFocus=!0;this.cardBrandIcons=!1;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 Me({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,S.resolveBillingApiUrl)(e.billingApiUrl),sdkVersion:S.SDK_VERSION}):void 0)}async mount(e,t){this.ownsTelemetryReporter&&!this.telemetryReporter&&(this.telemetryReporter=new A({billingApiUrl:(0,S.resolveBillingApiUrl)(this.config.billingApiUrl),sdkVersion:S.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 S.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 S.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(o){throw this.reportVaultLoadFailure(),this.failCardFieldsMount(),o}this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),this.postCardBrandIcons(),this.postCardFieldPlaceholders(),this.postSubmitLabel(),re(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 o of n){let i=document.createElement("script");for(let s of Array.from(o.attributes))i.setAttribute(s.name,s.value);i.text=o.text,o.replaceWith(i)}}attachMessageListener(){if(this.messageHandler)return;let e=t=>{if(this.expectedOrigin&&t.origin!==this.expectedOrigin)return;let n=t.data;if(Hr(n)){if(this.messageToken&&n.messageToken!==this.messageToken)return;this.applyHeight(n.height);return}if(jr(n)){if(this.messageToken&&n.messageToken!==this.messageToken)return;let l=n.messages.filter(u=>typeof u=="string"&&u.trim()).join(" ");this.emit("validation",{sessionId:this.config.sessionId,message:l||void 0});return}if(Kr(n)){if(this.messageToken&&n.messageToken!==this.messageToken)return;let l=typeof n.sessionId=="string"?n.sessionId:void 0;if(this.config.sessionId&&l&&l!==this.config.sessionId)return;this.cardFields.ready();return}if(!Br(n)||this.messageToken&&n.messageToken!==this.messageToken)return;let o=this.config.sessionId,i=typeof n.sessionId=="string"?n.sessionId:void 0;if(o&&i&&i!==o||(n.type==="complete"||n.type==="decline")&&o&&i!==o)return;let s=zr(n.paymentMethod),a=Vr(n.vaultOutcome),c={...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)?(re(he("operation.state_transition","vault_mount")),this.telemetryReporter?.log({name:"operation.state_transition",stage:"vault_mount",provider:"pcivault",paymentMethodCategory:"card"})):(re(Nr(n,this.submissionStarted,this.config.captureMethod,this.config.operation)),this.reportOutcome(n),n.type==="error"&&Be(this.submissionStarted,n).errorCode==="VAULT_LOAD_FAILED"&&this.cardFields.fail("load_error")),n.type==="ready"&&(this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),this.postCardBrandIcons(),this.postCardFieldPlaceholders(),this.postSubmitLabel(),$r(n)||this.cardFields.ready()),n.type==="action_required"&&n.nextActionRedirectUrl&&this.showActionRequiredOverlay(n.nextActionRedirectUrl),(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,c)};this.messageHandler=e,window.addEventListener("message",e)}isVerificationStateError(e){return e.type==="error"&&this.verificationRequired&&!this.submissionStarted&&Ur(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:ft(e,this.config.captureMethod,this.config.operation),provider:"pcivault",paymentMethodCategory:"card"});return}if(n==="error"){let s=Be(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[o,i]=gt[n];t.log({name:o,stage:i,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()}setCardFieldPlaceholders(e){let t=Yr(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:o}=this;e===void 0||!t||!n||!o||this.postToHostedWindow({source:"flopay-vault-host",type:"cardFieldPlaceholders",sessionId:t,messageToken:n,placeholders:{...e}},o)}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:o}=this;e===void 0||!t||!n||!o||this.postToHostedWindow({source:"flopay-vault-host",type:"submitLabel",sessionId:t,messageToken:n,label:e},o)}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 p=this.actionOverlay.querySelector("iframe");p instanceof HTMLIFrameElement&&p.src!==e&&(p.src=e),this.armActionRequiredTimeout();return}this.actionOverlayPreviousFocus=document.activeElement instanceof HTMLElement?document.activeElement:null;let t=ce(this.beginActionChallengeAttempt()),n=Se(e),o=!1,i=p=>{if(o)return;let y=_e(p,n);y&&(o=!0,t.record("policy_violation",{reason:y,evidenceBasis:"parent_csp_event"}))},s=()=>{t.record("pagehide_observed",{evidenceBasis:"page_lifecycle_event"})},a={telemetry:t,loaded:!1,detach:()=>{document.removeEventListener("securitypolicyviolation",i),window.removeEventListener("pagehide",s)}};this.actionChallenge=a,this.lastChallengeTelemetry=t,t.record("handoff_planned"),de(e)==="invalid"&&t.record("action_invalid",{reason:"invalid_url"}),document.addEventListener("securitypolicyviolation",i),window.addEventListener("pagehide",s);let c=document.createElement("div");c.setAttribute("data-flopay-action-required","1"),c.setAttribute("role","dialog"),c.setAttribute("aria-modal","true"),c.setAttribute("aria-label","Card authentication"),c.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 l=document.createElement("iframe");l.setAttribute("title","Card authentication"),l.setAttribute("allow","payment"),l.tabIndex=0,l.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(";"),l.addEventListener("load",()=>{a.loaded||(a.loaded=!0,t.record("iframe_load",{evidenceBasis:"iframe_load_event"}))}),l.src=e,c.appendChild(l);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()),c.appendChild(u),c.addEventListener("click",p=>{p.target===c&&this.abandonActionRequiredOverlay()});let h=0,m=p=>{let y=p.data,v=!!y&&typeof y=="object"&&y.source==="flopay-vault-3ds-return";if(p.source!==l.contentWindow){v&&h<Er&&(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"}),re(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",m),this.threeDsReturnHandler=m,t.record("render_attempted");try{document.body.appendChild(c)}catch(p){throw t.record("render_failed"),this.hideActionRequiredOverlay(),this.actionOverlayPreviousFocus=null,p}t.record("container_attached"),t.record("navigation_assigned");let f=be(c);f&&t.record("container_visibility",{reason:f,evidenceBasis:"parent_computed_style"}),this.actionOverlay=c,l.focus(),this.armActionRequiredTimeout(),re(he("vault.three_ds.handoff","three_ds_handoff"))}armActionRequiredTimeout(){this.actionOverlayTimer&&clearTimeout(this.actionOverlayTimer),this.actionOverlayTimer=setTimeout(()=>{this.actionOverlayTimer=null,this.actionOverlay&&this.timeOutActionRequiredOverlay()},Ir)}reportChallengeAbandoned(){re((0,S.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.hideActionRequiredOverlay(),this.emit("error",{...this.config.sessionId?{sessionId:this.config.sessionId}:{},message:Pr})}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.hideActionRequiredOverlay(),this.emit("challenge_dismissed",{...this.config.sessionId?{sessionId:this.config.sessionId}:{}})}}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.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 Ct(r,e){let t=Q;return new t(r,{reporter:e})}var vt=Symbol.for("@flopay/js.telemetry.bridge.v1");function Tt(r,e,t){let n=()=>e?.now()??t();Object.defineProperty(r,vt,{configurable:!1,enumerable:!1,writable:!1,value:{error:i=>e?.error(i),log:i=>e?.log(i),performance:i=>e?.performance(i),terminal:i=>e?.terminal(i),now:n,elapsed:i=>Math.max(0,n()-i),setCheckoutContext:i=>e?.setCheckoutContext(i),beginCheckout:(i={})=>e?.beginCheckout(i)??n(),disable:()=>e?.disable(),subscribe:i=>e?.subscribe(i)??(()=>{}),flush:()=>e?.flush()??Promise.resolve()}})}function bt(r){return r[vt]}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}),Tt(this,this.telemetryReporter,E)}cardCapture(e){return this.telemetryReporter?.log({name:"vault.capture.requested",stage:"vault_request",provider:"pcivault",paymentMethodCategory:"card"}),this.telemetryReporter?Ct({sessionId:e?.sessionId,captureMethod:e?.captureMethod,cardFieldsTimeoutMs:e?.cardFieldsTimeoutMs},this.telemetryReporter):new Q({sessionId:e?.sessionId,captureMethod:e?.captureMethod,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),o=this.now();this.telemetryReporter?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let i,s,a=l=>{if(i===void 0)return;let u=i,h=s;i=void 0,s=void 0,this.telemetryReporter?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:l,attempt:h}),this.telemetryReporter?.performance({stage:"session_first_byte",durationMs:u,durationMode:"machine",requestCategory:"session_read",statusClass:l,attempt:h})},c=ht(n,{now:()=>this.telemetryReporter?.now()??E(),onFirstByte:(l,u)=>{i=l,s=u},onRetry:(l,u)=>{this.telemetryReporter?.log({name:"operation.retry",stage:l==="session_read"?"session_read":"processing",requestCategory:l,attempt:u})}});try{let l=await c.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()-o,durationMode:"machine",requestCategory:"session_read",statusClass:"2xx"}),l}catch(l){let u=(0,M.classifyTelemetryFailure)(l,l instanceof M.FloPayError&&l.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()-o,durationMode:"machine",requestCategory:"session_read",statusClass:u.statusClass}),l}}getRawProvider(){return this.provider.getRawProvider()}destroy(){this.telemetryReporter?.log({name:"checkout.unmount",stage:"unmount"}),this.telemetryReporter?.destroy(),this.provider.destroy()}};function _t(r,e,t){let n=ye;return new n(r,e,t)}var N=require("@flopay/shared");var Ve=require("@flopay/shared"),St=require("@stripe/stripe-js"),oe=require("@flopay/shared"),wt=new WeakSet;function Rt(r){return r instanceof Ve.FloPayError&&wt.has(r)}var ne=class{constructor(){this.name="stripe";this.stripe=null}async initialize(e){if(typeof window>"u")return;let t=await(0,St.loadStripe)(e.publishableKey,{locale:e.locale??"auto"});if(!t){let n=new Ve.FloPayError("Failed to initialize Stripe. Check your publishable key.","authentication_error");throw wt.add(n),n}this.stripe=t}getRawProvider(){return this.stripe}destroy(){this.stripe=null}};var At=new Map;function ze(r){return Array.isArray(r)?r.map(ze):r&&typeof r=="object"?Object.fromEntries(Object.entries(r).filter(([,e])=>e!==void 0).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,ze(t)])):r}function Wr(r,e){return JSON.stringify([r,(0,N.resolveBillingApiUrl)(e?.billingApiUrl),e?.telemetry!==!1,e?.locale??"auto",e?.apiVersion??null,ze(e?.appearance??null)])}var De=new Map;async function kt(r,e){if(!r){let a=new A({billingApiUrl:(0,N.resolveBillingApiUrl)(e?.billingApiUrl),sdkVersion:N.SDK_VERSION,enabled:e?.telemetry!==!1});throw a.error({errorCode:"CONFIGURATION_INVALID",stage:"sdk_initialize",paymentMethodCategory:"unknown"}),a.flush().catch(()=>{}).finally(()=>a.destroy()),new N.FloPayError("A publishable key is required to initialize FloPay.","validation_error",{param:"publishableKey"})}let t=Wr(r,e),n=At.get(t);if(n)return e?.telemetry!==!1&&bt(n)?.log({name:"sdk.cache.hit",stage:"sdk_initialize"}),n;let o=De.get(t);if(o)return o;let i={...e,publishableKey:r},s=(async()=>{let a=new A({billingApiUrl:(0,N.resolveBillingApiUrl)(i.billingApiUrl),sdkVersion:N.SDK_VERSION,enabled:i.telemetry!==!1}),c=a.now();a.log({name:"sdk.initialize.started",stage:"sdk_initialize"}),a.log({name:"sdk.cache.miss",stage:"sdk_initialize"}),a.log({name:"provider.load.started",stage:"provider_load",provider:"stripe"});let l=new ne,u=a.now();try{await l.initialize(i)}catch(f){throw a.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:Rt(f)?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"unknown"}),a.destroy(),f}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-c,durationMode:"machine",provider:"stripe"}),a.performance({stage:"provider_ready",durationMs:h-u,durationMode:"machine",provider:"stripe"});let m=_t(l,i,a);return At.set(t,m),m})();De.set(t,s);try{return await s}finally{De.get(t)===s&&De.delete(t)}}var K=require("@flopay/shared");var Jr=4,Qr=1e3,Xr=1e3,Zr=15e3;function en(r){let e=!!r?.gateways?.stripe,t=!!r?.gateways?.worldpayCorporateGateway;return e===t?"unknown":e?"stripe":"worldpay"}function Mt(r,e,t){try{return typeof r?.beginThreeDsChallenge!="function"?void 0:r.beginThreeDsChallenge(e,{provider:en(t)})}catch{return}}function ge(r){return new K.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:r})}function It(){return new K.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function Pt(r){return r.replace(/\/+$/,"")}function tn(r){return r.status==="succeeded"||r.status==="authorized"||r.status==="declined"}function rn(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 je(r){if(typeof document>"u"||typeof window>"u")throw new K.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});let e=ce(r.telemetry);e.record("handoff_planned");let t=de(r.nextActionRedirectUrl);t==="missing"?e.record("action_missing",{reason:"missing_url"}):t==="invalid"&&e.record("action_invalid",{reason:"invalid_url"});let n=p=>{let y=$e(p);if(y==="buyer_cancel"){e.record("cancel_requested",{reason:y,evidenceBasis:"signal_reason"}),e.terminal("cancel",{reason:y,evidenceBasis:"signal_reason"});return}e.record("abort_observed",{reason:y,evidenceBasis:"signal_reason"}),e.terminal("abort",{reason:y,evidenceBasis:"signal_reason"})},o=p=>{(p.status==="succeeded"||p.status==="authorized"||p.status==="declined"||p.status==="timeout")&&e.reconcile(p.status)};if(r.signal?.aborted)throw n(r.signal.reason),ge();let i=`${Pt(r.billingApiUrl)}/v1/checkouts/sessions/${encodeURIComponent(r.sessionId)}/3ds/complete`,s=async()=>{let p=new AbortController,y=()=>p.abort();r.signal?.aborted?p.abort():r.signal?.addEventListener("abort",y);let v=window.setTimeout(()=>p.abort(),Zr);try{let C=await fetch(i,{method:"POST",headers:{"x-checkout-session-token":r.nonce,"content-type":"application/json",...e.attemptId?{"x-flopay-challenge-attempt":e.attemptId}:{}},body:"{}",signal:p.signal});if(!C.ok)return{status:"unknown"};let _=await C.json().catch(()=>null),g=rn(_);return o(g),g}catch{return{status:"unknown"}}finally{window.clearTimeout(v),r.signal?.removeEventListener("abort",y)}},a,c=()=>r.pollCompletionEndpoint!==!1?s():(a??(a=s()),a),l=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 m=null;try{m=new URL(r.billingApiUrl,window.location.href).origin}catch{m=null}let f=Se(r.nextActionRedirectUrl);try{let p=await new Promise((y,v)=>{let C=!1,_=0,g=0,F=0,$=!1,B=!1,x=!1,I=0,R=()=>{window.clearTimeout(_),window.clearInterval(g),window.clearTimeout(F),window.removeEventListener("message",P),window.removeEventListener("pagehide",ie),document.removeEventListener("securitypolicyviolation",O),h.removeEventListener("load",G),r.signal?.removeEventListener("abort",se)},X=async()=>{if(!(C||$)){$=!0;try{let w=await c();if(C||!tn(w))return;C=!0,R(),e.terminal("status_poll",{evidenceBasis:"server_status"}),y(w)}finally{$=!1}}},ie=()=>{e.record("pagehide_observed",{evidenceBasis:"page_lifecycle_event"})},O=w=>{if(x)return;let b=_e(w,f);b&&(x=!0,e.record("policy_violation",{reason:b,evidenceBasis:"parent_csp_event"}))},G=()=>{B||(B=!0,e.record("iframe_load",{evidenceBasis:"iframe_load_event"})),r.pollCompletionEndpoint!==!1&&(window.clearTimeout(F),F=window.setTimeout(()=>{X()},250))},se=()=>{C||(C=!0,R(),n(r.signal?.reason),v(ge()))},V=w=>{C||I>=Jr||(I+=1,e.record("return_rejected",{reason:w,evidenceBasis:"message_origin_check"}))},P=w=>{let b=w.data,z=!!b&&typeof b=="object"&&b.source==="flopay-vault-3ds-return";if(w.source!==h.contentWindow){z&&V("untrusted_source");return}if(m&&w.origin!==m){z&&V("untrusted_origin");return}z&&(C||(C=!0,R(),e.record("trusted_return",{evidenceBasis:"message_origin_check"}),e.terminal("trusted_return",{evidenceBasis:"message_origin_check"}),y(null)))};_=window.setTimeout(()=>{C||(C=!0,R(),B||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(It()))},K.THREE_DS_CHALLENGE_WINDOW_MS),r.pollCompletionEndpoint!==!1&&(g=window.setInterval(()=>{X()},Xr)),h.addEventListener("load",G),window.addEventListener("message",P),window.addEventListener("pagehide",ie),document.addEventListener("securitypolicyviolation",O),r.signal?.addEventListener("abort",se),h.src=r.nextActionRedirectUrl,e.record("render_attempted");try{u.appendChild(h),document.body.appendChild(u)}catch(w){throw C=!0,R(),e.record("render_failed"),w}e.record("container_attached"),e.record("navigation_assigned");let Z=be(u);Z&&e.record("container_visibility",{reason:Z,evidenceBasis:"parent_computed_style"}),h.focus(),r.signal?.aborted&&se()});return p||await c()}finally{u.parentNode?.removeChild(u),e.record("teardown"),l?.isConnected&&l.focus()}}function Et(r,e){try{let t=e.data.session?.status;t==="complete"?r.reconcile("succeeded"):t==="authorized"&&r.reconcile("authorized")}catch{}}function nn(r){return new K.FloPayError("Card was declined.","api_error",{code:r.declineReason??"authorization_declined",...r.gatewayDeclineReason?{declineCode:r.gatewayDeclineReason}:{}})}async function Dt(r,e){let t=`${Pt(r.billingApiUrl)}/v1/checkouts/sessions/${encodeURIComponent(r.sessionId)}/status`,n=new AbortController,o=new AbortController,i=()=>{n.abort(r.signal?.reason),o.abort(r.signal?.reason)};r.signal?.aborted?i():r.signal?.addEventListener("abort",i,{once:!0});let s=ce(r.telemetry),a=je({billingApiUrl:r.billingApiUrl,sessionId:r.sessionId,nonce:r.nonce,nextActionRedirectUrl:r.nextActionRedirectUrl,signal:n.signal,pollCompletionEndpoint:!1,...r.telemetry?{telemetry:r.telemetry}:{}}),c=e.waitForCheckoutSessionCompletion(r.sessionId,{initialDelayMs:Qr,nonce:r.nonce,statusUrl:t,continueAfterActionRequired:!0,timeoutMs:K.THREE_DS_CHALLENGE_WINDOW_MS+15e3,signal:o.signal,...s.attemptId?{challengeAttemptId:s.attemptId}:{}});c.catch(()=>{}),a.catch(()=>{});try{let l=await Promise.race([a,c]);if("data"in l)return s.terminal("status_poll",{evidenceBasis:"server_status"}),Et(s,l),l;if(l.status==="declined")throw(r.createDeclineError??nn)(l);if(l.status==="timeout")throw It();let u=await c;return Et(s,u),u}catch(l){throw r.signal?.aborted||l instanceof Error&&l.name==="AbortError"?ge(l):l}finally{r.signal?.removeEventListener("abort",i),n.abort(),o.abort()}}0&&(module.exports={FloPay,PaymentAPI,PciVaultCardCapture,SESSION_CREATE_TELEMETRY,StripeAdapter,beginSavedCardChallengeTelemetry,cacheSessionDisplayData,clearSessionDisplayData,completeSavedCardNextAction,createCheckoutSession,createCheckoutSessionWithRetries,createSavedCardActionAbortedError,dropThirdPartyOnlyError,getSessionDisplayData,loadFloPay,runSavedCardChallenge,toStripeAppearance,toStripeAppearanceTheme});
|
|
1
|
+
"use strict";var Fe=Object.defineProperty;var Ot=Object.getOwnPropertyDescriptor;var Ut=Object.getOwnPropertyNames;var qt=Object.prototype.hasOwnProperty;var Lt=(r,e)=>{for(var t in e)Fe(r,t,{get:e[t],enumerable:!0})},Nt=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Ut(e))!qt.call(r,i)&&i!==t&&Fe(r,i,{get:()=>e[i],enumerable:!(n=Ot(e,i))||n.enumerable});return r};var Bt=r=>Nt(Fe({},"__esModule",{value:!0}),r);var an={};Lt(an,{FloPay:()=>ye,PaymentAPI:()=>pe,PciVaultCardCapture:()=>Q,SESSION_CREATE_TELEMETRY:()=>Ne,StripeAdapter:()=>ne,beginSavedCardChallengeTelemetry:()=>It,cacheSessionDisplayData:()=>Y,clearSessionDisplayData:()=>Te,completeSavedCardNextAction:()=>Ft,createCheckoutSession:()=>Ze,createCheckoutSessionWithRetries:()=>nt,createSavedCardActionAbortedError:()=>ge,dropThirdPartyOnlyError:()=>xt.dropThirdPartyOnlyError,getSessionDisplayData:()=>ve,loadFloPay:()=>Et,runSavedCardChallenge:()=>je,toStripeAppearance:()=>ie.toStripeAppearance,toStripeAppearanceTheme:()=>ie.toStripeAppearanceTheme});module.exports=Bt(an);var xt=require("@flopay/shared");var T=require("@flopay/shared");function ae(r){return typeof r=="string"&&r.trim()?r:void 0}function le(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 U(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 Vt(){return Object.assign(new Error("The operation was aborted."),{name:"AbortError"})}function ee(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",c),c=()=>{s!==void 0&&clearTimeout(s),a(),o(Vt())};if(e.aborted){c();return}s=setTimeout(()=>{a(),i()},n),e.addEventListener("abort",c,{once:!0})})}var zt="flopay_session_display:";var fe=new Map;function Ce(r){return`${zt}${r}`}function xe(){if(typeof window>"u")return null;try{return window.sessionStorage}catch{return null}}function Y(r,e,t){if(!r)return;let n=t?.ttlMs??36e5,i={data:e,expiresAt:Date.now()+n},o=xe();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=xe();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=xe();if(e)try{e.removeItem(Ce(r))}catch{}}var k=require("@flopay/shared");var Oe=require("@flopay/shared"),jt=32,He=Symbol.for("@flopay/js.three-ds-challenge.attempts.v1");function Ht(){let r=globalThis,e=r[He];if(e instanceof Map)return e;let t=new Map;try{Object.defineProperty(r,He,{configurable:!0,enumerable:!1,writable:!1,value:t})}catch{}return t}function Kt(r,e){let t=Ht(),n=t.get(r);if(n)return n;for(;t.size>=jt;){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 $t=new Set(["pagehide_observed","cancel_requested","abort_observed","browser_terminal"]),Gt=new Set(["teardown","recovery_read_completed","provider_reconciled"]);function Ke(r,e={}){let t=(0,Oe.isThreeDsChallengeAttemptId)(e.attemptId)?e.attemptId.toLowerCase():r.newAttemptId(),n=()=>{try{let a=r.now();return Number.isFinite(a)?a:0}catch{return 0}},i=Kt(t,n());(e.provider==="stripe"||e.provider==="worldpay")&&(i.provider=e.provider);let o=i.provider,s=(a,c)=>{if(i.terminated&&!Gt.has(a))return;let l={attemptId:t,phase:a,attemptSequence:i.nextSequence,elapsedMs:Math.max(0,n()-i.startedAt),provider:o};i.nextSequence+=1,c.reason!==void 0&&(l.reason=c.reason),c.evidenceBasis!==void 0&&(l.evidenceBasis=c.evidenceBasis),c.terminalSource!==void 0&&(l.terminalSource=c.terminalSource),c.providerOutcome!==void 0&&(l.providerOutcome=c.providerOutcome);try{r.emit(l,$t.has(a))}catch{}};return{attemptId:t,record(a,c={}){a==="browser_terminal"||a==="provider_reconciled"||s(a,{reason:c.reason,evidenceBasis:c.evidenceBasis})},terminal(a,c={}){i.terminated||(s("browser_terminal",{terminalSource:a,reason:c.reason,evidenceBasis:c.evidenceBasis}),i.terminated=!0)},reconcile(a){i.reconciled.has(a)||(i.reconciled.add(a),s("provider_reconciled",{providerOutcome:a,evidenceBasis:"provider_fact"}))}}}function ce(r){let e=null;try{e=(0,Oe.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 de(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 $e(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 de(r)==="valid"?new URL(r).origin:null}catch{return null}}var Yt="/v1/sdk-telemetry/events",we=16,Ge=64,Wt=1500,Ye=1e3,Jt=64,Qt="00000000-0000-4000-8000-000000000000",Xt={technical_error:8,lifecycle:32,expected_outcome:32,performance:24},Zt=48;function j(){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 er(r){try{return new TextEncoder().encode(r).byteLength}catch{return r.length}}function tr(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(/\/+$/,"")}${Yt}`,this.sdkPackage=e.sdkPackage??"@flopay/js",this.sdkVersion=e.sdkVersion,this.correlationId=j(),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:j(),sequence:this.sequence++}))}error(e){if(this.notify({...e,class:"technical_error"}),!this.canCollect())return;let t=(0,k.buildTelemetryErrorEvent)({...this.checkoutContext,...e,eventId:Qt,sequence:0}),n=tr(t),i=this.now();this.pruneReportedFailures(i);let o=this.reportedFailures.get(n);if(o!==void 0&&i>=o&&i-o<Ye){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:j(),sequence:this.sequence++}))}performance(e){this.canCollect()&&this.enqueue((0,k.buildTelemetryPerformanceEvent)({...this.checkoutContext,...e,eventId:j(),sequence:this.sequence++}))}terminal(e){if(this.canCollect()&&(this.enqueue((0,k.buildTelemetryTerminalEvent)({...this.checkoutContext,...e,eventId:j(),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 Ke({now:()=>this.now(),newAttemptId:j,emit:(t,n)=>this.recordThreeDsChallenge(t,n)},e)}recordThreeDsChallenge(e,t){if(!this.canCollect()||this.threeDsChallengeCount>=Zt)return;let n=(0,k.buildTelemetryLogEvent)({...this.checkoutContext,...e,name:"three_ds.challenge",stage:"three_ds_handoff",eventId:j(),sequence:this.sequence++});if(!(this.queue.length>=Ge)){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>=Ye)&&this.reportedFailures.delete(t)}rememberReportedFailure(e,t){for(;this.reportedFailures.size>=Jt;){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>=Ge||this.eventCounts[e.class]>=Xt[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:j()});if(er(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 c=>{if(c.status!==202)return null;let l=null;try{l=await c.json()}catch{}return l?.status==="disabled"?"disabled":null}).catch(()=>null),s=new Promise(c=>{i=setTimeout(()=>{n?.abort(),c(null)},Wt)});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)}},We=Symbol.for("@flopay/js.telemetry.reporter-factory.v1"),Je=globalThis;Je[We]===void 0&&Object.defineProperty(Je,We,{configurable:!0,enumerable:!1,writable:!1,value:r=>new A(r)});var Ue=5,Qe=new WeakSet;function rr(r){(typeof r=="object"&&r!==null||typeof r=="function")&&Qe.add(r)}function nr(r){return(typeof r=="object"&&r!==null||typeof r=="function")&&Qe.has(r)}function ir(r,e){let t=e?.error,n=ae(e?.code)??ae(t?.code)??`http_${r}`,i=le(e?.message)??le(t?.message)??or(n,r);return new T.FloPayError(i,"api_error",{code:n,statusCode:r})}function or(r,e){switch(r){case"CouponLimitExceeded":return`Too many coupon codes \u2014 a checkout session accepts at most ${Ue}.`;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 Xe(r,e,t){let{billingApiUrl:n,checkoutBaseUrl:i,items:o=[],subscriptions:s=[],products:a,account:c,successUrl:l,cancelUrl:u,checkoutMode:h="confirm",captureMethod:m,couponCodes:f=[],checkoutMetadata:p,tagsData:y,redirectParams:v={},setCookie:C=!0,clientId:_,currency:g,utmMetadata:F,idempotencyKey:$}=r,B=(0,T.resolveIdempotencyKey)($);if(f.length>Ue)throw new T.FloPayError(`Too many coupon codes \u2014 a checkout session accepts at most ${Ue}.`,"validation_error",{code:"CouponLimitExceeded",param:"couponCodes"});let x=a??(0,T.foldIntoProducts)(o,s);(0,T.assertCaptureMethodEligible)({captureMethod:m,products:x});let I=(0,T.resolveSessionCurrency)(g,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:_,checkoutVersion:T.SDK_VERSION,successUrl:l,cancelUrl:u,currency:I,checkoutMode:h,products:x.map(P=>(0,T.buildProductPayload)(P,I)),accountData:{userId:c.userId,firstName:c.firstName??null,lastName:c.lastName??null,email:c.email,country:c.country??null,gender:c.gender??null,city:c.city??null,state:c.state??null,zip:c.zip??null,addressLine1:c.addressLine1??null,addressLine2:c.addressLine2??null},couponCodes:f};m==="manual"&&(R.captureMethod=m),p!==void 0&&(R.checkoutMetadata=p),y&&(R.tagsData=y),F&&F.length>0&&(R.utmMetadata=F);let X=`${n.replace(/\/+$/,"")}/v1/checkouts/sessions`,oe={"Content-Type":"application/json"};B&&(oe[T.IDEMPOTENCY_KEY_HEADER]=B);let O,G,se={method:"POST",headers:oe,body:JSON.stringify(R),signal:e},V;try{t?.startAttempt(),V=await fetch(X,se)}catch(P){throw rr(P),P}try{t?.record(V.status)}catch{}O=V.status;try{G=await V.json()}catch{}if(O>=400)throw(0,T.withTelemetryHttpDiagnostics)(ir(O,G),V);if(O===201){let P=G?.data?.uuid,Z=G?.data?.nonce;if(!P)throw new Error("Checkout session created but no UUID was returned by the billing API");if(!Z)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)&&Y(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,z]of Object.entries(v))w.searchParams.set(b,z);if(C&&typeof window<"u"&&typeof document<"u"){let b=JSON.stringify({origin_url:u}),z=window.location.hostname.split(".").slice(-2).join(".");document.cookie=`checkout_data=${encodeURIComponent(b)}; domain=.${z}; path=/; max-age=3600; SameSite=Lax; Secure;`,document.cookie=`flopay_checkout_token=${encodeURIComponent(Z)}; domain=.${z}; path=/; max-age=3600; SameSite=Lax; Secure;`}return typeof window<"u"&&(window.location.href=w.toString()),{status:201,redirectUrl:w.toString(),nonce:Z}}return O===204?(typeof window<"u"&&(window.location.href=l),{status:204}):{status:O}}async function Ze(r){let e=tt(r),t=et(e),n=U(r.timeoutMs);try{let i=await Xe(r,n.signal,t);return t.commit(),rt(e,i),i}catch(i){throw t.commit(),Re(e,i),i}finally{n.clear(),te(e.reporter)}}function et(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 tt(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 rt(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 te(r){r.flush().catch(()=>{}).finally(()=>r.destroy())}async function nt(r){let{maxRetries:e=2,...t}=r,n=tt(r),i=et(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"}),te(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=U(t.timeoutMs),a;for(let c=0;c<=e;c++){n.attempt=c;try{let l=await Xe(o,s.signal,i);return i.commit(),rt(n,l),s.clear(),te(n.reporter),l}catch(l){a=l;let u=l instanceof Error&&l.name==="AbortError",h=nr(l),m=l instanceof T.FloPayError&&l.code===T.IDEMPOTENCY_IN_PROGRESS_CODE;if((u||h||m)&&!s.signal.aborted&&c<e){n.reporter.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:c+1});try{await ee(c,s.signal)}catch(f){throw i.commit(),Re(n,f),s.clear(),te(n.reporter),f}continue}throw i.commit(),Re(n,l),s.clear(),te(n.reporter),l}}throw i.commit(),Re(n,a),s.clear(),te(n.reporter),a??new Error("Unknown error during checkout session creation")}var M=require("@flopay/shared");var d=require("@flopay/shared");function sr(r){return r==="on_session"||r==="off_session"}function ar(r){if(!r||typeof r!="object")return!1;let e=r;return typeof e.paymentMethodType=="string"&&typeof e.reason=="string"}function lr(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 cr="x-flopay-process-result-source",dr="status",mt=new WeakSet;function ur(r,e){let t=new d.FloPayError(r,"api_error",{code:e,statusCode:500});return mt.add(t),t}function mr(r){return typeof r=="object"&&r!==null&&mt.has(r)}function it(r){return r?.result==="DECLINE"||r?.result==="ERROR"}var pr=50,W=new Map;function hr(r,e){return W.get(r)?.has(e)===!0}function yr(r,e){let t=W.get(r)??new Set;if(t.add(e),W.delete(r),W.set(r,t),W.size>pr){let n=W.keys().next().value;n!==void 0&&W.delete(n)}}function gr(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 ot=0,st=500,Ae=15e3,at=15e3,fr=3e3,Cr=1e4,vr=1e4;function me(r){return typeof r=="object"&&r!==null}function H(r,e){return ae(r?.[e])}function lt(r,e){return le(r?.[e])}function Tr(r,e){let t=r?.[e];return typeof t=="number"&&Number.isFinite(t)?t:void 0}function Le(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 qe(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 L(r,e){let t=await r.json().catch(()=>null),n=me(t?.error)?t.error:null,i=lt(t,"message")??lt(n,"message")??e,o=H(t,"code")??H(t,"gatewayErrorCode")??H(n,"code")??`http_${r.status}`;return(0,d.withTelemetryHttpDiagnostics)(new d.FloPayError(i,"api_error",{code:o,statusCode:r.status}),r)}async function br(r){if(r.status!==403)return!1;let e=await r.clone().json().catch(()=>null),t=me(e?.error)?e.error:null;return(H(e,"code")??H(t,"code"))==="verification_required"}function _r(r){if(!(!me(r)||typeof r.required!="boolean"))return{required:r.required,provider:"turnstile"}}async function Sr(r){let e=r.status===400?await r.clone().json().catch(()=>null):null;return(0,d.classifyPaymentRejection)(r.status,e)}function ct(r){return r===400||r===422}var Ee=2;async function ke(r,e,t=Ee,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 Le(150*2**s,e?.signal??void 0)}}var Ne=Symbol.for("@flopay/js.session-create.telemetry.v1");function wr(r){return r[Ne]}function Rr(r){return"now"in r||"onFirstByte"in r||"onSessionCreateFailure"in r||"onRetry"in r}function pt(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 ht(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 dt(r){if(typeof r!="string")return;let e=r.trim();return e.length>0?e:void 0}function Ar(r){let e={};if(r.country&&(e.country=r.country),!(0,d.isCardHolderNamePlaceholder)(r.firstName,r.lastName)){let t=dt(r.firstName),n=dt(r.lastName);t&&(e.firstName=t),n&&(e.lastName=n)}return Object.keys(e).length>0?e:void 0}function kr(r,e){let t={clientId:r.clientId,checkoutVersion:d.SDK_VERSION,successUrl:r.successUrl,cancelUrl:r.cancelUrl,currency:e,checkoutMode:"full",deferDataAttachment:!0};r.captureMethod==="manual"&&(t.captureMethod=r.captureMethod);let n=Ar(r.account);return n&&(t.accountData=n),ht(t,r),t}function ut(r,e,t){return{currency:e,products:t.map(n=>(0,d.buildProductPayload)(n,e)),couponCodes:r.couponCodes??[],accountData:pt(r.account)}}function Er(r,e,t){return{currency:e,products:t.map(n=>(0,d.buildProductPayload)(n,e)),couponCodes:r.couponCodes??[]}}function Mr(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 J=class J{constructor(e,t={}){this.baseUrl=e.replace(/\/+$/,"");let n=Rr(t);this.telemetryHooks=n?t:void 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,...mr(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 c={[d.FLO_SDK_VERSION_HEADER]:d.SDK_VERSION};t&&(c["x-checkout-session-token"]=t);let l=!1;try{let u=await ke(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}`,{headers:c,signal:i},Ee,p=>{this.telemetryHooks?.onRetry?.("session_read",p),this.directTelemetry?.log({name:"operation.retry",stage:"session_read",requestCategory:"session_read",attempt:p})},p=>{a=p,s=this.telemetryTimestamp()});l=!0;let h=Math.max(0,this.telemetryTimestamp()-s);try{this.telemetryHooks?.onFirstByte?.(h,a)}catch{}let m=`${Math.floor(u.status/100)}xx`;if(this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:m,attempt:a}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:h,durationMode:"machine",requestCategory:"session_read",statusClass:m,attempt:a}),!u.ok)throw await L(u,"Failed to get checkout session");let f=await u.json();return this.directTelemetry?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:m}),this.directTelemetry?.performance({stage:"session_complete",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"session_read",statusClass:m}),{...f,data:this.mergeCachedDisplayData(f.data)}}catch(u){throw l&&(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){Y(e,t,n)}clearSessionDisplayData(e){Te(e)}async getVaultCapture(e,t){let n=`${this.baseUrl}\0${e}\0${t??""}`,i=J.activeVaultCaptureRequests.get(n);if(i!==void 0)return i;let o=this.requestVaultCapture(e,t);J.activeVaultCaptureRequests.set(n,o);try{return await o}finally{J.activeVaultCaptureRequests.get(n)===o&&J.activeVaultCaptureRequests.delete(n)}}async requestVaultCapture(e,t){let n=new AbortController,i=setTimeout(()=>n.abort(),vr);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},Ee,l=>{this.telemetryHooks?.onRetry?.("vault_capture",l),this.directTelemetry?.log({name:"operation.retry",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card",attempt:l})});if(await br(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 L(a,"Failed to load the secure card form");let c=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(c)}catch(a){let c=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(c,"VAULT_LOAD_FAILED","vault_request","vault_capture","card"),c}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,...c}=t,l=gr(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(c)}),h=u}catch(m){if(qe(m))throw this.reportDirectFailure(m,"PAYMENT_PROCESSING_FAILED","processing","process_payment",i),m;u=await this.reconcileProcessPayment(t.sessionId,{...n,nonce:s,paymentMethodCategory:i,submittedIntentId:l})}if(!u.ok&&u.status!==202){let m=await Sr(u);return m?this.directTelemetry?.terminal({outcome:m,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 m=await this.resolveProcessResponse(u,t.sessionId,{...n,nonce:s,paymentMethodCategory:i,submittedIntentId:l});return this.directTelemetry?.log({name:"payment.processing.completed",stage:"processing",requestCategory:"process_payment",statusClass:(0,d.telemetryStatusClass)(m.status),paymentMethodCategory:i}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"process_payment",statusClass:(0,d.telemetryStatusClass)(m.status),paymentMethodCategory:i}),m}catch(m){throw m instanceof d.FloPayError&&m.code==="checkout_processing_timeout"||this.reportDirectFailure(m,"PAYMENT_PROCESSING_FAILED","processing","process_payment",i),m}}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??Cr,a=new AbortController,c=()=>a.abort();i?.signal&&(i.signal.aborted?a.abort():i.signal.addEventListener("abort",c,{once:!0}));let l=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},Ee,h=>{this.telemetryHooks?.onRetry?.("account_snapshot",h),this.directTelemetry?.log({name:"operation.retry",stage:"processing",requestCategory:"account_snapshot",attempt:h})})}finally{clearTimeout(l),i?.signal?.removeEventListener("abort",c)}if(!u.ok)throw await L(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",c=typeof s=="string"&&s.length>0&&!a&&(typeof o.paymentMethodId=="string"||o.paymentMethodId===null),l=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(!c||!l&&!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 m=(0,d.isUuidV4)(h)?h:(0,d.randomUuidV4)();this.beginDirectTelemetryCheckout(e);let f=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.intent.started",stage:"processing",requestCategory:"intent_create"});let p={"Content-Type":"application/json","x-checkout-session-token":t,[d.IDEMPOTENCY_KEY_HEADER]:i?.idempotencyKey||m},y=!1;try{let v=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents`,{method:"POST",headers:p,body:JSON.stringify({...n,authorizationAttemptId:m}),signal:i?.signal});if(!v.ok){y=!0;let R=await L(v,"Failed to create checkout intent"),X=(0,d.classifyTelemetryFailure)(R,"PAYMENT_PROCESSING_FAILED");throw ct(R.statusCode)?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"intent_create",statusClass:"4xx"}):this.directTelemetry?.error({...X,stage:"processing",requestCategory:"intent_create"}),R}let C=await v.json();if(v.status===202&&me(C)&&C.type==="checkout_processing")return y=!0,await this.settleProcessingSessionIntent(C,v,e,t,n);let _=C.data;if(!_||typeof _!="object")throw new d.FloPayError("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});let g=_,F=g.paymentMethodType,$=(g.paymentMethodCategory==="wallet"||g.paymentMethodCategory==="apm")&&typeof F=="string"&&F.trim().toLowerCase()!=="card"&&(typeof g.paymentMethodId=="string"||g.paymentMethodId===null)&&typeof g.providerObjectId=="string",B=g.provider==="stripe"&&(g.intentKind==="payment"||g.intentKind==="setup")&&typeof g.clientSecret=="string",x=g.provider==="paypal"&&g.paymentMethodCategory==="wallet"&&g.paymentMethodId===null&&(g.paymentMethodType==="paypal"&&g.intentKind==="payment"&&(g.providerObjectType==="order"||g.providerObjectType==="subscription")||g.paymentMethodType===d.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&g.intentKind==="payment"&&g.providerObjectType==="order"||g.paymentMethodType===d.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&g.intentKind==="setup"&&g.providerObjectType==="setup_token")&&g.clientSecret===null,I=g.provider===n.provider&&g.paymentMethodCategory===n.paymentMethodCategory&&g.paymentMethodType===n.paymentMethodType&&g.paymentMethodId===n.paymentMethodId&&g.intentKind===n.intentKind;if(!$||!B&&!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()-f),durationMode:"machine",requestCategory:"intent_create",statusClass:(0,d.telemetryStatusClass)(v.status)}),g}catch(v){throw y||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}}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,c=o.providerIntentId,l=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"&&l,h=o.provider==="stripe"&&(o.paymentMethodCategory==="wallet"||o.paymentMethodCategory==="apm")&&(c===void 0||typeof c=="string"&&/^pi_[a-z0-9_]{1,252}$/i.test(c)),m=o.provider==="paypal"&&o.paymentMethodCategory==="wallet"&&o.paymentMethodType==="paypal"&&c===void 0;if(!u||!h&&!m)throw new d.FloPayError("Invalid non-card decline classification.","validation_error",{code:"InvalidSessionIntentDeclineRequest"});let f=m?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:s}:{provider:"stripe",paymentMethodCategory:o.paymentMethodCategory,paymentMethodType:o.paymentMethodType,providerDeclineReason:s,...typeof c=="string"?{providerIntentId:c}:{}},p=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(f),signal:i?.signal});if(!p.ok)throw await L(p,"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 L(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 c=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"}),c}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=U(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(l=>(0,d.buildProductPayload)(l,o)),accountData:pt(e.account),couponCodes:e.couponCodes??[]};e.captureMethod==="manual"&&(s.captureMethod=e.captureMethod),e.tokenizedData&&(s.tokenizedData=e.tokenizedData),ht(s,e);let a=await this.postCheckoutSessionCreate(s,e,t,n),c=!1;try{let l=await a.json();if(l.data&&"gateways"in l.data){this.autoCacheDisplayData(l.data.uuid,e);let m=this.mergeCachedDisplayData(l.data),f=this.normalizeRawSession(m);return l.vault&&f.data.session&&(f.data.session.vault=this.toVaultBlock(l.vault)),{...f,autoProcessingError:l.autoProcessingError,autoProcessingAttempted:l.autoProcessingAttempted,autoProcessingPending:l.autoProcessingPending}}let u=l.data?.uuid;if(!u)throw new d.FloPayError("No session ID returned","api_error",{code:"InvalidCheckoutSessionResponse"});return this.autoCacheDisplayData(u,e),this.adoptDirectTelemetryCheckout(u),c=!0,{...await this.getUnifiedCheckoutSession(u),autoProcessingError:l.autoProcessingError,autoProcessingAttempted:l.autoProcessingAttempted,autoProcessingPending:l.autoProcessingPending}}catch(l){throw c?l:(0,d.markSessionResponseReceived)(l)}}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),t.checkoutMode==="auto"&&(o[d.FLO_SDK_CAPABILITIES_HEADER]=d.ASYNC_AUTO_CHECKOUT_CAPABILITY);let a,c=!1,l=wr(t),u=(m,f,p)=>{c||(c=!0,this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:p,attempt:m}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:Math.max(0,this.telemetryTimestamp()-f),durationMode:"machine",requestCategory:"session_create",statusClass:p,attempt:m}))},h=m=>{try{this.telemetryHooks?.onRetry?.("session_create",m),this.directTelemetry?.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:m})}catch{}};for(let m=0;m<3;m++){i.attempt=m;let f=this.telemetryTimestamp();try{l?.onAttempt?.(m)}catch{}try{a=await fetch(`${this.baseUrl}/v1/checkouts/sessions?expand=true`,{method:"POST",headers:o,body:JSON.stringify(e),signal:n})}catch(v){if(i.statusClass=n.aborted||v instanceof Error&&v.name==="AbortError"?"timeout":"network_error",n.aborted||v instanceof Error&&v.name==="AbortError"||m>=2)throw v;let C=m+1;h(C),await ee(m,n);continue}let p=(0,d.telemetryStatusClass)(a.status);if(i.statusClass=p,a.status===204)throw u(m,f,p),new d.FloPayError("Session auto-completed \u2014 payment method already on file","api_error",{code:"session_auto_completed"});if(a.ok){u(m,f,p);break}let y=await L(a,"Failed to create checkout session");if(y.code===d.IDEMPOTENCY_IN_PROGRESS_CODE&&m<2){h(m+1),await ee(m,n);continue}throw u(m,f,p),y}if(!a)throw new TypeError("Checkout-session creation exhausted its retry budget.");return a}async createDetachedSession(e){this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp(),n=U(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(C){throw n.clear(),this.reportSessionCreateFailure(C,t,i),C}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{ut(e,s,o)}catch(C){throw n.clear(),this.reportSessionCreateFailure(C,t,i),C}let a,c,l=!1;try{let C=await this.postCheckoutSessionCreate(kr(e,s),e,n.signal,i);if(l=!0,c=await C.json(),!c.data||!("gateways"in c.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(c.data)),c.vault&&a.data.session&&(a.data.session.vault=this.toVaultBlock(c.vault))}catch(C){throw n.clear(),l&&(0,d.markSessionResponseReceived)(C),this.reportSessionCreateFailure(C,t,i),C}let u=a.data.session?.id??c.data.uuid??"",h=a.data.session?.clientSecret??c.data.nonce??"";if(!u||!h){n.clear();let C=new d.FloPayError("Checkout session shell was created without a session id or nonce.","api_error",{code:"InvalidCheckoutSessionResponse"});throw this.reportSessionCreateFailure(C,t,i),C}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 m=!e.account.email?.trim(),f=U(e.timeoutMs??12e3),p=this.claimCheckoutSession(u,h,m?Er(e,s,o):ut(e,s,o),{params:e,startedAt:t,deadline:f,createAttempt:i.attempt}),y=m?void 0:p,v=(C={})=>{if(y!==void 0)return y;let _={...e,account:{...e.account,...C,email:C.email?.trim()||e.account.email?.trim()}};return(0,d.isValidEmail)(_.account.email)?(y=p.then(()=>{let g=this.telemetryTimestamp();return this.claimCheckoutSession(u,h,Mr(_.account),{params:_,startedAt:g,deadline:U(e.timeoutMs??12e3),createAttempt:0})}),y.catch(()=>{}),y):Promise.reject(new d.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}))};return p.catch(()=>{}),{shell:a,sessionId:u,nonce:h,claimed:p,claim:v}}async claimCheckoutSession(e,t,n,i){let o=i?.startedAt??this.telemetryTimestamp(),s=this.telemetryTimestamp(),a=i?.deadline??U(12e3),c=JSON.stringify(n),l="unknown",u=0,h=!1;this.directTelemetry?.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"});try{let m;for(u=0;u<3;u++){try{m=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},body:c,signal:a.signal})}catch(y){let v=a.signal.aborted||y instanceof Error&&y.name==="AbortError";if(l=v?"timeout":"network_error",v||u>=2)throw y;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 ee(u,a.signal);continue}if(l=(0,d.telemetryStatusClass)(m.status),m.ok)break;throw await L(m,"Failed to attach checkout session data")}if(!m)throw new TypeError("Checkout-session claim exhausted its retry budget.");h=!0;let f=await m.json();if(!f.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(f.data.uuid??e,i.params);let p=this.normalizeRawSession(this.mergeCachedDisplayData(f.data));return f.vault&&p.data.session&&(p.data.session.vault=this.toVaultBlock(f.vault)),this.directTelemetry?.log({name:"session.claim.completed",stage:"session_claim",requestCategory:"session_claim",statusClass:l}),this.directTelemetry?.performance({stage:"session_claim",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"session_claim",statusClass:l,attempt:u}),this.directTelemetry?.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:l}),this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"session_create",statusClass:l,attempt:i?.createAttempt??u}),p}catch(m){throw h&&(0,d.markSessionResponseReceived)(m),this.reportSessionCreateFailure(m,s,{attempt:u,statusClass:l},"session_claim"),m}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&&ct(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,c=!1,l,u=setTimeout(()=>{l=setTimeout(()=>{c=!0,a.abort()},at)},o),h=()=>a.abort(t?.signal?.reason);t?.signal?.aborted?h():t?.signal?.addEventListener("abort",h,{once:!0});let m=this.clampRetryAfterMs(t?.initialDelayMs??ot),f=0;try{if(t?.statusUrl){let p=await this.waitForCheckoutStatus(e,{initialDelayMs:m,timeoutMs:o,nonce:t.nonce,statusUrl:t.statusUrl,pollAfterAction:t.continueAfterActionRequired,signal:a.signal});if(p){let y=await this.resolveCheckoutSessionStatus(e,p,t.nonce,a.signal,()=>c);return this.reportRecoveryCompleted(n,i,t.challengeAttemptId),y}}for(;;){let p=s-Date.now();if(p<=0)throw D();if(m>0){try{f+=1,this.telemetryHooks?.onRetry?.("session_read",f),this.directTelemetry?.log({name:"operation.retry",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:i,attempt:f})}catch{}if(await Le(Math.min(m,p),a.signal),Date.now()>=s)throw D()}let y=await this.getUnifiedCheckoutSessionForRecovery(e,t?.nonce,a.signal),v=y.data.session?.status;if(v==="authorized"||v==="complete"||v==="expired")return this.reportRecoveryCompleted(n,i,t?.challengeAttemptId),y;if(Date.now()>=s)throw D();m=this.clampRetryAfterMs(Math.max(m*2,st))}}catch(p){let y=c&&qe(p)?D():p;throw this.reportDirectFailure(y,"RECOVERY_FAILED","recovery","session_read",i),y}finally{clearTimeout(u),clearTimeout(l),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 l=s.code===d.STORED_PAYMENT_METHOD_UNSUPPORTED_CODE;throw new d.FloPayError(l?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 ur("Payment could not be completed. Please try again.",s?.code??"payment_processing_error");let a;try{a=await this.getUnifiedCheckoutSessionForRecovery(e,n,i)}catch(l){if(!o?.()||!qe(l))throw l;a={providers:[],mode:"tokenize",data:{},raw:t}}let c=a.data.session;return c&&s?.result==="SUCCESS"?{...a,data:{...a.data,session:{...c,status:"complete"}}}:c&&s?.result==="AUTHORIZED"?{...a,data:{...a.data,session:{...c,status:"authorized",paymentId:t.paymentId??void 0,authorizationExpiresAt:t.authorizationExpiresAt??void 0}}}:c&&t.status==="completed"?{...a,data:{...a.data,session:{...c,status:"complete"}}}:c&&t.status==="authorized"?{...a,data:{...a.data,session:{...c,status:"authorized",paymentId:t.paymentId??void 0,authorizationExpiresAt:t.authorizationExpiresAt??void 0}}}:c&&t.status==="expired"?{...a,data:{...a.data,session:{...c,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 Le(Math.min(o,s),t.signal),Date.now()>=i))throw D();let a=i-Date.now();if(a<=0)throw D();let c=new AbortController,l,u=t.signal?new Promise((_,g)=>{l=g}):null,h=()=>{c.abort(t.signal?.reason),l?.(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 m,f=t.signal?null:new Promise((_,g)=>{m=setTimeout(()=>{g(D()),c.abort()},a+at)}),p;try{let _=this.fetchCheckoutStatus(e,t.nonce,t.statusUrl,c.signal);p=await Promise.race([_,f,u].filter(g=>g!==null))}finally{m!==void 0&&clearTimeout(m),t.signal?.removeEventListener("abort",h)}if(!p)return null;let y=it(p.latestTransactionAttempt)&&!this.isOwnFailedAttempt(e,p,t.submittedIntentId);if(p.status==="completed"||p.status==="authorized"||p.status==="expired"||p.status==="voided")return y?{...p,latestTransactionAttempt:null}:p;let v=p.latestTransactionAttempt?.result,C=t.pollAfterAction===!0&&v==="ACTION_REQUIRED";if(!y&&v!==void 0&&v!=="PENDING"&&!C)return p;o=this.clampRetryAfterMs(Math.max(o*2,st))}}isOwnFailedAttempt(e,t,n){let i=t.latestTransactionAttempt?.providerIntentId??null;return n!==void 0?i===n:i===null?!0:!hr(t.uuid||e,i)}rememberReportedFailure(e,t){let n=t.latestTransactionAttempt;!it(n)||!n.providerIntentId||yr(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 c=await ke(s,{headers:a,signal:i});if(c.status===404||c.status===405)return null;if(!c.ok)throw await L(c,"Failed to get checkout session status");let l=await c.json();return me(l.data)&&"latestTransactionAttempt"in l.data?l.data:null}normalizeRawSession(e){let t=e.gateways??{},n=[],i={session:this.toCheckoutSession(e)},o=t.stripe;if(o?.publishableKey){n.push("stripe");let c=[e.stripeClientSecret,o.stripeClientSecret].find(l=>typeof l=="string"&&l.length>0);i.stripe={clientSecret:c??"",publishableKey:o.publishableKey??void 0,paypalPublishableKey:o.paypalPublishableKey??void 0,environment:o.environment,enabledPaymentMethods:Array.isArray(o.enabledPaymentMethods)?o.enabledPaymentMethods.filter(l=>typeof l=="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((l,u)=>l+(u.overrideAmount??u.totalAmount??0),0),o=n?e.totalAmount:i,s=Math.round(o*100),a=e.currency??t[0]?.currency??"USD",c="payment";return e.checkoutMode==="setup"?c="setup":t.some(l=>l.type==="subscription")&&(c="subscription"),{id:e.uuid,clientSecret:e.nonce,mode:c,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}:{},...sr(e.futureUse)?{futureUse:e.futureUse}:{},...Array.isArray(e.futureUseUnsupported)?{futureUseUnsupported:e.futureUseUnsupported.filter(ar)}:{},buyerIdentified:e.buyerIdentified,providerPaymentMethodId:typeof e.providerPaymentMethodId=="string"?e.providerPaymentMethodId:null,products:t.map(l=>({...l,totalAmount:typeof l.totalAmount=="number"?l.totalAmount:void 0,overrideAmount:typeof l.overrideAmount=="number"?l.overrideAmount:null,currency:typeof l.currency=="string"?l.currency:void 0,metadata:l.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=_r(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={[cr]:dr},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,c=a?.code===d.STORED_PAYMENT_METHOD_UNSUPPORTED_CODE,l=a?.declineReason??void 0;return new Response(JSON.stringify({type:l??"authorization_declined",message:c?d.STORED_PAYMENT_METHOD_UNSUPPORTED_MESSAGE:"Payment was declined. Please choose another payment method.",code:a?.code??l??"authorization_declined",...l?{declineCode:l}:{}}),{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:lr(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(c){if(this.reportDirectFailure(c,"RECOVERY_FAILED","recovery","session_read",t?.paymentMethodCategory??"saved"),c instanceof d.FloPayError&&c.code==="checkout_processing_timeout")throw c}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:H(e,"sessionId")??n,retryAfterMs:this.clampRetryAfterMs(Tr(e,"retryAfterMs")??s??ot),statusUrl:H(e,"statusUrl"),sessionUrl:H(e,"sessionUrl")}}clampRetryAfterMs(e){return Math.max(0,Math.min(e,fr))}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);Y(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),c=a?n.get(a):void 0;return{...s,name:s.name??c?.name??null,totalAmount:s.totalAmount??c?.totalAmount,overrideAmount:s.overrideAmount??c?.overrideAmount,currency:s.currency??c?.currency}});return{...e,currency:e.currency??t?.currency,products:o}}};J.activeVaultCaptureRequests=new Map;var pe=J;function yt(r,e){let t=pe;return new t(r,e)}var S=require("@flopay/shared");var Ie=require("@flopay/shared");function gt(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 Me=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,Ie.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=gt(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=gt(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,Ie.invokeMerchantCallback)(()=>t(e))}};var Ir=4,Pe="flopay-vault",Pr=3e4,Dr=S.THREE_DS_CHALLENGE_WINDOW_MS+Pr,Fr="Card authentication timed out.",ft={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 xr(r){return r.class==="lifecycle"?r.name:r.class==="technical_error"?r.code:r.class==="expected_outcome"?r.outcome:"sdk.performance"}function re(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:xr(r),data:e})}catch{}}function he(r,e){return(0,S.buildTelemetryLogEvent)({eventId:"11111111-1111-4111-8111-111111111111",name:r,stage:e,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}var Or=new Set(["authorization_declined","authentication_required","authorization_expired","capture_failed"]);function Ur(r){return typeof r=="string"&&Or.has(r)?r:"unknown"}var qr=new Set(["verification_failed","verification_expired"]);function Lr(r){return r==null?!0:typeof r=="string"&&qr.has(r)}var Nr="vault_mount";function Br(r){return r.failureStage===Nr}function Be(r,e){return r&&!Br(e)?{errorCode:"VAULT_SUBMIT_FAILED",stage:"vault_submit",failureCategory:"provider_runtime",reason:Ur(e.failureOutcome)}:{errorCode:"VAULT_LOAD_FAILED",stage:"vault_mount",failureCategory:"provider_runtime"}}function Ct(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 Vr(r,e,t,n="checkout"){let{type:i}=r;if(i==="complete"||i==="decline")return(0,S.buildTelemetryTerminalEvent)({eventId:"22222222-2222-4222-8222-222222222222",outcome:Ct(r,t,n),sequence:0,provider:"pcivault",paymentMethodCategory:"card"});if(i==="error"){let a=Be(e,r);return(0,S.buildTelemetryErrorEvent)({eventId:"33333333-3333-4333-8333-333333333333",...a,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}let[o,s]=ft[i];return he(o,s)}function zr(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===Pe&&(e.type==="ready"||e.type==="submitting"||e.type==="blocked"||e.type==="complete"||e.type==="decline"||e.type==="error"||e.type==="action_required")}function jr(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 Hr(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 Kr(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===Pe&&e.type==="validation"&&Array.isArray(e.messages)}function $r(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===Pe&&e.type==="resize"&&typeof e.height=="number"&&Number.isFinite(e.height)}function Gr(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===Pe&&e.type==="fields_interactive"}function Yr(r){let e=r.capabilities;return Array.isArray(e)&&e.includes("fields_interactive")}var Wr=["number","expiry","cvv","name"];function Jr(r){if(r===null||typeof r!="object")return;let e=r,t={};for(let n of Wr){let i=e[n];typeof i=="string"&&(t[n]=i)}return t}var Q=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.messageToken=null;this.expectedOrigin=null;this.theme=void 0;this.submitGateBlocked=!1;this.cardFieldOrder=null;this.cardAutoFocus=!0;this.cardBrandIcons=!1;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 Me({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,S.resolveBillingApiUrl)(e.billingApiUrl),sdkVersion:S.SDK_VERSION}):void 0)}async mount(e,t){this.ownsTelemetryReporter&&!this.telemetryReporter&&(this.telemetryReporter=new A({billingApiUrl:(0,S.resolveBillingApiUrl)(this.config.billingApiUrl),sdkVersion:S.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 S.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 S.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.postCardFieldPlaceholders(),this.postSubmitLabel(),re(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($r(n)){if(this.messageToken&&n.messageToken!==this.messageToken)return;this.applyHeight(n.height);return}if(Kr(n)){if(this.messageToken&&n.messageToken!==this.messageToken)return;let l=n.messages.filter(u=>typeof u=="string"&&u.trim()).join(" ");this.emit("validation",{sessionId:this.config.sessionId,message:l||void 0});return}if(Gr(n)){if(this.messageToken&&n.messageToken!==this.messageToken)return;let l=typeof n.sessionId=="string"?n.sessionId:void 0;if(this.config.sessionId&&l&&l!==this.config.sessionId)return;this.cardFields.ready();return}if(!zr(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=Hr(n.paymentMethod),a=jr(n.vaultOutcome),c={...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)?(re(he("operation.state_transition","vault_mount")),this.telemetryReporter?.log({name:"operation.state_transition",stage:"vault_mount",provider:"pcivault",paymentMethodCategory:"card"})):(re(Vr(n,this.submissionStarted,this.config.captureMethod,this.config.operation)),this.reportOutcome(n),n.type==="error"&&Be(this.submissionStarted,n).errorCode==="VAULT_LOAD_FAILED"&&this.cardFields.fail("load_error")),n.type==="ready"&&(this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),this.postCardBrandIcons(),this.postCardFieldPlaceholders(),this.postSubmitLabel(),Yr(n)||this.cardFields.ready()),n.type==="action_required"&&n.nextActionRedirectUrl&&this.showActionRequiredOverlay(n.nextActionRedirectUrl),(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,c)};this.messageHandler=e,window.addEventListener("message",e)}isVerificationStateError(e){return e.type==="error"&&this.verificationRequired&&!this.submissionStarted&&Lr(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:Ct(e,this.config.captureMethod,this.config.operation),provider:"pcivault",paymentMethodCategory:"card"});return}if(n==="error"){let s=Be(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]=ft[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()}setCardFieldPlaceholders(e){let t=Jr(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 p=this.actionOverlay.querySelector("iframe");p instanceof HTMLIFrameElement&&p.src!==e&&(p.src=e),this.armActionRequiredTimeout();return}this.actionOverlayPreviousFocus=document.activeElement instanceof HTMLElement?document.activeElement:null;let t=ce(this.beginActionChallengeAttempt()),n=Se(e),i=!1,o=p=>{if(i)return;let y=_e(p,n);y&&(i=!0,t.record("policy_violation",{reason:y,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"),de(e)==="invalid"&&t.record("action_invalid",{reason:"invalid_url"}),document.addEventListener("securitypolicyviolation",o),window.addEventListener("pagehide",s);let c=document.createElement("div");c.setAttribute("data-flopay-action-required","1"),c.setAttribute("role","dialog"),c.setAttribute("aria-modal","true"),c.setAttribute("aria-label","Card authentication"),c.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 l=document.createElement("iframe");l.setAttribute("title","Card authentication"),l.setAttribute("allow","payment"),l.tabIndex=0,l.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(";"),l.addEventListener("load",()=>{a.loaded||(a.loaded=!0,t.record("iframe_load",{evidenceBasis:"iframe_load_event"}))}),l.src=e,c.appendChild(l);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()),c.appendChild(u),c.addEventListener("click",p=>{p.target===c&&this.abandonActionRequiredOverlay()});let h=0,m=p=>{let y=p.data,v=!!y&&typeof y=="object"&&y.source==="flopay-vault-3ds-return";if(p.source!==l.contentWindow){v&&h<Ir&&(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"}),re(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",m),this.threeDsReturnHandler=m,t.record("render_attempted");try{document.body.appendChild(c)}catch(p){throw t.record("render_failed"),this.hideActionRequiredOverlay(),this.actionOverlayPreviousFocus=null,p}t.record("container_attached"),t.record("navigation_assigned");let f=be(c);f&&t.record("container_visibility",{reason:f,evidenceBasis:"parent_computed_style"}),this.actionOverlay=c,l.focus(),this.armActionRequiredTimeout(),re(he("vault.three_ds.handoff","three_ds_handoff"))}armActionRequiredTimeout(){this.actionOverlayTimer&&clearTimeout(this.actionOverlayTimer),this.actionOverlayTimer=setTimeout(()=>{this.actionOverlayTimer=null,this.actionOverlay&&this.timeOutActionRequiredOverlay()},Dr)}reportChallengeAbandoned(){re((0,S.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.hideActionRequiredOverlay(),this.emit("error",{...this.config.sessionId?{sessionId:this.config.sessionId}:{},message:Fr})}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.hideActionRequiredOverlay(),this.emit("challenge_dismissed",{...this.config.sessionId?{sessionId:this.config.sessionId}:{}})}}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.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 vt(r,e){let t=Q;return new t(r,{reporter:e})}var Tt=Symbol.for("@flopay/js.telemetry.bridge.v1");function bt(r,e,t){let n=()=>e?.now()??t();Object.defineProperty(r,Tt,{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 _t(r){return r[Tt]}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}),bt(this,this.telemetryReporter,E)}cardCapture(e){return this.telemetryReporter?.log({name:"vault.capture.requested",stage:"vault_request",provider:"pcivault",paymentMethodCategory:"card"}),this.telemetryReporter?vt({sessionId:e?.sessionId,captureMethod:e?.captureMethod,cardFieldsTimeoutMs:e?.cardFieldsTimeoutMs},this.telemetryReporter):new Q({sessionId:e?.sessionId,captureMethod:e?.captureMethod,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=l=>{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:l,attempt:h}),this.telemetryReporter?.performance({stage:"session_first_byte",durationMs:u,durationMode:"machine",requestCategory:"session_read",statusClass:l,attempt:h})},c=yt(n,{now:()=>this.telemetryReporter?.now()??E(),onFirstByte:(l,u)=>{o=l,s=u},onRetry:(l,u)=>{this.telemetryReporter?.log({name:"operation.retry",stage:l==="session_read"?"session_read":"processing",requestCategory:l,attempt:u})}});try{let l=await c.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"}),l}catch(l){let u=(0,M.classifyTelemetryFailure)(l,l instanceof M.FloPayError&&l.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}),l}}getRawProvider(){return this.provider.getRawProvider()}destroy(){this.telemetryReporter?.log({name:"checkout.unmount",stage:"unmount"}),this.telemetryReporter?.destroy(),this.provider.destroy()}};function St(r,e,t){let n=ye;return new n(r,e,t)}var N=require("@flopay/shared");var Ve=require("@flopay/shared"),wt=require("@stripe/stripe-js"),ie=require("@flopay/shared"),Rt=new WeakSet;function At(r){return r instanceof Ve.FloPayError&&Rt.has(r)}var ne=class{constructor(){this.name="stripe";this.stripe=null}async initialize(e){if(typeof window>"u")return;let t=await(0,wt.loadStripe)(e.publishableKey,{locale:e.locale??"auto"});if(!t){let n=new Ve.FloPayError("Failed to initialize Stripe. Check your publishable key.","authentication_error");throw Rt.add(n),n}this.stripe=t}getRawProvider(){return this.stripe}destroy(){this.stripe=null}};var kt=new Map;function ze(r){return Array.isArray(r)?r.map(ze):r&&typeof r=="object"?Object.fromEntries(Object.entries(r).filter(([,e])=>e!==void 0).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,ze(t)])):r}function Qr(r,e){return JSON.stringify([r,(0,N.resolveBillingApiUrl)(e?.billingApiUrl),e?.telemetry!==!1,e?.locale??"auto",e?.apiVersion??null,ze(e?.appearance??null)])}var De=new Map;async function Et(r,e){if(!r){let a=new A({billingApiUrl:(0,N.resolveBillingApiUrl)(e?.billingApiUrl),sdkVersion:N.SDK_VERSION,enabled:e?.telemetry!==!1});throw a.error({errorCode:"CONFIGURATION_INVALID",stage:"sdk_initialize",paymentMethodCategory:"unknown"}),a.flush().catch(()=>{}).finally(()=>a.destroy()),new N.FloPayError("A publishable key is required to initialize FloPay.","validation_error",{param:"publishableKey"})}let t=Qr(r,e),n=kt.get(t);if(n)return e?.telemetry!==!1&&_t(n)?.log({name:"sdk.cache.hit",stage:"sdk_initialize"}),n;let i=De.get(t);if(i)return i;let o={...e,publishableKey:r},s=(async()=>{let a=new A({billingApiUrl:(0,N.resolveBillingApiUrl)(o.billingApiUrl),sdkVersion:N.SDK_VERSION,enabled:o.telemetry!==!1}),c=a.now();a.log({name:"sdk.initialize.started",stage:"sdk_initialize"}),a.log({name:"sdk.cache.miss",stage:"sdk_initialize"}),a.log({name:"provider.load.started",stage:"provider_load",provider:"stripe"});let l=new ne,u=a.now();try{await l.initialize(o)}catch(f){throw a.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:At(f)?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"unknown"}),a.destroy(),f}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-c,durationMode:"machine",provider:"stripe"}),a.performance({stage:"provider_ready",durationMs:h-u,durationMode:"machine",provider:"stripe"});let m=St(l,o,a);return kt.set(t,m),m})();De.set(t,s);try{return await s}finally{De.get(t)===s&&De.delete(t)}}var K=require("@flopay/shared");var Xr=4,Zr=1e3,en=1e3,tn=15e3;function rn(r){let e=!!r?.gateways?.stripe,t=!!r?.gateways?.worldpayCorporateGateway;return e===t?"unknown":e?"stripe":"worldpay"}function It(r,e,t){try{return typeof r?.beginThreeDsChallenge!="function"?void 0:r.beginThreeDsChallenge(e,{provider:rn(t)})}catch{return}}function ge(r){return new K.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:r})}function Pt(){return new K.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function Dt(r){return r.replace(/\/+$/,"")}function nn(r){return r.status==="succeeded"||r.status==="authorized"||r.status==="declined"}function on(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 je(r){if(typeof document>"u"||typeof window>"u")throw new K.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});let e=ce(r.telemetry);e.record("handoff_planned");let t=de(r.nextActionRedirectUrl);t==="missing"?e.record("action_missing",{reason:"missing_url"}):t==="invalid"&&e.record("action_invalid",{reason:"invalid_url"});let n=p=>{let y=$e(p);if(y==="buyer_cancel"){e.record("cancel_requested",{reason:y,evidenceBasis:"signal_reason"}),e.terminal("cancel",{reason:y,evidenceBasis:"signal_reason"});return}e.record("abort_observed",{reason:y,evidenceBasis:"signal_reason"}),e.terminal("abort",{reason:y,evidenceBasis:"signal_reason"})},i=p=>{(p.status==="succeeded"||p.status==="authorized"||p.status==="declined"||p.status==="timeout")&&e.reconcile(p.status)};if(r.signal?.aborted)throw n(r.signal.reason),ge();let o=`${Dt(r.billingApiUrl)}/v1/checkouts/sessions/${encodeURIComponent(r.sessionId)}/3ds/complete`,s=async()=>{let p=new AbortController,y=()=>p.abort();r.signal?.aborted?p.abort():r.signal?.addEventListener("abort",y);let v=window.setTimeout(()=>p.abort(),tn);try{let C=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:p.signal});if(!C.ok)return{status:"unknown"};let _=await C.json().catch(()=>null),g=on(_);return i(g),g}catch{return{status:"unknown"}}finally{window.clearTimeout(v),r.signal?.removeEventListener("abort",y)}},a,c=()=>r.pollCompletionEndpoint!==!1?s():(a??(a=s()),a),l=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 m=null;try{m=new URL(r.billingApiUrl,window.location.href).origin}catch{m=null}let f=Se(r.nextActionRedirectUrl);try{let p=await new Promise((y,v)=>{let C=!1,_=0,g=0,F=0,$=!1,B=!1,x=!1,I=0,R=()=>{window.clearTimeout(_),window.clearInterval(g),window.clearTimeout(F),window.removeEventListener("message",P),window.removeEventListener("pagehide",oe),document.removeEventListener("securitypolicyviolation",O),h.removeEventListener("load",G),r.signal?.removeEventListener("abort",se)},X=async()=>{if(!(C||$)){$=!0;try{let w=await c();if(C||!nn(w))return;C=!0,R(),e.terminal("status_poll",{evidenceBasis:"server_status"}),y(w)}finally{$=!1}}},oe=()=>{e.record("pagehide_observed",{evidenceBasis:"page_lifecycle_event"})},O=w=>{if(x)return;let b=_e(w,f);b&&(x=!0,e.record("policy_violation",{reason:b,evidenceBasis:"parent_csp_event"}))},G=()=>{B||(B=!0,e.record("iframe_load",{evidenceBasis:"iframe_load_event"})),r.pollCompletionEndpoint!==!1&&(window.clearTimeout(F),F=window.setTimeout(()=>{X()},250))},se=()=>{C||(C=!0,R(),n(r.signal?.reason),v(ge()))},V=w=>{C||I>=Xr||(I+=1,e.record("return_rejected",{reason:w,evidenceBasis:"message_origin_check"}))},P=w=>{let b=w.data,z=!!b&&typeof b=="object"&&b.source==="flopay-vault-3ds-return";if(w.source!==h.contentWindow){z&&V("untrusted_source");return}if(m&&w.origin!==m){z&&V("untrusted_origin");return}z&&(C||(C=!0,R(),e.record("trusted_return",{evidenceBasis:"message_origin_check"}),e.terminal("trusted_return",{evidenceBasis:"message_origin_check"}),y(null)))};_=window.setTimeout(()=>{C||(C=!0,R(),B||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(Pt()))},K.THREE_DS_CHALLENGE_WINDOW_MS),r.pollCompletionEndpoint!==!1&&(g=window.setInterval(()=>{X()},en)),h.addEventListener("load",G),window.addEventListener("message",P),window.addEventListener("pagehide",oe),document.addEventListener("securitypolicyviolation",O),r.signal?.addEventListener("abort",se),h.src=r.nextActionRedirectUrl,e.record("render_attempted");try{u.appendChild(h),document.body.appendChild(u)}catch(w){throw C=!0,R(),e.record("render_failed"),w}e.record("container_attached"),e.record("navigation_assigned");let Z=be(u);Z&&e.record("container_visibility",{reason:Z,evidenceBasis:"parent_computed_style"}),h.focus(),r.signal?.aborted&&se()});return p||await c()}finally{u.parentNode?.removeChild(u),e.record("teardown"),l?.isConnected&&l.focus()}}function Mt(r,e){try{let t=e.data.session?.status;t==="complete"?r.reconcile("succeeded"):t==="authorized"&&r.reconcile("authorized")}catch{}}function sn(r){return new K.FloPayError("Card was declined.","api_error",{code:r.declineReason??"authorization_declined",...r.gatewayDeclineReason?{declineCode:r.gatewayDeclineReason}:{}})}async function Ft(r,e){let t=`${Dt(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=ce(r.telemetry),a=je({billingApiUrl:r.billingApiUrl,sessionId:r.sessionId,nonce:r.nonce,nextActionRedirectUrl:r.nextActionRedirectUrl,signal:n.signal,pollCompletionEndpoint:!1,...r.telemetry?{telemetry:r.telemetry}:{}}),c=e.waitForCheckoutSessionCompletion(r.sessionId,{initialDelayMs:Zr,nonce:r.nonce,statusUrl:t,continueAfterActionRequired:!0,timeoutMs:K.THREE_DS_CHALLENGE_WINDOW_MS+15e3,signal:i.signal,...s.attemptId?{challengeAttemptId:s.attemptId}:{}});c.catch(()=>{}),a.catch(()=>{});try{let l=await Promise.race([a,c]);if("data"in l)return s.terminal("status_poll",{evidenceBasis:"server_status"}),Mt(s,l),l;if(l.status==="declined")throw(r.createDeclineError??sn)(l);if(l.status==="timeout")throw Pt();let u=await c;return Mt(s,u),u}catch(l){throw r.signal?.aborted||l instanceof Error&&l.name==="AbortError"?ge(l):l}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,loadFloPay,runSavedCardChallenge,toStripeAppearance,toStripeAppearanceTheme});
|