@flopay/js 1.14.15 → 1.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/dist/card-setup.cjs +1 -1
- package/dist/card-setup.mjs +1 -1
- package/dist/chunk-QFFZVSUD.mjs +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.mjs +1 -1
- package/dist/payment-api.d.ts +12 -1
- package/package.json +2 -2
- package/dist/chunk-2ZB6JO3E.mjs +0 -1
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var Ie=Object.defineProperty;var It=Object.getOwnPropertyDescriptor;var Pt=Object.getOwnPropertyNames;var Dt=Object.prototype.hasOwnProperty;var xt=(r,e)=>{for(var t in e)Ie(r,t,{get:e[t],enumerable:!0})},Ot=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Pt(e))!Dt.call(r,o)&&o!==t&&Ie(r,o,{get:()=>e[o],enumerable:!(n=It(e,o))||n.enumerable});return r};var Ft=r=>Ot(Ie({},"__esModule",{value:!0}),r);var Yr={};xt(Yr,{FloPay:()=>ye,PaymentAPI:()=>pe,PciVaultCardCapture:()=>Q,SESSION_CREATE_TELEMETRY:()=>Ue,StripeAdapter:()=>ne,beginSavedCardChallengeTelemetry:()=>Rt,cacheSessionDisplayData:()=>Y,clearSessionDisplayData:()=>Te,completeSavedCardNextAction:()=>Et,createCheckoutSession:()=>Je,createCheckoutSessionWithRetries:()=>et,createSavedCardActionAbortedError:()=>ge,dropThirdPartyOnlyError:()=>Mt.dropThirdPartyOnlyError,getSessionDisplayData:()=>ve,loadFloPay:()=>St,runSavedCardChallenge:()=>Be,toStripeAppearance:()=>oe.toStripeAppearance,toStripeAppearanceTheme:()=>oe.toStripeAppearanceTheme});module.exports=Ft(Yr);var Mt=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 Ut(){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 a,s=()=>e.removeEventListener("abort",c),c=()=>{a!==void 0&&clearTimeout(a),s(),i(Ut())};if(e.aborted){c();return}a=setTimeout(()=>{s(),o()},n),e.addEventListener("abort",c,{once:!0})})}var qt="flopay_session_display:";var fe=new Map;function Ce(r){return`${qt}${r}`}function Pe(){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=Pe();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=Pe();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=Pe();if(e)try{e.removeItem(Ce(r))}catch{}}var k=require("@flopay/shared");var De=require("@flopay/shared"),Lt=32,Ve=Symbol.for("@flopay/js.three-ds-challenge.attempts.v1");function Nt(){let r=globalThis,e=r[Ve];if(e instanceof Map)return e;let t=new Map;try{Object.defineProperty(r,Ve,{configurable:!0,enumerable:!1,writable:!1,value:t})}catch{}return t}function Bt(r,e){let t=Nt(),n=t.get(r);if(n)return n;for(;t.size>=Lt;){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 Vt=new Set(["pagehide_observed","cancel_requested","abort_observed","browser_terminal"]),zt=new Set(["teardown","recovery_read_completed","provider_reconciled"]);function ze(r,e={}){let t=(0,De.isThreeDsChallengeAttemptId)(e.attemptId)?e.attemptId.toLowerCase():r.newAttemptId(),n=()=>{try{let s=r.now();return Number.isFinite(s)?s:0}catch{return 0}},o=Bt(t,n());(e.provider==="stripe"||e.provider==="worldpay")&&(o.provider=e.provider);let i=o.provider,a=(s,c)=>{if(o.terminated&&!zt.has(s))return;let l={attemptId:t,phase:s,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,Vt.has(s))}catch{}};return{attemptId:t,record(s,c={}){s==="browser_terminal"||s==="provider_reconciled"||a(s,{reason:c.reason,evidenceBasis:c.evidenceBasis})},terminal(s,c={}){o.terminated||(a("browser_terminal",{terminalSource:s,reason:c.reason,evidenceBasis:c.evidenceBasis}),o.terminated=!0)},reconcile(s){o.reconciled.has(s)||(o.reconciled.add(s),a("provider_reconciled",{providerOutcome:s,evidenceBasis:"provider_fact"}))}}}function ce(r){let e=null;try{e=(0,De.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 je(r){return r==="buyer_cancel"||r==="component_unmount"||r==="navigation"?r:"unspecified"}function be(r){try{if(typeof window>"u"||typeof window.getComputedStyle!="function")return null;for(let e=r;e;e=e.parentElement){let t=window.getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden"||t.visibility==="collapse"||t.opacity==="0")return"hidden"}return"visible"}catch{return null}}function _e(r,e){if(!e)return null;try{let t=r,n=String(t.effectiveDirective||t.violatedDirective||"").trim().split(/\s+/)[0],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 jt="/v1/sdk-telemetry/events",we=16,He=64,Ht=1500,Ke=1e3,Kt=64,$t="00000000-0000-4000-8000-000000000000",Gt={technical_error:8,lifecycle:32,expected_outcome:32,performance:24},Yt=48;function z(){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 Wt(r){try{return new TextEncoder().encode(r).byteLength}catch{return r.length}}function Jt(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(/\/+$/,"")}${jt}`,this.sdkPackage=e.sdkPackage??"@flopay/js",this.sdkVersion=e.sdkVersion,this.correlationId=z(),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:z(),sequence:this.sequence++}))}error(e){if(this.notify({...e,class:"technical_error"}),!this.canCollect())return;let t=(0,k.buildTelemetryErrorEvent)({...this.checkoutContext,...e,eventId:$t,sequence:0}),n=Jt(t),o=this.now();this.pruneReportedFailures(o);let i=this.reportedFailures.get(n);if(i!==void 0&&o>=i&&o-i<Ke){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:z(),sequence:this.sequence++}))}performance(e){this.canCollect()&&this.enqueue((0,k.buildTelemetryPerformanceEvent)({...this.checkoutContext,...e,eventId:z(),sequence:this.sequence++}))}terminal(e){if(this.canCollect()&&(this.enqueue((0,k.buildTelemetryTerminalEvent)({...this.checkoutContext,...e,eventId:z(),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 ze({now:()=>this.now(),newAttemptId:z,emit:(t,n)=>this.recordThreeDsChallenge(t,n)},e)}recordThreeDsChallenge(e,t){if(!this.canCollect()||this.threeDsChallengeCount>=Yt)return;let n=(0,k.buildTelemetryLogEvent)({...this.checkoutContext,...e,name:"three_ds.challenge",stage:"three_ds_handoff",eventId:z(),sequence:this.sequence++});if(!(this.queue.length>=He)){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>=Ke)&&this.reportedFailures.delete(t)}rememberReportedFailure(e,t){for(;this.reportedFailures.size>=Kt;){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>=He||this.eventCounts[e.class]>=Gt[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:z()});if(Wt(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),a=new Promise(c=>{o=setTimeout(()=>{n?.abort(),c(null)},Ht)});await Promise.race([i,a])==="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)}},$e=Symbol.for("@flopay/js.telemetry.reporter-factory.v1"),Ge=globalThis;Ge[$e]===void 0&&Object.defineProperty(Ge,$e,{configurable:!0,enumerable:!1,writable:!1,value:r=>new A(r)});var xe=5,Ye=new WeakSet;function Qt(r){(typeof r=="object"&&r!==null||typeof r=="function")&&Ye.add(r)}function Xt(r){return(typeof r=="object"&&r!==null||typeof r=="function")&&Ye.has(r)}function Zt(r,e){let t=e?.error,n=ae(e?.code)??ae(t?.code)??`http_${r}`,o=le(e?.message)??le(t?.message)??er(n,r);return new T.FloPayError(o,"api_error",{code:n,statusCode:r})}function er(r,e){switch(r){case"CouponLimitExceeded":return`Too many coupon codes \u2014 a checkout session accepts at most ${xe}.`;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 We(r,e,t){let{billingApiUrl:n,checkoutBaseUrl:o,items:i=[],subscriptions:a=[],products:s,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:x,idempotencyKey:$}=r,N=(0,T.resolveIdempotencyKey)($);if(f.length>xe)throw new T.FloPayError(`Too many coupon codes \u2014 a checkout session accepts at most ${xe}.`,"validation_error",{code:"CouponLimitExceeded",param:"couponCodes"});let O=s??(0,T.foldIntoProducts)(i,a);(0,T.assertCaptureMethodEligible)({captureMethod:m,products:O});let I=(0,T.resolveSessionCurrency)(g,i,a,O);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:O.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),x&&x.length>0&&(R.utmMetadata=x);let X=`${n.replace(/\/+$/,"")}/v1/checkouts/sessions`,ie={"Content-Type":"application/json"};N&&(ie[T.IDEMPOTENCY_KEY_HEADER]=N);let F,G,se={method:"POST",headers:ie,body:JSON.stringify(R),signal:e},B;try{t?.startAttempt(),B=await fetch(X,se)}catch(P){throw Qt(P),P}try{t?.record(B.status)}catch{}F=B.status;try{G=await B.json()}catch{}if(F>=400)throw(0,T.withTelemetryHttpDiagnostics)(Zt(F,G),B);if(F===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"});(O.length>0||I)&&Y(P,{currency:I,products:O.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,V]of Object.entries(v))w.searchParams.set(b,V);if(C&&typeof window<"u"&&typeof document<"u"){let b=JSON.stringify({origin_url:u}),V=window.location.hostname.split(".").slice(-2).join(".");document.cookie=`checkout_data=${encodeURIComponent(b)}; domain=.${V}; path=/; max-age=3600; SameSite=Lax; Secure;`,document.cookie=`flopay_checkout_token=${encodeURIComponent(Z)}; domain=.${V}; path=/; max-age=3600; SameSite=Lax; Secure;`}return typeof window<"u"&&(window.location.href=w.toString()),{status:201,redirectUrl:w.toString(),nonce:Z}}return F===204?(typeof window<"u"&&(window.location.href=l),{status:204}):{status:F}}async function Je(r){let e=Xe(r),t=Qe(e),n=U(r.timeoutMs);try{let o=await We(r,n.signal,t);return t.commit(),Ze(e,o),o}catch(o){throw t.commit(),Re(e,o),o}finally{n.clear(),te(e.reporter)}}function Qe(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 Xe(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 Ze(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 et(r){let{maxRetries:e=2,...t}=r,n=Xe(r),o=Qe(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)},a=U(t.timeoutMs),s;for(let c=0;c<=e;c++){n.attempt=c;try{let l=await We(i,a.signal,o);return o.commit(),Ze(n,l),a.clear(),te(n.reporter),l}catch(l){s=l;let u=l instanceof Error&&l.name==="AbortError",h=Xt(l),m=l instanceof T.FloPayError&&l.code===T.IDEMPOTENCY_IN_PROGRESS_CODE;if((u||h||m)&&!a.signal.aborted&&c<e){n.reporter.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:c+1});try{await ee(c,a.signal)}catch(f){throw o.commit(),Re(n,f),a.clear(),te(n.reporter),f}continue}throw o.commit(),Re(n,l),a.clear(),te(n.reporter),l}}throw o.commit(),Re(n,s),a.clear(),te(n.reporter),s??new Error("Unknown error during checkout session creation")}var M=require("@flopay/shared");var d=require("@flopay/shared");function tr(r){return r==="on_session"||r==="off_session"}function rr(r){if(!r||typeof r!="object")return!1;let e=r;return typeof e.paymentMethodType=="string"&&typeof e.reason=="string"}function nr(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 or="x-flopay-process-result-source",ir="status";function tt(r){return r?.result==="DECLINE"||r?.result==="ERROR"}var sr=50,W=new Map;function ar(r,e){return W.get(r)?.has(e)===!0}function lr(r,e){let t=W.get(r)??new Set;if(t.add(e),W.delete(r),W.set(r,t),W.size>sr){let n=W.keys().next().value;n!==void 0&&W.delete(n)}}function cr(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 rt=0,nt=500,Ae=15e3,ot=15e3,dr=3e3,ur=1e4,mr=1e4;function me(r){return typeof r=="object"&&r!==null}function H(r,e){return ae(r?.[e])}function it(r,e){return le(r?.[e])}function pr(r,e){let t=r?.[e];return typeof t=="number"&&Number.isFinite(t)?t:void 0}function Fe(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 Oe(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 j(r,e){let t=await r.json().catch(()=>null),n=me(t?.error)?t.error:null,o=it(t,"message")??it(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 hr(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 yr(r){if(!(!me(r)||typeof r.required!="boolean"))return{required:r.required,provider:"turnstile"}}async function gr(r){let e=r.status===400?await r.clone().json().catch(()=>null):null;return(0,d.classifyPaymentRejection)(r.status,e)}function st(r){return r===400||r===422}var Ee=2;async function ke(r,e,t=Ee,n,o){let i;for(let a=0;;a++)try{return o?.(a),await fetch(r,e)}catch(s){if(e?.signal?.aborted||s instanceof Error&&s.name==="AbortError")throw s;if(i=s,a>=t)throw i;try{n?.(a+1)}catch{}await Fe(150*2**a,e?.signal??void 0)}}var Ue=Symbol.for("@flopay/js.session-create.telemetry.v1");function fr(r){return r[Ue]}function Cr(r){return"now"in r||"onFirstByte"in r||"onSessionCreateFailure"in r||"onRetry"in r}function lt(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 ct(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 vr(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}),ct(t,r),t}function at(r,e,t){return{currency:e,products:t.map(n=>(0,d.buildProductPayload)(n,e)),couponCodes:r.couponCodes??[],accountData:lt(r.account)}}function Tr(r,e,t){return{currency:e,products:t.map(n=>(0,d.buildProductPayload)(n,e)),couponCodes:r.couponCodes??[]}}function br(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=Cr(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 a=(0,d.classifyTelemetryFailure)(e,t);this.directTelemetry?.error({...a,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(),a=i,s=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=>{s=p,a=this.telemetryTimestamp()});l=!0;let h=Math.max(0,this.telemetryTimestamp()-a);try{this.telemetryHooks?.onFirstByte?.(h,s)}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:s}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:h,durationMode:"machine",requestCategory:"session_read",statusClass:m,attempt:s}),!u.ok)throw await j(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(),mr);this.beginDirectTelemetryCheckout(e);let i=this.telemetryTimestamp();this.directTelemetry?.log({name:"vault.capture.requested",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card"});let a={"Content-Type":"application/json"};t&&(a["x-checkout-session-token"]=t);try{let s=await ke(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/vault/capture`,{method:"POST",headers:a,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 hr(s))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(!s.ok)throw await j(s,"Failed to load the secure card form");let c=await s.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(s){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"}):s;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:a,paymentMethodCategory:s,...c}=t,l=cr(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":a},body:JSON.stringify(c)}),h=u}catch(m){if(Oe(m))throw this.reportDirectFailure(m,"PAYMENT_PROCESSING_FAILED","processing","process_payment",o),m;u=await this.reconcileProcessPayment(t.sessionId,{...n,nonce:a,paymentMethodCategory:o,submittedIntentId:l})}if(!u.ok&&u.status!==202){let m=await gr(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:a,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 a=o?.timeoutMs??ur,s=new AbortController,c=()=>s.abort();o?.signal&&(o.signal.aborted?s.abort():o.signal.addEventListener("abort",c,{once:!0}));let l=setTimeout(()=>s.abort(),a);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:s.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 j(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,a=i.paymentMethodType,s=typeof a=="string"&&a.trim().toLowerCase()==="card",c=typeof a=="string"&&a.length>0&&!s&&(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 j(v,"Failed to create checkout intent"),X=(0,d.classifyTelemetryFailure)(R,"PAYMENT_PROCESSING_FAILED");throw st(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=_,x=g.paymentMethodType,$=(g.paymentMethodCategory==="wallet"||g.paymentMethodCategory==="apm")&&typeof x=="string"&&x.trim().toLowerCase()!=="card"&&(typeof g.paymentMethodId=="string"||g.paymentMethodId===null)&&typeof g.providerObjectId=="string",N=g.provider==="stripe"&&(g.intentKind==="payment"||g.intentKind==="setup")&&typeof g.clientSecret=="string",O=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(!$||!N&&!O||!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 a=this.toCheckoutProcessingPending(e,t,n);try{return{settled:!0,response:await this.resolveCheckoutProcessing(a,n,{nonce:o,paymentMethodCategory:i.provider==="paypal"?"paypal":i.paymentMethodCategory})}}catch(s){throw s instanceof d.FloPayError&&s.code==="checkout_processing_timeout"?new d.FloPayError(s.message,s.type,{code:s.code,statusCode:202,sessionId:a.sessionId,cause:s}):s}}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,a=i.providerDeclineReason,s=i.paymentMethodType,c=i.providerIntentId,l=typeof a=="string"&&/^[a-z0-9][a-z0-9_.:-]{0,63}$/i.test(a)&&!/^(?:pm|pi|seti|tok|src|cus|sess|sk|pk)_/i.test(a),u=typeof s=="string"&&s.length>0&&s.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:a}:{provider:"stripe",paymentMethodCategory:i.paymentMethodCategory,paymentMethodType:i.paymentMethodType,providerDeclineReason:a,...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 j(p,"Failed to report checkout decline")}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,a=new URLSearchParams({email:e,page:String(o),limit:String(i),sortField:"createdAt",sortDirection:"DESC"});try{let s=await fetch(`${this.baseUrl}/v1/payments?${a.toString()}`,{method:"GET",signal:t?.signal,keepalive:!0});if(!s.ok)throw(0,d.withTelemetryHttpDiagnostics)(new d.FloPayError("Failed to fetch payments","api_error",{statusCode:s.status}),s);let c=await s.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(s){throw this.reportDirectFailure(s,"RECOVERY_FAILED","recovery","other","saved"),s}}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 a={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:lt(e.account),couponCodes:e.couponCodes??[]};e.captureMethod==="manual"&&(a.captureMethod=e.captureMethod),e.tokenizedData&&(a.tokenizedData=e.tokenizedData),ct(a,e);let s=await this.postCheckoutSessionCreate(a,e,t,n),c=!1;try{let l=await s.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},a=(0,d.resolveIdempotencyKey)(t.idempotencyKey);a&&(i[d.IDEMPOTENCY_KEY_HEADER]=a),t.checkoutMode==="auto"&&(i[d.FLO_SDK_CAPABILITIES_HEADER]=d.ASYNC_AUTO_CHECKOUT_CAPABILITY);let s,c=!1,l=fr(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{s=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)(s.status);if(o.statusClass=p,s.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(s.ok){u(m,f,p);break}let y=await j(s,"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(!s)throw new TypeError("Checkout-session creation exhausted its retry budget.");return s}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 a=(0,d.resolveSessionCurrency)(e.currency,e.items,e.subscriptions,i);if(!a)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{at(e,a,i)}catch(C){throw n.clear(),this.reportSessionCreateFailure(C,t,o),C}let s,c,l=!1;try{let C=await this.postCheckoutSessionCreate(vr(e,a),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"});s=this.normalizeRawSession(this.mergeCachedDisplayData(c.data)),c.vault&&s.data.session&&(s.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=s.data.session?.id??c.data.uuid??"",h=s.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?Tr(e,a,i):at(e,a,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,br(_.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:s,sessionId:u,nonce:h,claimed:p,claim:v}}async claimCheckoutSession(e,t,n,o){let i=o?.startedAt??this.telemetryTimestamp(),a=this.telemetryTimestamp(),s=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:s.signal})}catch(y){let v=s.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,s.signal);continue}if(l=(0,d.telemetryStatusClass)(m.status),m.ok)break;throw await j(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()-a),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,a,{attempt:u,statusClass:l},"session_claim"),m}finally{s.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&&st(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,a=Date.now()+i,s=new AbortController,c=!1,l,u=setTimeout(()=>{l=setTimeout(()=>{c=!0,s.abort()},ot)},i),h=()=>s.abort(t?.signal?.reason);t?.signal?.aborted?h():t?.signal?.addEventListener("abort",h,{once:!0});let m=this.clampRetryAfterMs(t?.initialDelayMs??rt),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:s.signal});if(p){let y=await this.resolveCheckoutSessionStatus(e,p,t.nonce,s.signal,()=>c);return this.reportRecoveryCompleted(n,o,t.challengeAttemptId),y}}for(;;){let p=a-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 Fe(Math.min(m,p),s.signal),Date.now()>=a)throw D()}let y=await this.getUnifiedCheckoutSessionForRecovery(e,t?.nonce,s.signal),v=y.data.session?.status;if(v==="authorized"||v==="complete"||v==="expired")return this.reportRecoveryCompleted(n,o,t?.challengeAttemptId),y;if(Date.now()>=a)throw D();m=this.clampRetryAfterMs(Math.max(m*2,nt))}}catch(p){let y=c&&Oe(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 a=t.latestTransactionAttempt;if(this.rememberReportedFailure(e,t),a?.result==="DECLINE"){let l=a.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:a.code??a.declineReason??"authorization_declined",statusCode:400})}if(a?.result==="ERROR"||t.status==="voided")throw new d.FloPayError("Payment could not be completed. Please try again.","api_error",{code:a?.code??"payment_processing_error",statusCode:500});let s;try{s=await this.getUnifiedCheckoutSessionForRecovery(e,n,o)}catch(l){if(!i?.()||!Oe(l))throw l;s={providers:[],mode:"tokenize",data:{},raw:t}}let c=s.data.session;return c&&a?.result==="SUCCESS"?{...s,data:{...s.data,session:{...c,status:"complete"}}}:c&&a?.result==="AUTHORIZED"?{...s,data:{...s.data,session:{...c,status:"authorized",paymentId:t.paymentId??void 0,authorizationExpiresAt:t.authorizationExpiresAt??void 0}}}:c&&t.status==="completed"?{...s,data:{...s.data,session:{...c,status:"complete"}}}:c&&t.status==="authorized"?{...s,data:{...s.data,session:{...c,status:"authorized",paymentId:t.paymentId??void 0,authorizationExpiresAt:t.authorizationExpiresAt??void 0}}}:c&&t.status==="expired"?{...s,data:{...s.data,session:{...c,status:"expired"}}}:a?.result!=="ACTION_REQUIRED"?s:a.gateway==="paypal"&&a.providerIntentId?{...s,autoProcessingError:{type:"paypal_direct_required",message:"PayPal authorization required",orderId:a.providerIntentId,checkoutMethod:"paypal"}}:a.nextActionRedirectUrl?{...s,autoProcessingError:{type:"3ds_required",message:"Additional authentication is required.",nextActionRedirectUrl:a.nextActionRedirectUrl}}:s}async waitForCheckoutStatus(e,t){let n=t.timeoutMs??Ae,o=Date.now()+n,i=this.clampRetryAfterMs(t.initialDelayMs);for(;;){let a=o-Date.now();if(a<=0||i>0&&(await Fe(Math.min(i,a),t.signal),Date.now()>=o))throw D();let s=o-Date.now();if(s<=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()},s+ot)}),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=tt(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,nt))}}isOwnFailedAttempt(e,t,n){let o=t.latestTransactionAttempt?.providerIntentId??null;return n!==void 0?o===n:o===null?!0:!ar(t.uuid||e,o)}rememberReportedFailure(e,t){let n=t.latestTransactionAttempt;!tt(n)||!n.providerIntentId||lr(t.uuid||e,n.providerIntentId)}async fetchCheckoutStatus(e,t,n,o){let i=`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/status`,a=i;if(n)try{let u=new URL(n,`${this.baseUrl}/`),h=new URL(i);u.origin===h.origin&&(a=u.toString())}catch{}let s={[d.FLO_SDK_VERSION_HEADER]:d.SDK_VERSION};t&&(s["x-checkout-session-token"]=t);let c=await ke(a,{headers:s,signal:o});if(c.status===404||c.status===405)return null;if(!c.ok)throw await j(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 a=t.paypal;return a?.publishableKey&&(n.push("paypal"),o.paypal={publishableKey:a.publishableKey,environment:a.environment,providerObjectType:a.providerObjectType,approvalPresentation:a.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,a=Math.round(i*100),s=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:a,currency:s,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}:{},...tr(e.futureUse)?{futureUse:e.futureUse}:{},...Array.isArray(e.futureUseUnsupported)?{futureUseUnsupported:e.futureUseUnsupported.filter(rr)}:{},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=yr(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 s=await this.waitForCheckoutStatus(e.sessionId,{initialDelayMs:e.retryAfterMs,timeoutMs:o,nonce:n?.nonce,statusUrl:e.statusUrl,submittedIntentId:n?.submittedIntentId});if(s)return this.toProcessResponseFromStatus(s,t,n?.nonce)}let a=await this.waitForCheckoutSessionCompletion(e.sessionId,{initialDelayMs:e.retryAfterMs,timeoutMs:i-Date.now(),nonce:n?.nonce,paymentMethodCategory:n?.paymentMethodCategory});return this.toProcessResponseFromSession(a,t)}async toProcessResponseFromStatus(e,t,n){let o=e.latestTransactionAttempt?.result,i={[or]:ir},a={"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:a});if(e.status==="expired"){let s=await this.resolveCheckoutSessionStatus(t,e,n);return this.toProcessResponseFromSession(s,t)}if(this.rememberReportedFailure(t,e),o==="DECLINE"){let s=e.latestTransactionAttempt,c=s?.code===d.STORED_PAYMENT_METHOD_UNSUPPORTED_CODE,l=s?.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:s?.code??l??"authorization_declined",...l?{declineCode:l}:{}}),{status:400,headers:a})}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:a});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:a});if(o==="ERROR"||e.status==="voided")return new Response(JSON.stringify({type:"unknown",code:e.latestTransactionAttempt?.code??"payment_processing_error",message:nr(e)??"Payment could not be completed. Please try again."}),{status:500,headers:a});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 a=o-Date.now();if(a<=0)throw D();let s=await this.waitForCheckoutSessionCompletion(e,{initialDelayMs:0,timeoutMs:a,nonce:t?.nonce,paymentMethodCategory:t?.paymentMethodCategory});return this.toProcessResponseFromSession(s,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),a=i!==void 0&&Number.isFinite(i)?i*1e3:void 0;return{type:"checkout_processing",sessionId:H(e,"sessionId")??n,retryAfterMs:this.clampRetryAfterMs(pr(e,"retryAfterMs")??a??rt),statusUrl:H(e,"statusUrl"),sessionUrl:H(e,"sessionUrl")}}clampRetryAfterMs(e){return Math.max(0,Math.min(e,dr))}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(a=>({code:a.code??a.providerItemId??a.providerPlanId,type:a.type,name:a.name??a.itemName??a.providerItemName??a.subscriptionName??a.providerPlanName??null,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount,currency:a.currency??i??void 0}))})}mergeCachedDisplayData(e){let t=ve(e.uuid),n=new Map,o=a=>a?`code:${a}`:void 0;for(let a of t?.products??[]){let s=o(a.code);s&&n.set(s,a)}let i=(e.products??[]).map(a=>{let s=o(a.code),c=s?n.get(s):void 0;return{...a,name:a.name??c?.name??null,totalAmount:a.totalAmount??c?.totalAmount,overrideAmount:a.overrideAmount??c?.overrideAmount,currency:a.currency??c?.currency}});return{...e,currency:e.currency??t?.currency,products:i}}};J.activeVaultCaptureRequests=new Map;var pe=J;function dt(r,e){let t=pe;return new t(r,e)}var S=require("@flopay/shared");var _r=4,qe="flopay-vault",Sr=3e4,wr=S.THREE_DS_CHALLENGE_WINDOW_MS+Sr,Rr="Card authentication timed out.",ut={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 Ar(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:Ar(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 kr=new Set(["authorization_declined","authentication_required","authorization_expired","capture_failed"]);function Er(r){return typeof r=="string"&&kr.has(r)?r:"unknown"}var Mr=new Set(["verification_failed","verification_expired"]);function Ir(r){return r==null?!0:typeof r=="string"&&Mr.has(r)}var Pr="vault_mount";function Dr(r){return r.failureStage===Pr}function mt(r,e){return r&&!Dr(e)?{errorCode:"VAULT_SUBMIT_FAILED",stage:"vault_submit",failureCategory:"provider_runtime",reason:Er(e.failureOutcome)}:{errorCode:"VAULT_LOAD_FAILED",stage:"vault_mount",failureCategory:"provider_runtime"}}function pt(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 xr(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:pt(r,t,n),sequence:0,provider:"pcivault",paymentMethodCategory:"card"});if(o==="error"){let s=mt(e,r);return(0,S.buildTelemetryErrorEvent)({eventId:"33333333-3333-4333-8333-333333333333",...s,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}let[i,a]=ut[o];return he(i,a)}function Or(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===qe&&(e.type==="ready"||e.type==="submitting"||e.type==="blocked"||e.type==="complete"||e.type==="decline"||e.type==="error"||e.type==="action_required")}function Fr(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 Ur(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 qr(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===qe&&e.type==="validation"&&Array.isArray(e.messages)}function Lr(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===qe&&e.type==="resize"&&typeof e.height=="number"&&Number.isFinite(e.height)}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.submitLabel=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.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,typeof window>"u"||typeof document>"u")throw this.reportVaultLoadFailure(),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(),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)}catch(o){throw this.reportVaultLoadFailure(),o}this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),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)}}unmount(){if(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 a of Array.from(o.attributes))i.setAttribute(a.name,a.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(Lr(n)){if(this.messageToken&&n.messageToken!==this.messageToken)return;this.applyHeight(n.height);return}if(qr(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(!Or(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 a=Ur(n.paymentMethod),s=Fr(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}:{},...s?{vaultOutcome:s}:{},...a?{paymentMethod:a}:{}};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(xr(n,this.submissionStarted,this.config.captureMethod,this.config.operation)),this.reportOutcome(n)),n.type==="ready"&&(this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),this.postSubmitLabel()),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&&Ir(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:pt(e,this.config.captureMethod,this.config.operation),provider:"pcivault",paymentMethodCategory:"card"});return}if(n==="error"){let a=mt(this.submissionStarted,e);t.log({name:"vault.terminal",stage:a.stage,provider:"pcivault",paymentMethodCategory:"card"}),t.error({...a,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 a=this.submissionStartedAt;this.submissionStartedAt=null,a!==null&&t.performance({stage:"three_ds_handoff",durationMs:Math.max(0,t.now()-a),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:"action_required",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"});return}let[o,i]=ut[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())}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"}))},a=()=>{t.record("pagehide_observed",{evidenceBasis:"page_lifecycle_event"})},s={telemetry:t,loaded:!1,detach:()=>{document.removeEventListener("securitypolicyviolation",i),window.removeEventListener("pagehide",a)}};this.actionChallenge=s,this.lastChallengeTelemetry=t,t.record("handoff_planned"),de(e)==="invalid"&&t.record("action_invalid",{reason:"invalid_url"}),document.addEventListener("securitypolicyviolation",i),window.addEventListener("pagehide",a);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",()=>{s.loaded||(s.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<_r&&(h+=1,t.record("return_rejected",{reason:"untrusted_source",evidenceBasis:"message_origin_check"}));return}v&&(t.record("trusted_return",{evidenceBasis:"message_origin_check"}),t.terminal("trusted_return",{evidenceBasis:"message_origin_check"}),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()},wr)}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:Rr})}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 ht(r,e){let t=Q;return new t(r,{reporter:e})}var yt=Symbol.for("@flopay/js.telemetry.bridge.v1");function gt(r,e,t){let n=()=>e?.now()??t();Object.defineProperty(r,yt,{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 ft(r){return r[yt]}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}),gt(this,this.telemetryReporter,E)}cardCapture(e){return this.telemetryReporter?.log({name:"vault.capture.requested",stage:"vault_request",provider:"pcivault",paymentMethodCategory:"card"}),this.telemetryReporter?ht({sessionId:e?.sessionId,captureMethod:e?.captureMethod},this.telemetryReporter):new Q({sessionId:e?.sessionId,captureMethod:e?.captureMethod,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,a,s=l=>{if(i===void 0)return;let u=i,h=a;i=void 0,a=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=dt(n,{now:()=>this.telemetryReporter?.now()??E(),onFirstByte:(l,u)=>{i=l,a=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 s("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 s(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 Ct(r,e,t){let n=ye;return new n(r,e,t)}var L=require("@flopay/shared");var Le=require("@flopay/shared"),vt=require("@stripe/stripe-js"),oe=require("@flopay/shared"),Tt=new WeakSet;function bt(r){return r instanceof Le.FloPayError&&Tt.has(r)}var ne=class{constructor(){this.name="stripe";this.stripe=null}async initialize(e){if(typeof window>"u")return;let t=await(0,vt.loadStripe)(e.publishableKey,{locale:e.locale??"auto"});if(!t){let n=new Le.FloPayError("Failed to initialize Stripe. Check your publishable key.","authentication_error");throw Tt.add(n),n}this.stripe=t}getRawProvider(){return this.stripe}destroy(){this.stripe=null}};var _t=new Map;function Ne(r){return Array.isArray(r)?r.map(Ne):r&&typeof r=="object"?Object.fromEntries(Object.entries(r).filter(([,e])=>e!==void 0).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,Ne(t)])):r}function Nr(r,e){return JSON.stringify([r,(0,L.resolveBillingApiUrl)(e?.billingApiUrl),e?.telemetry!==!1,e?.locale??"auto",e?.apiVersion??null,Ne(e?.appearance??null)])}var Me=new Map;async function St(r,e){if(!r){let s=new A({billingApiUrl:(0,L.resolveBillingApiUrl)(e?.billingApiUrl),sdkVersion:L.SDK_VERSION,enabled:e?.telemetry!==!1});throw s.error({errorCode:"CONFIGURATION_INVALID",stage:"sdk_initialize",paymentMethodCategory:"unknown"}),s.flush().catch(()=>{}).finally(()=>s.destroy()),new L.FloPayError("A publishable key is required to initialize FloPay.","validation_error",{param:"publishableKey"})}let t=Nr(r,e),n=_t.get(t);if(n)return e?.telemetry!==!1&&ft(n)?.log({name:"sdk.cache.hit",stage:"sdk_initialize"}),n;let o=Me.get(t);if(o)return o;let i={...e,publishableKey:r},a=(async()=>{let s=new A({billingApiUrl:(0,L.resolveBillingApiUrl)(i.billingApiUrl),sdkVersion:L.SDK_VERSION,enabled:i.telemetry!==!1}),c=s.now();s.log({name:"sdk.initialize.started",stage:"sdk_initialize"}),s.log({name:"sdk.cache.miss",stage:"sdk_initialize"}),s.log({name:"provider.load.started",stage:"provider_load",provider:"stripe"});let l=new ne,u=s.now();try{await l.initialize(i)}catch(f){throw s.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:bt(f)?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"unknown"}),s.destroy(),f}let h=s.now();s.log({name:"provider.ready",stage:"provider_ready",provider:"stripe"}),s.log({name:"provider.availability.checked",stage:"provider_ready",provider:"stripe"}),s.log({name:"sdk.initialize.ready",stage:"sdk_initialize"}),s.performance({stage:"sdk_initialize",durationMs:h-c,durationMode:"machine",provider:"stripe"}),s.performance({stage:"provider_ready",durationMs:h-u,durationMode:"machine",provider:"stripe"});let m=Ct(l,i,s);return _t.set(t,m),m})();Me.set(t,a);try{return await a}finally{Me.get(t)===a&&Me.delete(t)}}var K=require("@flopay/shared");var Br=4,Vr=1e3,zr=1e3,jr=15e3;function Hr(r){let e=!!r?.gateways?.stripe,t=!!r?.gateways?.worldpayCorporateGateway;return e===t?"unknown":e?"stripe":"worldpay"}function Rt(r,e,t){try{return typeof r?.beginThreeDsChallenge!="function"?void 0:r.beginThreeDsChallenge(e,{provider:Hr(t)})}catch{return}}function ge(r){return new K.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:r})}function At(){return new K.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function kt(r){return r.replace(/\/+$/,"")}function Kr(r){return r.status==="succeeded"||r.status==="authorized"||r.status==="declined"}function $r(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 Be(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=je(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=`${kt(r.billingApiUrl)}/v1/checkouts/sessions/${encodeURIComponent(r.sessionId)}/3ds/complete`,a=async()=>{let p=new AbortController,y=()=>p.abort();r.signal?.aborted?p.abort():r.signal?.addEventListener("abort",y);let v=window.setTimeout(()=>p.abort(),jr);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=$r(_);return o(g),g}catch{return{status:"unknown"}}finally{window.clearTimeout(v),r.signal?.removeEventListener("abort",y)}},s,c=()=>r.pollCompletionEndpoint!==!1?a():(s??(s=a()),s),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,x=0,$=!1,N=!1,O=!1,I=0,R=()=>{window.clearTimeout(_),window.clearInterval(g),window.clearTimeout(x),window.removeEventListener("message",P),window.removeEventListener("pagehide",ie),document.removeEventListener("securitypolicyviolation",F),h.removeEventListener("load",G),r.signal?.removeEventListener("abort",se)},X=async()=>{if(!(C||$)){$=!0;try{let w=await c();if(C||!Kr(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"})},F=w=>{if(O)return;let b=_e(w,f);b&&(O=!0,e.record("policy_violation",{reason:b,evidenceBasis:"parent_csp_event"}))},G=()=>{N||(N=!0,e.record("iframe_load",{evidenceBasis:"iframe_load_event"})),r.pollCompletionEndpoint!==!1&&(window.clearTimeout(x),x=window.setTimeout(()=>{X()},250))},se=()=>{C||(C=!0,R(),n(r.signal?.reason),v(ge()))},B=w=>{C||I>=Br||(I+=1,e.record("return_rejected",{reason:w,evidenceBasis:"message_origin_check"}))},P=w=>{let b=w.data,V=!!b&&typeof b=="object"&&b.source==="flopay-vault-3ds-return";if(w.source!==h.contentWindow){V&&B("untrusted_source");return}if(m&&w.origin!==m){V&&B("untrusted_origin");return}V&&(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(),N||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(At()))},K.THREE_DS_CHALLENGE_WINDOW_MS),r.pollCompletionEndpoint!==!1&&(g=window.setInterval(()=>{X()},zr)),h.addEventListener("load",G),window.addEventListener("message",P),window.addEventListener("pagehide",ie),document.addEventListener("securitypolicyviolation",F),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 wt(r,e){try{let t=e.data.session?.status;t==="complete"?r.reconcile("succeeded"):t==="authorized"&&r.reconcile("authorized")}catch{}}function Gr(r){return new K.FloPayError("Card was declined.","api_error",{code:r.declineReason??"authorization_declined",...r.gatewayDeclineReason?{declineCode:r.gatewayDeclineReason}:{}})}async function Et(r,e){let t=`${kt(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 a=ce(r.telemetry),s=Be({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:Vr,nonce:r.nonce,statusUrl:t,continueAfterActionRequired:!0,timeoutMs:K.THREE_DS_CHALLENGE_WINDOW_MS+15e3,signal:o.signal,...a.attemptId?{challengeAttemptId:a.attemptId}:{}});c.catch(()=>{}),s.catch(()=>{});try{let l=await Promise.race([s,c]);if("data"in l)return a.terminal("status_poll",{evidenceBasis:"server_status"}),wt(a,l),l;if(l.status==="declined")throw(r.createDeclineError??Gr)(l);if(l.status==="timeout")throw At();let u=await c;return wt(a,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 Pe=Object.defineProperty;var Pt=Object.getOwnPropertyDescriptor;var It=Object.getOwnPropertyNames;var Dt=Object.prototype.hasOwnProperty;var xt=(r,e)=>{for(var t in e)Pe(r,t,{get:e[t],enumerable:!0})},Ot=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of It(e))!Dt.call(r,o)&&o!==t&&Pe(r,o,{get:()=>e[o],enumerable:!(n=Pt(e,o))||n.enumerable});return r};var Ft=r=>Ot(Pe({},"__esModule",{value:!0}),r);var Yr={};xt(Yr,{FloPay:()=>ye,PaymentAPI:()=>pe,PciVaultCardCapture:()=>Q,SESSION_CREATE_TELEMETRY:()=>Ue,StripeAdapter:()=>ne,beginSavedCardChallengeTelemetry:()=>Rt,cacheSessionDisplayData:()=>Y,clearSessionDisplayData:()=>Te,completeSavedCardNextAction:()=>Et,createCheckoutSession:()=>Je,createCheckoutSessionWithRetries:()=>et,createSavedCardActionAbortedError:()=>ge,dropThirdPartyOnlyError:()=>Mt.dropThirdPartyOnlyError,getSessionDisplayData:()=>ve,loadFloPay:()=>St,runSavedCardChallenge:()=>Be,toStripeAppearance:()=>oe.toStripeAppearance,toStripeAppearanceTheme:()=>oe.toStripeAppearanceTheme});module.exports=Ft(Yr);var Mt=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 Ut(){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,s)=>{let a,i=()=>e.removeEventListener("abort",c),c=()=>{a!==void 0&&clearTimeout(a),i(),s(Ut())};if(e.aborted){c();return}a=setTimeout(()=>{i(),o()},n),e.addEventListener("abort",c,{once:!0})})}var qt="flopay_session_display:";var fe=new Map;function Ce(r){return`${qt}${r}`}function Ie(){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},s=Ie();if(s)try{s.setItem(Ce(r),JSON.stringify(o));return}catch{}fe.set(r,o)}function ve(r){if(!r)return null;let e=Ie();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=Ie();if(e)try{e.removeItem(Ce(r))}catch{}}var k=require("@flopay/shared");var De=require("@flopay/shared"),Lt=32,Ve=Symbol.for("@flopay/js.three-ds-challenge.attempts.v1");function Nt(){let r=globalThis,e=r[Ve];if(e instanceof Map)return e;let t=new Map;try{Object.defineProperty(r,Ve,{configurable:!0,enumerable:!1,writable:!1,value:t})}catch{}return t}function Bt(r,e){let t=Nt(),n=t.get(r);if(n)return n;for(;t.size>=Lt;){let s=t.keys().next();if(s.done)break;t.delete(s.value)}let o={nextSequence:0,startedAt:e,terminated:!1,reconciled:new Set,provider:"unknown"};return t.set(r,o),o}var Vt=new Set(["pagehide_observed","cancel_requested","abort_observed","browser_terminal"]),zt=new Set(["teardown","recovery_read_completed","provider_reconciled"]);function ze(r,e={}){let t=(0,De.isThreeDsChallengeAttemptId)(e.attemptId)?e.attemptId.toLowerCase():r.newAttemptId(),n=()=>{try{let i=r.now();return Number.isFinite(i)?i:0}catch{return 0}},o=Bt(t,n());(e.provider==="stripe"||e.provider==="worldpay")&&(o.provider=e.provider);let s=o.provider,a=(i,c)=>{if(o.terminated&&!zt.has(i))return;let l={attemptId:t,phase:i,attemptSequence:o.nextSequence,elapsedMs:Math.max(0,n()-o.startedAt),provider:s};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,Vt.has(i))}catch{}};return{attemptId:t,record(i,c={}){i==="browser_terminal"||i==="provider_reconciled"||a(i,{reason:c.reason,evidenceBasis:c.evidenceBasis})},terminal(i,c={}){o.terminated||(a("browser_terminal",{terminalSource:i,reason:c.reason,evidenceBasis:c.evidenceBasis}),o.terminated=!0)},reconcile(i){o.reconciled.has(i)||(o.reconciled.add(i),a("provider_reconciled",{providerOutcome:i,evidenceBasis:"provider_fact"}))}}}function ce(r){let e=null;try{e=(0,De.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 je(r){return r==="buyer_cancel"||r==="component_unmount"||r==="navigation"?r:"unspecified"}function be(r){try{if(typeof window>"u"||typeof window.getComputedStyle!="function")return null;for(let e=r;e;e=e.parentElement){let t=window.getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden"||t.visibility==="collapse"||t.opacity==="0")return"hidden"}return"visible"}catch{return null}}function _e(r,e){if(!e)return null;try{let t=r,n=String(t.effectiveDirective||t.violatedDirective||"").trim().split(/\s+/)[0],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 jt="/v1/sdk-telemetry/events",we=16,He=64,Ht=1500,Ke=1e3,Kt=64,$t="00000000-0000-4000-8000-000000000000",Gt={technical_error:8,lifecycle:32,expected_outcome:32,performance:24},Yt=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 Wt(r){try{return new TextEncoder().encode(r).byteLength}catch{return r.length}}function Jt(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(/\/+$/,"")}${jt}`,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:$t,sequence:0}),n=Jt(t),o=this.now();this.pruneReportedFailures(o);let s=this.reportedFailures.get(n);if(s!==void 0&&o>=s&&o-s<Ke){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 ze({now:()=>this.now(),newAttemptId:j,emit:(t,n)=>this.recordThreeDsChallenge(t,n)},e)}recordThreeDsChallenge(e,t){if(!this.canCollect()||this.threeDsChallengeCount>=Yt)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>=He)){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>=Ke)&&this.reportedFailures.delete(t)}rememberReportedFailure(e,t){for(;this.reportedFailures.size>=Kt;){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>=He||this.eventCounts[e.class]>=Gt[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(Wt(t)>k.TELEMETRY_MAX_BATCH_BYTES)return;let n=typeof AbortController>"u"?null:new AbortController,o=null;try{let s=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),a=new Promise(c=>{o=setTimeout(()=>{n?.abort(),c(null)},Ht)});await Promise.race([s,a])==="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)}},$e=Symbol.for("@flopay/js.telemetry.reporter-factory.v1"),Ge=globalThis;Ge[$e]===void 0&&Object.defineProperty(Ge,$e,{configurable:!0,enumerable:!1,writable:!1,value:r=>new A(r)});var xe=5,Ye=new WeakSet;function Qt(r){(typeof r=="object"&&r!==null||typeof r=="function")&&Ye.add(r)}function Xt(r){return(typeof r=="object"&&r!==null||typeof r=="function")&&Ye.has(r)}function Zt(r,e){let t=e?.error,n=ae(e?.code)??ae(t?.code)??`http_${r}`,o=le(e?.message)??le(t?.message)??er(n,r);return new T.FloPayError(o,"api_error",{code:n,statusCode:r})}function er(r,e){switch(r){case"CouponLimitExceeded":return`Too many coupon codes \u2014 a checkout session accepts at most ${xe}.`;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 We(r,e,t){let{billingApiUrl:n,checkoutBaseUrl:o,items:s=[],subscriptions:a=[],products:i,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:x,idempotencyKey:$}=r,B=(0,T.resolveIdempotencyKey)($);if(f.length>xe)throw new T.FloPayError(`Too many coupon codes \u2014 a checkout session accepts at most ${xe}.`,"validation_error",{code:"CouponLimitExceeded",param:"couponCodes"});let O=i??(0,T.foldIntoProducts)(s,a);(0,T.assertCaptureMethodEligible)({captureMethod:m,products:O});let P=(0,T.resolveSessionCurrency)(g,s,a,O);if(!P)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:P,checkoutMode:h,products:O.map(I=>(0,T.buildProductPayload)(I,P)),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),x&&x.length>0&&(R.utmMetadata=x);let X=`${n.replace(/\/+$/,"")}/v1/checkouts/sessions`,se={"Content-Type":"application/json"};B&&(se[T.IDEMPOTENCY_KEY_HEADER]=B);let F,G,ie={method:"POST",headers:se,body:JSON.stringify(R),signal:e},V;try{t?.startAttempt(),V=await fetch(X,ie)}catch(I){throw Qt(I),I}try{t?.record(V.status)}catch{}F=V.status;try{G=await V.json()}catch{}if(F>=400)throw(0,T.withTelemetryHttpDiagnostics)(Zt(F,G),V);if(F===201){let I=G?.data?.uuid,Z=G?.data?.nonce;if(!I)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"});(O.length>0||P)&&Y(I,{currency:P,products:O.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??P}))});let w=new URL(`${o.replace(/\/+$/,"")}/secure`);w.searchParams.set("id",I);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 F===204?(typeof window<"u"&&(window.location.href=l),{status:204}):{status:F}}async function Je(r){let e=Xe(r),t=Qe(e),n=U(r.timeoutMs);try{let o=await We(r,n.signal,t);return t.commit(),Ze(e,o),o}catch(o){throw t.commit(),Re(e,o),o}finally{n.clear(),te(e.reporter)}}function Qe(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 Xe(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 Ze(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 et(r){let{maxRetries:e=2,...t}=r,n=Xe(r),o=Qe(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 s={...t,idempotencyKey:(0,T.resolveIdempotencyKey)(t.idempotencyKey)},a=U(t.timeoutMs),i;for(let c=0;c<=e;c++){n.attempt=c;try{let l=await We(s,a.signal,o);return o.commit(),Ze(n,l),a.clear(),te(n.reporter),l}catch(l){i=l;let u=l instanceof Error&&l.name==="AbortError",h=Xt(l),m=l instanceof T.FloPayError&&l.code===T.IDEMPOTENCY_IN_PROGRESS_CODE;if((u||h||m)&&!a.signal.aborted&&c<e){n.reporter.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:c+1});try{await ee(c,a.signal)}catch(f){throw o.commit(),Re(n,f),a.clear(),te(n.reporter),f}continue}throw o.commit(),Re(n,l),a.clear(),te(n.reporter),l}}throw o.commit(),Re(n,i),a.clear(),te(n.reporter),i??new Error("Unknown error during checkout session creation")}var M=require("@flopay/shared");var d=require("@flopay/shared");function tr(r){return r==="on_session"||r==="off_session"}function rr(r){if(!r||typeof r!="object")return!1;let e=r;return typeof e.paymentMethodType=="string"&&typeof e.reason=="string"}function nr(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 or="x-flopay-process-result-source",sr="status";function tt(r){return r?.result==="DECLINE"||r?.result==="ERROR"}var ir=50,W=new Map;function ar(r,e){return W.get(r)?.has(e)===!0}function lr(r,e){let t=W.get(r)??new Set;if(t.add(e),W.delete(r),W.set(r,t),W.size>ir){let n=W.keys().next().value;n!==void 0&&W.delete(n)}}function cr(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 rt=0,nt=500,Ae=15e3,ot=15e3,dr=3e3,ur=1e4,mr=1e4;function me(r){return typeof r=="object"&&r!==null}function H(r,e){return ae(r?.[e])}function st(r,e){return le(r?.[e])}function pr(r,e){let t=r?.[e];return typeof t=="number"&&Number.isFinite(t)?t:void 0}function Fe(r,e){return e?new Promise((t,n)=>{let o=()=>{clearTimeout(s),n(e.reason??Object.assign(new Error("The operation was aborted."),{name:"AbortError"}))},s=setTimeout(()=>{e.removeEventListener("abort",o),t()},r);e.aborted?o():e.addEventListener("abort",o,{once:!0})}):new Promise(t=>setTimeout(t,r))}function Oe(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=st(t,"message")??st(n,"message")??e,s=H(t,"code")??H(t,"gatewayErrorCode")??H(n,"code")??`http_${r.status}`;return(0,d.withTelemetryHttpDiagnostics)(new d.FloPayError(o,"api_error",{code:s,statusCode:r.status}),r)}async function hr(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 yr(r){if(!(!me(r)||typeof r.required!="boolean"))return{required:r.required,provider:"turnstile"}}async function gr(r){let e=r.status===400?await r.clone().json().catch(()=>null):null;return(0,d.classifyPaymentRejection)(r.status,e)}function it(r){return r===400||r===422}var Ee=2;async function ke(r,e,t=Ee,n,o){let s;for(let a=0;;a++)try{return o?.(a),await fetch(r,e)}catch(i){if(e?.signal?.aborted||i instanceof Error&&i.name==="AbortError")throw i;if(s=i,a>=t)throw s;try{n?.(a+1)}catch{}await Fe(150*2**a,e?.signal??void 0)}}var Ue=Symbol.for("@flopay/js.session-create.telemetry.v1");function fr(r){return r[Ue]}function Cr(r){return"now"in r||"onFirstByte"in r||"onSessionCreateFailure"in r||"onRetry"in r}function lt(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 ct(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 vr(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}),ct(t,r),t}function at(r,e,t){return{currency:e,products:t.map(n=>(0,d.buildProductPayload)(n,e)),couponCodes:r.couponCodes??[],accountData:lt(r.account)}}function Tr(r,e,t){return{currency:e,products:t.map(n=>(0,d.buildProductPayload)(n,e)),couponCodes:r.couponCodes??[]}}function br(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 s=o.trim();s&&(e[n]=s)}return{accountData:e}}var J=class J{constructor(e,t={}){this.baseUrl=e.replace(/\/+$/,"");let n=Cr(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,s="unknown"){let a=(0,d.classifyTelemetryFailure)(e,t);this.directTelemetry?.error({...a,stage:n,requestCategory:o,paymentMethodCategory:s})}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 s=this.telemetryTimestamp(),a=s,i=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=>{i=p,a=this.telemetryTimestamp()});l=!0;let h=Math.max(0,this.telemetryTimestamp()-a);try{this.telemetryHooks?.onFirstByte?.(h,i)}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:i}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:h,durationMode:"machine",requestCategory:"session_read",statusClass:m,attempt:i}),!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()-s),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 s=this.requestVaultCapture(e,t);J.activeVaultCaptureRequests.set(n,s);try{return await s}finally{J.activeVaultCaptureRequests.get(n)===s&&J.activeVaultCaptureRequests.delete(n)}}async requestVaultCapture(e,t){let n=new AbortController,o=setTimeout(()=>n.abort(),mr);this.beginDirectTelemetryCheckout(e);let s=this.telemetryTimestamp();this.directTelemetry?.log({name:"vault.capture.requested",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card"});let a={"Content-Type":"application/json"};t&&(a["x-checkout-session-token"]=t);try{let i=await ke(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/vault/capture`,{method:"POST",headers:a,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 hr(i))return this.directTelemetry?.performance({stage:"vault_request",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"4xx"}),{verification:{required:!0,provider:"turnstile"}};if(!i.ok)throw await L(i,"Failed to load the secure card form");let c=await i.json();return this.directTelemetry?.performance({stage:"vault_request",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"2xx"}),this.toVaultBlock(c)}catch(i){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"}):i;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 s=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.processing.started",stage:"processing",requestCategory:"process_payment",paymentMethodCategory:o});let{nonce:a,paymentMethodCategory:i,...c}=t,l=cr(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":a},body:JSON.stringify(c)}),h=u}catch(m){if(Oe(m))throw this.reportDirectFailure(m,"PAYMENT_PROCESSING_FAILED","processing","process_payment",o),m;u=await this.reconcileProcessPayment(t.sessionId,{...n,nonce:a,paymentMethodCategory:o,submittedIntentId:l})}if(!u.ok&&u.status!==202){let m=await gr(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:a,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()-s),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 s=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.state_transition",stage:"processing",requestCategory:"account_snapshot"});let a=o?.timeoutMs??ur,i=new AbortController,c=()=>i.abort();o?.signal&&(o.signal.aborted?i.abort():o.signal.addEventListener("abort",c,{once:!0}));let l=setTimeout(()=>i.abort(),a);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:i.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()-s),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 s=n,a=s.paymentMethodType,i=typeof a=="string"&&a.trim().toLowerCase()==="card",c=typeof a=="string"&&a.length>0&&!i&&(typeof s.paymentMethodId=="string"||s.paymentMethodId===null),l=s.provider==="stripe"&&(s.paymentMethodCategory==="wallet"||s.paymentMethodCategory==="apm")&&(s.intentKind==="payment"||s.intentKind==="setup"),u=s.provider==="paypal"&&s.paymentMethodCategory==="wallet"&&s.paymentMethodId===null&&(s.paymentMethodType==="paypal"&&s.intentKind==="payment"||s.paymentMethodType===d.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&(s.intentKind==="payment"||s.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=s.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 it(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=_,x=g.paymentMethodType,$=(g.paymentMethodCategory==="wallet"||g.paymentMethodCategory==="apm")&&typeof x=="string"&&x.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",O=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,P=g.provider===n.provider&&g.paymentMethodCategory===n.paymentMethodCategory&&g.paymentMethodType===n.paymentMethodType&&g.paymentMethodId===n.paymentMethodId&&g.intentKind===n.intentKind;if(!$||!B&&!O||!P)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,s){let a=this.toCheckoutProcessingPending(e,t,n);try{return{settled:!0,response:await this.resolveCheckoutProcessing(a,n,{nonce:o,paymentMethodCategory:s.provider==="paypal"?"paypal":s.paymentMethodCategory})}}catch(i){throw i instanceof d.FloPayError&&i.code==="checkout_processing_timeout"?new d.FloPayError(i.message,i.type,{code:i.code,statusCode:202,sessionId:a.sessionId,cause:i}):i}}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 s=n,a=s.providerDeclineReason,i=s.paymentMethodType,c=s.providerIntentId,l=typeof a=="string"&&/^[a-z0-9][a-z0-9_.:-]{0,63}$/i.test(a)&&!/^(?:pm|pi|seti|tok|src|cus|sess|sk|pk)_/i.test(a),u=typeof i=="string"&&i.length>0&&i.trim().toLowerCase()!=="card"&&l,h=s.provider==="stripe"&&(s.paymentMethodCategory==="wallet"||s.paymentMethodCategory==="apm")&&(c===void 0||typeof c=="string"&&/^pi_[a-z0-9_]{1,252}$/i.test(c)),m=s.provider==="paypal"&&s.paymentMethodCategory==="wallet"&&s.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:a}:{provider:"stripe",paymentMethodCategory:s.paymentMethodCategory,paymentMethodType:s.paymentMethodType,providerDeclineReason:a,...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 s=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(s.status===404||s.status===405)return null;if(!s.ok)throw await L(s,"Failed to resolve the payment method layout");let a=await s.json();return(0,d.normalizePaymentMethodLayout)(a?.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,s=t?.limit??1,a=new URLSearchParams({email:e,page:String(o),limit:String(s),sortField:"createdAt",sortDirection:"DESC"});try{let i=await fetch(`${this.baseUrl}/v1/payments?${a.toString()}`,{method:"GET",signal:t?.signal,keepalive:!0});if(!i.ok)throw(0,d.withTelemetryHttpDiagnostics)(new d.FloPayError("Failed to fetch payments","api_error",{statusCode:i.status}),i);let c=await i.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(i){throw this.reportDirectFailure(i,"RECOVERY_FAILED","recovery","other","saved"),i}}async createAndFetchSession(e){if((0,d.isDetachedSessionEligible)(e)){let s=e.account.email?.trim();if(s&&!(0,d.isValidEmail)(s))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 s=await this.createAndFetchSessionRequest(e,n.signal,o);return this.adoptDirectTelemetryCheckout(s.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}),s}catch(s){throw this.reportSessionCreateFailure(s,t,o),s}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 s=(0,d.resolveSessionCurrency)(e.currency,e.items,e.subscriptions,o);if(!s)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 a={clientId:e.clientId,checkoutVersion:d.SDK_VERSION,successUrl:e.successUrl,cancelUrl:e.cancelUrl,currency:s,checkoutMode:e.checkoutMode??"full",products:o.map(l=>(0,d.buildProductPayload)(l,s)),accountData:lt(e.account),couponCodes:e.couponCodes??[]};e.captureMethod==="manual"&&(a.captureMethod=e.captureMethod),e.tokenizedData&&(a.tokenizedData=e.tokenizedData),ct(a,e);let i=await this.postCheckoutSessionCreate(a,e,t,n),c=!1;try{let l=await i.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 s={"Content-Type":"application/json",[d.FLO_SDK_VERSION_HEADER]:d.SDK_VERSION},a=(0,d.resolveIdempotencyKey)(t.idempotencyKey);a&&(s[d.IDEMPOTENCY_KEY_HEADER]=a),t.checkoutMode==="auto"&&(s[d.FLO_SDK_CAPABILITIES_HEADER]=d.ASYNC_AUTO_CHECKOUT_CAPABILITY);let i,c=!1,l=fr(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{i=await fetch(`${this.baseUrl}/v1/checkouts/sessions?expand=true`,{method:"POST",headers:s,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)(i.status);if(o.statusClass=p,i.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(i.ok){u(m,f,p);break}let y=await L(i,"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(!i)throw new TypeError("Checkout-session creation exhausted its retry budget.");return i}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 s=e.products??(0,d.foldIntoProducts)(e.items,e.subscriptions);try{(0,d.assertCaptureMethodEligible)({captureMethod:e.captureMethod,products:s})}catch(C){throw n.clear(),this.reportSessionCreateFailure(C,t,o),C}let a=(0,d.resolveSessionCurrency)(e.currency,e.items,e.subscriptions,s);if(!a)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{at(e,a,s)}catch(C){throw n.clear(),this.reportSessionCreateFailure(C,t,o),C}let i,c,l=!1;try{let C=await this.postCheckoutSessionCreate(vr(e,a),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"});i=this.normalizeRawSession(this.mergeCachedDisplayData(c.data)),c.vault&&i.data.session&&(i.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=i.data.session?.id??c.data.uuid??"",h=i.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?Tr(e,a,s):at(e,a,s),{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,br(_.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:i,sessionId:u,nonce:h,claimed:p,claim:v}}async claimCheckoutSession(e,t,n,o){let s=o?.startedAt??this.telemetryTimestamp(),a=this.telemetryTimestamp(),i=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:i.signal})}catch(y){let v=i.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,i.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()-a),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()-s),durationMode:"machine",requestCategory:"session_create",statusClass:l,attempt:o?.createAttempt??u}),p}catch(m){throw h&&(0,d.markSessionResponseReceived)(m),this.reportSessionCreateFailure(m,a,{attempt:u,statusClass:l},"session_claim"),m}finally{i.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 s=(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:s.statusClass,attempt:n.attempt}),e instanceof d.FloPayError&&e.type==="validation_error"||e instanceof d.FloPayError&&it(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({...s,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 s=t?.timeoutMs??Ae,a=Date.now()+s,i=new AbortController,c=!1,l,u=setTimeout(()=>{l=setTimeout(()=>{c=!0,i.abort()},ot)},s),h=()=>i.abort(t?.signal?.reason);t?.signal?.aborted?h():t?.signal?.addEventListener("abort",h,{once:!0});let m=this.clampRetryAfterMs(t?.initialDelayMs??rt),f=0;try{if(t?.statusUrl){let p=await this.waitForCheckoutStatus(e,{initialDelayMs:m,timeoutMs:s,nonce:t.nonce,statusUrl:t.statusUrl,pollAfterAction:t.continueAfterActionRequired,signal:i.signal});if(p){let y=await this.resolveCheckoutSessionStatus(e,p,t.nonce,i.signal,()=>c);return this.reportRecoveryCompleted(n,o,t.challengeAttemptId),y}}for(;;){let p=a-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 Fe(Math.min(m,p),i.signal),Date.now()>=a)throw D()}let y=await this.getUnifiedCheckoutSessionForRecovery(e,t?.nonce,i.signal),v=y.data.session?.status;if(v==="authorized"||v==="complete"||v==="expired")return this.reportRecoveryCompleted(n,o,t?.challengeAttemptId),y;if(Date.now()>=a)throw D();m=this.clampRetryAfterMs(Math.max(m*2,nt))}}catch(p){let y=c&&Oe(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,s){let a=t.latestTransactionAttempt;if(this.rememberReportedFailure(e,t),a?.result==="DECLINE"){let l=a.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:a.code??a.declineReason??"authorization_declined",statusCode:400})}if(a?.result==="ERROR"||t.status==="voided")throw new d.FloPayError("Payment could not be completed. Please try again.","api_error",{code:a?.code??"payment_processing_error",statusCode:500});let i;try{i=await this.getUnifiedCheckoutSessionForRecovery(e,n,o)}catch(l){if(!s?.()||!Oe(l))throw l;i={providers:[],mode:"tokenize",data:{},raw:t}}let c=i.data.session;return c&&a?.result==="SUCCESS"?{...i,data:{...i.data,session:{...c,status:"complete"}}}:c&&a?.result==="AUTHORIZED"?{...i,data:{...i.data,session:{...c,status:"authorized",paymentId:t.paymentId??void 0,authorizationExpiresAt:t.authorizationExpiresAt??void 0}}}:c&&t.status==="completed"?{...i,data:{...i.data,session:{...c,status:"complete"}}}:c&&t.status==="authorized"?{...i,data:{...i.data,session:{...c,status:"authorized",paymentId:t.paymentId??void 0,authorizationExpiresAt:t.authorizationExpiresAt??void 0}}}:c&&t.status==="expired"?{...i,data:{...i.data,session:{...c,status:"expired"}}}:a?.result!=="ACTION_REQUIRED"?i:a.gateway==="paypal"&&a.providerIntentId?{...i,autoProcessingError:{type:"paypal_direct_required",message:"PayPal authorization required",orderId:a.providerIntentId,checkoutMethod:"paypal"}}:a.nextActionRedirectUrl?{...i,autoProcessingError:{type:"3ds_required",message:"Additional authentication is required.",nextActionRedirectUrl:a.nextActionRedirectUrl}}:i}async waitForCheckoutStatus(e,t){let n=t.timeoutMs??Ae,o=Date.now()+n,s=this.clampRetryAfterMs(t.initialDelayMs);for(;;){let a=o-Date.now();if(a<=0||s>0&&(await Fe(Math.min(s,a),t.signal),Date.now()>=o))throw D();let i=o-Date.now();if(i<=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()},i+ot)}),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=tt(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;s=this.clampRetryAfterMs(Math.max(s*2,nt))}}isOwnFailedAttempt(e,t,n){let o=t.latestTransactionAttempt?.providerIntentId??null;return n!==void 0?o===n:o===null?!0:!ar(t.uuid||e,o)}rememberReportedFailure(e,t){let n=t.latestTransactionAttempt;!tt(n)||!n.providerIntentId||lr(t.uuid||e,n.providerIntentId)}async fetchCheckoutStatus(e,t,n,o){let s=`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/status`,a=s;if(n)try{let u=new URL(n,`${this.baseUrl}/`),h=new URL(s);u.origin===h.origin&&(a=u.toString())}catch{}let i={[d.FLO_SDK_VERSION_HEADER]:d.SDK_VERSION};t&&(i["x-checkout-session-token"]=t);let c=await ke(a,{headers:i,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)},s=t.stripe;if(s?.publishableKey){n.push("stripe");let c=[e.stripeClientSecret,s.stripeClientSecret].find(l=>typeof l=="string"&&l.length>0);o.stripe={clientSecret:c??"",publishableKey:s.publishableKey??void 0,paypalPublishableKey:s.paypalPublishableKey??void 0,environment:s.environment,enabledPaymentMethods:Array.isArray(s.enabledPaymentMethods)?s.enabledPaymentMethods.filter(l=>typeof l=="string"):void 0}}let a=t.paypal;return a?.publishableKey&&(n.push("paypal"),o.paypal={publishableKey:a.publishableKey,environment:a.environment,providerObjectType:a.providerObjectType,approvalPresentation:a.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),s=n?e.totalAmount:o,a=Math.round(s*100),i=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:a,currency:i,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}:{},...tr(e.futureUse)?{futureUse:e.futureUse}:{},...Array.isArray(e.futureUseUnsupported)?{futureUseUnsupported:e.futureUseUnsupported.filter(rr)}:{},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=yr(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),s=this.toCheckoutProcessingPending(o,e,t);return this.resolveCheckoutProcessing(s,t,n)}async resolveCheckoutProcessing(e,t,n){let o=n?.pollTimeoutMs??Ae,s=Date.now()+o;if(e.statusUrl){let i=await this.waitForCheckoutStatus(e.sessionId,{initialDelayMs:e.retryAfterMs,timeoutMs:o,nonce:n?.nonce,statusUrl:e.statusUrl,submittedIntentId:n?.submittedIntentId});if(i)return this.toProcessResponseFromStatus(i,t,n?.nonce)}let a=await this.waitForCheckoutSessionCompletion(e.sessionId,{initialDelayMs:e.retryAfterMs,timeoutMs:s-Date.now(),nonce:n?.nonce,paymentMethodCategory:n?.paymentMethodCategory});return this.toProcessResponseFromSession(a,t)}async toProcessResponseFromStatus(e,t,n){let o=e.latestTransactionAttempt?.result,s={[or]:sr},a={"Content-Type":"application/json",...s};if(e.status==="completed"||o==="SUCCESS")return new Response(null,{status:204,statusText:"No Content",headers:s});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:a});if(e.status==="expired"){let i=await this.resolveCheckoutSessionStatus(t,e,n);return this.toProcessResponseFromSession(i,t)}if(this.rememberReportedFailure(t,e),o==="DECLINE"){let i=e.latestTransactionAttempt,c=i?.code===d.STORED_PAYMENT_METHOD_UNSUPPORTED_CODE,l=i?.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:i?.code??l??"authorization_declined",...l?{declineCode:l}:{}}),{status:400,headers:a})}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:a});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:a});if(o==="ERROR"||e.status==="voided")return new Response(JSON.stringify({type:"unknown",code:e.latestTransactionAttempt?.code??"payment_processing_error",message:nr(e)??"Payment could not be completed. Please try again."}),{status:500,headers:a});throw D()}async reconcileProcessPayment(e,t){let n=t?.pollTimeoutMs??Ae,o=Date.now()+n,s=null;try{s=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(s)return this.toProcessResponseFromStatus(s,e,t?.nonce);let a=o-Date.now();if(a<=0)throw D();let i=await this.waitForCheckoutSessionCompletion(e,{initialDelayMs:0,timeoutMs:a,nonce:t?.nonce,paymentMethodCategory:t?.paymentMethodCategory});return this.toProcessResponseFromSession(i,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"),s=o===null||o.trim()===""?void 0:Number(o),a=s!==void 0&&Number.isFinite(s)?s*1e3:void 0;return{type:"checkout_processing",sessionId:H(e,"sessionId")??n,retryAfterMs:this.clampRetryAfterMs(pr(e,"retryAfterMs")??a??rt),statusUrl:H(e,"statusUrl"),sessionUrl:H(e,"sessionUrl")}}clampRetryAfterMs(e){return Math.max(0,Math.min(e,dr))}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,s=(0,d.resolveSessionCurrency)(t.currency,o?void 0:t.items,o?void 0:t.subscriptions,n);Y(e,{currency:s??void 0,products:n.map(a=>({code:a.code??a.providerItemId??a.providerPlanId,type:a.type,name:a.name??a.itemName??a.providerItemName??a.subscriptionName??a.providerPlanName??null,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount,currency:a.currency??s??void 0}))})}mergeCachedDisplayData(e){let t=ve(e.uuid),n=new Map,o=a=>a?`code:${a}`:void 0;for(let a of t?.products??[]){let i=o(a.code);i&&n.set(i,a)}let s=(e.products??[]).map(a=>{let i=o(a.code),c=i?n.get(i):void 0;return{...a,name:a.name??c?.name??null,totalAmount:a.totalAmount??c?.totalAmount,overrideAmount:a.overrideAmount??c?.overrideAmount,currency:a.currency??c?.currency}});return{...e,currency:e.currency??t?.currency,products:s}}};J.activeVaultCaptureRequests=new Map;var pe=J;function dt(r,e){let t=pe;return new t(r,e)}var S=require("@flopay/shared");var _r=4,qe="flopay-vault",Sr=3e4,wr=S.THREE_DS_CHALLENGE_WINDOW_MS+Sr,Rr="Card authentication timed out.",ut={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 Ar(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:Ar(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 kr=new Set(["authorization_declined","authentication_required","authorization_expired","capture_failed"]);function Er(r){return typeof r=="string"&&kr.has(r)?r:"unknown"}var Mr=new Set(["verification_failed","verification_expired"]);function Pr(r){return r==null?!0:typeof r=="string"&&Mr.has(r)}var Ir="vault_mount";function Dr(r){return r.failureStage===Ir}function mt(r,e){return r&&!Dr(e)?{errorCode:"VAULT_SUBMIT_FAILED",stage:"vault_submit",failureCategory:"provider_runtime",reason:Er(e.failureOutcome)}:{errorCode:"VAULT_LOAD_FAILED",stage:"vault_mount",failureCategory:"provider_runtime"}}function pt(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 xr(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:pt(r,t,n),sequence:0,provider:"pcivault",paymentMethodCategory:"card"});if(o==="error"){let i=mt(e,r);return(0,S.buildTelemetryErrorEvent)({eventId:"33333333-3333-4333-8333-333333333333",...i,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}let[s,a]=ut[o];return he(s,a)}function Or(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===qe&&(e.type==="ready"||e.type==="submitting"||e.type==="blocked"||e.type==="complete"||e.type==="decline"||e.type==="error"||e.type==="action_required")}function Fr(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 Ur(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 qr(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===qe&&e.type==="validation"&&Array.isArray(e.messages)}function Lr(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===qe&&e.type==="resize"&&typeof e.height=="number"&&Number.isFinite(e.height)}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.submitLabel=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.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,typeof window>"u"||typeof document>"u")throw this.reportVaultLoadFailure(),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(),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)}catch(o){throw this.reportVaultLoadFailure(),o}this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),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)}}unmount(){if(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 s=document.createElement("script");for(let a of Array.from(o.attributes))s.setAttribute(a.name,a.value);s.text=o.text,o.replaceWith(s)}}attachMessageListener(){if(this.messageHandler)return;let e=t=>{if(this.expectedOrigin&&t.origin!==this.expectedOrigin)return;let n=t.data;if(Lr(n)){if(this.messageToken&&n.messageToken!==this.messageToken)return;this.applyHeight(n.height);return}if(qr(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(!Or(n)||this.messageToken&&n.messageToken!==this.messageToken)return;let o=this.config.sessionId,s=typeof n.sessionId=="string"?n.sessionId:void 0;if(o&&s&&s!==o||(n.type==="complete"||n.type==="decline")&&o&&s!==o)return;let a=Ur(n.paymentMethod),i=Fr(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}:{},...i?{vaultOutcome:i}:{},...a?{paymentMethod:a}:{}};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(xr(n,this.submissionStarted,this.config.captureMethod,this.config.operation)),this.reportOutcome(n)),n.type==="ready"&&(this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),this.postSubmitLabel()),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&&Pr(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:pt(e,this.config.captureMethod,this.config.operation),provider:"pcivault",paymentMethodCategory:"card"});return}if(n==="error"){let a=mt(this.submissionStarted,e);t.log({name:"vault.terminal",stage:a.stage,provider:"pcivault",paymentMethodCategory:"card"}),t.error({...a,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 a=this.submissionStartedAt;this.submissionStartedAt=null,a!==null&&t.performance({stage:"three_ds_handoff",durationMs:Math.max(0,t.now()-a),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:"action_required",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"});return}let[o,s]=ut[n];t.log({name:o,stage:s,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())}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,s=p=>{if(o)return;let y=_e(p,n);y&&(o=!0,t.record("policy_violation",{reason:y,evidenceBasis:"parent_csp_event"}))},a=()=>{t.record("pagehide_observed",{evidenceBasis:"page_lifecycle_event"})},i={telemetry:t,loaded:!1,detach:()=>{document.removeEventListener("securitypolicyviolation",s),window.removeEventListener("pagehide",a)}};this.actionChallenge=i,this.lastChallengeTelemetry=t,t.record("handoff_planned"),de(e)==="invalid"&&t.record("action_invalid",{reason:"invalid_url"}),document.addEventListener("securitypolicyviolation",s),window.addEventListener("pagehide",a);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",()=>{i.loaded||(i.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<_r&&(h+=1,t.record("return_rejected",{reason:"untrusted_source",evidenceBasis:"message_origin_check"}));return}v&&(t.record("trusted_return",{evidenceBasis:"message_origin_check"}),t.terminal("trusted_return",{evidenceBasis:"message_origin_check"}),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()},wr)}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:Rr})}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 ht(r,e){let t=Q;return new t(r,{reporter:e})}var yt=Symbol.for("@flopay/js.telemetry.bridge.v1");function gt(r,e,t){let n=()=>e?.now()??t();Object.defineProperty(r,yt,{configurable:!1,enumerable:!1,writable:!1,value:{error:s=>e?.error(s),log:s=>e?.log(s),performance:s=>e?.performance(s),terminal:s=>e?.terminal(s),now:n,elapsed:s=>Math.max(0,n()-s),setCheckoutContext:s=>e?.setCheckoutContext(s),beginCheckout:(s={})=>e?.beginCheckout(s)??n(),disable:()=>e?.disable(),subscribe:s=>e?.subscribe(s)??(()=>{}),flush:()=>e?.flush()??Promise.resolve()}})}function ft(r){return r[yt]}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}),gt(this,this.telemetryReporter,E)}cardCapture(e){return this.telemetryReporter?.log({name:"vault.capture.requested",stage:"vault_request",provider:"pcivault",paymentMethodCategory:"card"}),this.telemetryReporter?ht({sessionId:e?.sessionId,captureMethod:e?.captureMethod},this.telemetryReporter):new Q({sessionId:e?.sessionId,captureMethod:e?.captureMethod,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 s,a,i=l=>{if(s===void 0)return;let u=s,h=a;s=void 0,a=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=dt(n,{now:()=>this.telemetryReporter?.now()??E(),onFirstByte:(l,u)=>{s=l,a=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 i("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 i(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 Ct(r,e,t){let n=ye;return new n(r,e,t)}var N=require("@flopay/shared");var Le=require("@flopay/shared"),vt=require("@stripe/stripe-js"),oe=require("@flopay/shared"),Tt=new WeakSet;function bt(r){return r instanceof Le.FloPayError&&Tt.has(r)}var ne=class{constructor(){this.name="stripe";this.stripe=null}async initialize(e){if(typeof window>"u")return;let t=await(0,vt.loadStripe)(e.publishableKey,{locale:e.locale??"auto"});if(!t){let n=new Le.FloPayError("Failed to initialize Stripe. Check your publishable key.","authentication_error");throw Tt.add(n),n}this.stripe=t}getRawProvider(){return this.stripe}destroy(){this.stripe=null}};var _t=new Map;function Ne(r){return Array.isArray(r)?r.map(Ne):r&&typeof r=="object"?Object.fromEntries(Object.entries(r).filter(([,e])=>e!==void 0).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,Ne(t)])):r}function Nr(r,e){return JSON.stringify([r,(0,N.resolveBillingApiUrl)(e?.billingApiUrl),e?.telemetry!==!1,e?.locale??"auto",e?.apiVersion??null,Ne(e?.appearance??null)])}var Me=new Map;async function St(r,e){if(!r){let i=new A({billingApiUrl:(0,N.resolveBillingApiUrl)(e?.billingApiUrl),sdkVersion:N.SDK_VERSION,enabled:e?.telemetry!==!1});throw i.error({errorCode:"CONFIGURATION_INVALID",stage:"sdk_initialize",paymentMethodCategory:"unknown"}),i.flush().catch(()=>{}).finally(()=>i.destroy()),new N.FloPayError("A publishable key is required to initialize FloPay.","validation_error",{param:"publishableKey"})}let t=Nr(r,e),n=_t.get(t);if(n)return e?.telemetry!==!1&&ft(n)?.log({name:"sdk.cache.hit",stage:"sdk_initialize"}),n;let o=Me.get(t);if(o)return o;let s={...e,publishableKey:r},a=(async()=>{let i=new A({billingApiUrl:(0,N.resolveBillingApiUrl)(s.billingApiUrl),sdkVersion:N.SDK_VERSION,enabled:s.telemetry!==!1}),c=i.now();i.log({name:"sdk.initialize.started",stage:"sdk_initialize"}),i.log({name:"sdk.cache.miss",stage:"sdk_initialize"}),i.log({name:"provider.load.started",stage:"provider_load",provider:"stripe"});let l=new ne,u=i.now();try{await l.initialize(s)}catch(f){throw i.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:bt(f)?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"unknown"}),i.destroy(),f}let h=i.now();i.log({name:"provider.ready",stage:"provider_ready",provider:"stripe"}),i.log({name:"provider.availability.checked",stage:"provider_ready",provider:"stripe"}),i.log({name:"sdk.initialize.ready",stage:"sdk_initialize"}),i.performance({stage:"sdk_initialize",durationMs:h-c,durationMode:"machine",provider:"stripe"}),i.performance({stage:"provider_ready",durationMs:h-u,durationMode:"machine",provider:"stripe"});let m=Ct(l,s,i);return _t.set(t,m),m})();Me.set(t,a);try{return await a}finally{Me.get(t)===a&&Me.delete(t)}}var K=require("@flopay/shared");var Br=4,Vr=1e3,zr=1e3,jr=15e3;function Hr(r){let e=!!r?.gateways?.stripe,t=!!r?.gateways?.worldpayCorporateGateway;return e===t?"unknown":e?"stripe":"worldpay"}function Rt(r,e,t){try{return typeof r?.beginThreeDsChallenge!="function"?void 0:r.beginThreeDsChallenge(e,{provider:Hr(t)})}catch{return}}function ge(r){return new K.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:r})}function At(){return new K.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function kt(r){return r.replace(/\/+$/,"")}function Kr(r){return r.status==="succeeded"||r.status==="authorized"||r.status==="declined"}function $r(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 Be(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=je(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 s=`${kt(r.billingApiUrl)}/v1/checkouts/sessions/${encodeURIComponent(r.sessionId)}/3ds/complete`,a=async()=>{let p=new AbortController,y=()=>p.abort();r.signal?.aborted?p.abort():r.signal?.addEventListener("abort",y);let v=window.setTimeout(()=>p.abort(),jr);try{let C=await fetch(s,{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=$r(_);return o(g),g}catch{return{status:"unknown"}}finally{window.clearTimeout(v),r.signal?.removeEventListener("abort",y)}},i,c=()=>r.pollCompletionEndpoint!==!1?a():(i??(i=a()),i),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,x=0,$=!1,B=!1,O=!1,P=0,R=()=>{window.clearTimeout(_),window.clearInterval(g),window.clearTimeout(x),window.removeEventListener("message",I),window.removeEventListener("pagehide",se),document.removeEventListener("securitypolicyviolation",F),h.removeEventListener("load",G),r.signal?.removeEventListener("abort",ie)},X=async()=>{if(!(C||$)){$=!0;try{let w=await c();if(C||!Kr(w))return;C=!0,R(),e.terminal("status_poll",{evidenceBasis:"server_status"}),y(w)}finally{$=!1}}},se=()=>{e.record("pagehide_observed",{evidenceBasis:"page_lifecycle_event"})},F=w=>{if(O)return;let b=_e(w,f);b&&(O=!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(x),x=window.setTimeout(()=>{X()},250))},ie=()=>{C||(C=!0,R(),n(r.signal?.reason),v(ge()))},V=w=>{C||P>=Br||(P+=1,e.record("return_rejected",{reason:w,evidenceBasis:"message_origin_check"}))},I=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(At()))},K.THREE_DS_CHALLENGE_WINDOW_MS),r.pollCompletionEndpoint!==!1&&(g=window.setInterval(()=>{X()},zr)),h.addEventListener("load",G),window.addEventListener("message",I),window.addEventListener("pagehide",se),document.addEventListener("securitypolicyviolation",F),r.signal?.addEventListener("abort",ie),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&&ie()});return p||await c()}finally{u.parentNode?.removeChild(u),e.record("teardown"),l?.isConnected&&l.focus()}}function wt(r,e){try{let t=e.data.session?.status;t==="complete"?r.reconcile("succeeded"):t==="authorized"&&r.reconcile("authorized")}catch{}}function Gr(r){return new K.FloPayError("Card was declined.","api_error",{code:r.declineReason??"authorization_declined",...r.gatewayDeclineReason?{declineCode:r.gatewayDeclineReason}:{}})}async function Et(r,e){let t=`${kt(r.billingApiUrl)}/v1/checkouts/sessions/${encodeURIComponent(r.sessionId)}/status`,n=new AbortController,o=new AbortController,s=()=>{n.abort(r.signal?.reason),o.abort(r.signal?.reason)};r.signal?.aborted?s():r.signal?.addEventListener("abort",s,{once:!0});let a=ce(r.telemetry),i=Be({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:Vr,nonce:r.nonce,statusUrl:t,continueAfterActionRequired:!0,timeoutMs:K.THREE_DS_CHALLENGE_WINDOW_MS+15e3,signal:o.signal,...a.attemptId?{challengeAttemptId:a.attemptId}:{}});c.catch(()=>{}),i.catch(()=>{});try{let l=await Promise.race([i,c]);if("data"in l)return a.terminal("status_poll",{evidenceBasis:"server_status"}),wt(a,l),l;if(l.status==="declined")throw(r.createDeclineError??Gr)(l);if(l.status==="timeout")throw At();let u=await c;return wt(a,u),u}catch(l){throw r.signal?.aborted||l instanceof Error&&l.name==="AbortError"?ge(l):l}finally{r.signal?.removeEventListener("abort",s),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});
|