@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 CHANGED
@@ -54,6 +54,7 @@ mounting provider UI. Use `FloPayCheckout` or `SplitCardForm` from
54
54
  - `getUnifiedCheckoutSession(sessionId, nonce)` reads and normalizes a session.
55
55
  - `createSessionIntent(sessionId, nonce, request)` creates a Stripe wallet/APM or direct-PayPal intent. The request is a discriminated union of provider, payment-method category, type, and id, and intent kind; direct-card requests are not representable. If the session is still processing an earlier payment (for example a PayPal capture under review), the billing API answers `202 checkout_processing`. The SDK then polls the session status within the same time limit `processPayment` uses. It resolves to a settled result, `{ settled: true, response }`, instead of an intent. `response` is the `Response` `processPayment` would give for that outcome: `204` succeeded, `200` authorized, `400` declined. Check for it with `isSettledSessionIntent` from `@flopay/shared`. If the time limit runs out first, it rejects with `checkout_processing_timeout`, `statusCode: 202` and the `sessionId`.
56
56
  - `reportSessionIntentDecline(sessionId, nonce, request)` reports a client-observed non-card decline using a classification code only. Messages, identifiers, card data, credentials, and personal data are rejected before sending.
57
+ - `resolvePaymentMethodLayout(sessionId, nonce, rules)` sends the merchant's `PaymentMethodLayoutRules` and returns the `PaymentMethodLayout` the billing API resolved for this buyer: the order of `'card'`, `'paypal'`, `'wallets'` and `'apms'`, where the buyer's country came from (`'session'`, `'ip'` or `'none'`), and warnings about invalid rules. The SDK sends no country, and the IP country is never returned. It resolves `null` when the billing API predates the route.
57
58
  - `processPayment(userId, params)` submits a saved or approved non-card payment to the session's `/process` route. When the billing API answers `202`, the SDK follows its authenticated status endpoint until the latest transaction attempt succeeds, authorizes, declines, requires buyer action, fails, or times out.
58
59
  - `getPaymentsByEmail(email)` looks up prior payments for a saved-payment experience.
59
60
 
@@ -346,6 +347,7 @@ await api.reportSessionIntentDecline('session_uuid', 'session_nonce', {
346
347
  | `claimCheckoutSession(sessionId, nonce, payload)` | `Promise<NormalizedCheckoutSession>` | Sends a `PATCH /v1/checkouts/sessions/{id}/claim` |
347
348
  | `createSessionIntent(sessionId, nonce, request, options?)` | `Promise<SessionIntentResult>` | Creates a Stripe wallet/APM or direct-PayPal intent. If the session is still processing an earlier payment, resolves to `{ settled: true, response }` with that payment's outcome. |
348
349
  | `reportSessionIntentDecline(sessionId, nonce, request, options?)` | `Promise<void>` | Reports a non-card decline classification |
350
+ | `resolvePaymentMethodLayout(sessionId, nonce, rules, options?)` | `Promise<PaymentMethodLayout \| null>` | Applies the merchant's layout rules to this buyer; `null` on a billing API without the route |
349
351
  | `processPayment(userId, params, options?)` | `Promise<Response>` | Submits a saved or approved non-card payment to `/process`; a `202` follows the advertised authenticated status endpoint and maps terminal attempt outcomes back to the existing process response shapes |
350
352
  | `waitForCheckoutSessionCompletion(sessionId, options?)` | `Promise<NormalizedCheckoutSession>` | Waits for terminal state; pass the session `nonce` and a processing response's `statusUrl` to reconcile attempt-level success, authorization, decline, buyer action, and failure. `timeoutMs` (15 seconds by default) stops normal polling. A read already in flight may still land during a grace of up to 15 more seconds; if it returns a terminal status, the SDK may start one follow-up session read to normalize the result. The entire operation remains capped by that grace |
351
353
  | `reportThreeDsAbandoned(sessionId)` | `void` | Records a saved-card 3DS challenge the buyer never finished as a buyer-abandonment outcome in Flo's privacy-safe telemetry, not as a technical failure. No-op when telemetry is off. The automatic payment button calls it for you |
@@ -1 +1 @@
1
- "use strict";var $=Object.defineProperty;var Fe=Object.getOwnPropertyDescriptor;var Ue=Object.getOwnPropertyNames;var qe=Object.prototype.hasOwnProperty;var Le=(r,e)=>{for(var t in e)$(r,t,{get:e[t],enumerable:!0})},Ne=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ue(e))!qe.call(r,s)&&s!==t&&$(r,s,{get:()=>e[s],enumerable:!(n=Fe(e,s))||n.enumerable});return r};var Ve=r=>Ne($({},"__esModule",{value:!0}),r);var zt={};Le(zt,{PaymentAPI:()=>j,PciVaultCardCapture:()=>K,clearSetupRedirectParams:()=>Me,readSetupRedirectReturn:()=>ke});module.exports=Ve(zt);var c=require("@flopay/shared");function re(r){return typeof r=="string"&&r.trim()?r:void 0}function ne(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 D(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 Be(){return Object.assign(new Error("The operation was aborted."),{name:"AbortError"})}function q(r,e){let t=150*2**r,n=Math.round(t*(.75+Math.random()*.5));return new Promise((s,i)=>{let o,a=()=>e.removeEventListener("abort",l),l=()=>{o!==void 0&&clearTimeout(o),a(),i(Be())};if(e.aborted){l();return}o=setTimeout(()=>{a(),s()},n),e.addEventListener("abort",l,{once:!0})})}var ze="flopay_session_display:";var L=new Map;function N(r){return`${ze}${r}`}function Y(){if(typeof window>"u")return null;try{return window.sessionStorage}catch{return null}}function W(r,e,t){if(!r)return;let n=t?.ttlMs??36e5,s={data:e,expiresAt:Date.now()+n},i=Y();if(i)try{i.setItem(N(r),JSON.stringify(s));return}catch{}L.set(r,s)}function se(r){if(!r)return null;let e=Y();if(e)try{let n=e.getItem(N(r));if(n){let s=JSON.parse(n);if(s&&typeof s.expiresAt=="number"&&s.expiresAt>Date.now())return s.data;e.removeItem(N(r))}}catch{}let t=L.get(r);if(t){if(t.expiresAt>Date.now())return t.data;L.delete(r)}return null}function ie(r){if(!r)return;L.delete(r);let e=Y();if(e)try{e.removeItem(N(r))}catch{}}var b=require("@flopay/shared");var Q=require("@flopay/shared"),He=32,oe=Symbol.for("@flopay/js.three-ds-challenge.attempts.v1");function je(){let r=globalThis,e=r[oe];if(e instanceof Map)return e;let t=new Map;try{Object.defineProperty(r,oe,{configurable:!0,enumerable:!1,writable:!1,value:t})}catch{}return t}function Ke(r,e){let t=je(),n=t.get(r);if(n)return n;for(;t.size>=He;){let i=t.keys().next();if(i.done)break;t.delete(i.value)}let s={nextSequence:0,startedAt:e,terminated:!1,reconciled:new Set,provider:"unknown"};return t.set(r,s),s}var Ge=new Set(["pagehide_observed","cancel_requested","abort_observed","browser_terminal"]),$e=new Set(["teardown","recovery_read_completed","provider_reconciled"]);function ae(r,e={}){let t=(0,Q.isThreeDsChallengeAttemptId)(e.attemptId)?e.attemptId.toLowerCase():r.newAttemptId(),n=()=>{try{let a=r.now();return Number.isFinite(a)?a:0}catch{return 0}},s=Ke(t,n());(e.provider==="stripe"||e.provider==="worldpay")&&(s.provider=e.provider);let i=s.provider,o=(a,l)=>{if(s.terminated&&!$e.has(a))return;let u={attemptId:t,phase:a,attemptSequence:s.nextSequence,elapsedMs:Math.max(0,n()-s.startedAt),provider:i};s.nextSequence+=1,l.reason!==void 0&&(u.reason=l.reason),l.evidenceBasis!==void 0&&(u.evidenceBasis=l.evidenceBasis),l.terminalSource!==void 0&&(u.terminalSource=l.terminalSource),l.providerOutcome!==void 0&&(u.providerOutcome=l.providerOutcome);try{r.emit(u,Ge.has(a))}catch{}};return{attemptId:t,record(a,l={}){a==="browser_terminal"||a==="provider_reconciled"||o(a,{reason:l.reason,evidenceBasis:l.evidenceBasis})},terminal(a,l={}){s.terminated||(o("browser_terminal",{terminalSource:a,reason:l.reason,evidenceBasis:l.evidenceBasis}),s.terminated=!0)},reconcile(a){s.reconciled.has(a)||(s.reconciled.add(a),o("provider_reconciled",{providerOutcome:a,evidenceBasis:"provider_fact"}))}}}function ce(r){let e=null;try{e=(0,Q.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 J(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 le(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 ue(r,e){if(!e)return null;try{let t=r,n=String(t.effectiveDirective||t.violatedDirective||"").trim().split(/\s+/)[0],s=null;return n==="frame-src"&&(s="frame_src"),n==="child-src"&&(s="child_src"),!s||typeof t.blockedURI!="string"?null:new URL(t.blockedURI).origin===e?s:null}catch{return null}}function de(r){try{return J(r)==="valid"?new URL(r).origin:null}catch{return null}}var Ye="/v1/sdk-telemetry/events",V=16,me=64,We=1500,he=1e3,Qe=64,Je="00000000-0000-4000-8000-000000000000",Xe={technical_error:8,lifecycle:32,expected_outcome:32,performance:24},Ze=48;function A(){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 et(r){try{return new TextEncoder().encode(r).byteLength}catch{return r.length}}function tt(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 R(){return globalThis.performance?.now()??0}var w=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(/\/+$/,"")}${Ye}`,this.sdkPackage=e.sdkPackage??"@flopay/js",this.sdkVersion=e.sdkVersion,this.correlationId=A(),this.merchantEnabled=e.enabled!==!1,this.clock=e.clock??R,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,b.buildTelemetryLogEvent)({...this.checkoutContext,...e,eventId:A(),sequence:this.sequence++}))}error(e){if(this.notify({...e,class:"technical_error"}),!this.canCollect())return;let t=(0,b.buildTelemetryErrorEvent)({...this.checkoutContext,...e,eventId:Je,sequence:0}),n=tt(t),s=this.now();this.pruneReportedFailures(s);let i=this.reportedFailures.get(n);if(i!==void 0&&s>=i&&s-i<he){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,s),this.enqueue((0,b.buildTelemetryErrorEvent)({...this.checkoutContext,...e,eventId:A(),sequence:this.sequence++}))}performance(e){this.canCollect()&&this.enqueue((0,b.buildTelemetryPerformanceEvent)({...this.checkoutContext,...e,eventId:A(),sequence:this.sequence++}))}terminal(e){if(this.canCollect()&&(this.enqueue((0,b.buildTelemetryTerminalEvent)({...this.checkoutContext,...e,eventId:A(),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 ae({now:()=>this.now(),newAttemptId:A,emit:(t,n)=>this.recordThreeDsChallenge(t,n)},e)}recordThreeDsChallenge(e,t){if(!this.canCollect()||this.threeDsChallengeCount>=Ze)return;let n=(0,b.buildTelemetryLogEvent)({...this.checkoutContext,...e,name:"three_ds.challenge",stage:"three_ds_handoff",eventId:A(),sequence:this.sequence++});if(!(this.queue.length>=me)){if(this.threeDsChallengeCount+=1,this.queue.push(n),t){this.drainQueue();return}if(this.queue.length>=V){this.flush();return}this.scheduleFlush()}}now(){try{return this.clock()}catch{return R()}}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>=he)&&this.reportedFailures.delete(t)}rememberReportedFailure(e,t){for(;this.reportedFailures.size>=Qe;){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>=me||this.eventCounts[e.class]>=Xe[e.class])){if(this.eventCounts[e.class]+=1,this.queue.push(e),this.queue.length>=V){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,V);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,V);this.sendBatch(e)}}async sendBatch(e){if(!this.browserTransportAvailable||this.ingestionDisabled)return;let t=(0,b.serializeTelemetryBatch)(e,{correlationId:this.correlationId,sdkPackage:this.sdkPackage,sdkVersion:this.sdkVersion,batchId:A()});if(et(t)>b.TELEMETRY_MAX_BATCH_BYTES)return;let n=typeof AbortController>"u"?null:new AbortController,s=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 l=>{if(l.status!==202)return null;let u=null;try{u=await l.json()}catch{}return u?.status==="disabled"?"disabled":null}).catch(()=>null),o=new Promise(l=>{s=setTimeout(()=>{n?.abort(),l(null)},We)});await Promise.race([i,o])==="disabled"&&this.disableFromIngestion()}catch{}finally{s&&clearTimeout(s)}}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)}},pe=Symbol.for("@flopay/js.telemetry.reporter-factory.v1"),ye=globalThis;ye[pe]===void 0&&Object.defineProperty(ye,pe,{configurable:!0,enumerable:!1,writable:!1,value:r=>new w(r)});function rt(r){return r==="on_session"||r==="off_session"}function nt(r){if(!r||typeof r!="object")return!1;let e=r;return typeof e.paymentMethodType=="string"&&typeof e.reason=="string"}function st(r){let e=r.vaultOutcome;if(!(!e||e.code!==c.CHECKOUT_SESSION_BUYER_EMAIL_REQUIRED))return typeof e.message=="string"&&e.message.trim()!==""?e.message:void 0}var it="x-flopay-process-result-source",ot="status";function ge(r){return r?.result==="DECLINE"||r?.result==="ERROR"}var at=50,M=new Map;function ct(r,e){return M.get(r)?.has(e)===!0}function lt(r,e){let t=M.get(r)??new Set;if(t.add(e),M.delete(r),M.set(r,t),M.size>at){let n=M.keys().next().value;n!==void 0&&M.delete(n)}}function ut(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 fe=0,Ce=500,B=15e3,ve=15e3,dt=3e3,mt=1e4,ht=1e4;function F(r){return typeof r=="object"&&r!==null}function k(r,e){return re(r?.[e])}function Te(r,e){return ne(r?.[e])}function pt(r,e){let t=r?.[e];return typeof t=="number"&&Number.isFinite(t)?t:void 0}function Z(r,e){return e?new Promise((t,n)=>{let s=()=>{clearTimeout(i),n(e.reason??Object.assign(new Error("The operation was aborted."),{name:"AbortError"}))},i=setTimeout(()=>{e.removeEventListener("abort",s),t()},r);e.aborted?s():e.addEventListener("abort",s,{once:!0})}):new Promise(t=>setTimeout(t,r))}function X(r){return r instanceof Error&&r.name==="AbortError"}function S(){return new c.FloPayError(c.CHECKOUT_PROCESSING_TIMEOUT_MESSAGE,"api_error",{code:"checkout_processing_timeout"})}async function E(r,e){let t=await r.json().catch(()=>null),n=F(t?.error)?t.error:null,s=Te(t,"message")??Te(n,"message")??e,i=k(t,"code")??k(t,"gatewayErrorCode")??k(n,"code")??`http_${r.status}`;return(0,c.withTelemetryHttpDiagnostics)(new c.FloPayError(s,"api_error",{code:i,statusCode:r.status}),r)}async function yt(r){if(r.status!==403)return!1;let e=await r.clone().json().catch(()=>null),t=F(e?.error)?e.error:null;return(k(e,"code")??k(t,"code"))==="verification_required"}function gt(r){if(!(!F(r)||typeof r.required!="boolean"))return{required:r.required,provider:"turnstile"}}async function ft(r){let e=r.status===400?await r.clone().json().catch(()=>null):null;return(0,c.classifyPaymentRejection)(r.status,e)}function be(r){return r===400||r===422}var H=2;async function z(r,e,t=H,n,s){let i;for(let o=0;;o++)try{return s?.(o),await fetch(r,e)}catch(a){if(e?.signal?.aborted||a instanceof Error&&a.name==="AbortError")throw a;if(i=a,o>=t)throw i;try{n?.(o+1)}catch{}await Z(150*2**o,e?.signal??void 0)}}var Ct=Symbol.for("@flopay/js.session-create.telemetry.v1");function vt(r){return r[Ct]}function Tt(r){return"now"in r||"onFirstByte"in r||"onSessionCreateFailure"in r||"onRetry"in r}function Se(r){let e=(0,c.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 Re(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 bt(r,e){let t={clientId:r.clientId,checkoutVersion:c.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}),Re(t,r),t}function _e(r,e,t){return{currency:e,products:t.map(n=>(0,c.buildProductPayload)(n,e)),couponCodes:r.couponCodes??[],accountData:Se(r.account)}}function _t(r,e,t){return{currency:e,products:t.map(n=>(0,c.buildProductPayload)(n,e)),couponCodes:r.couponCodes??[]}}function St(r){let e={},t=(0,c.isCardHolderNamePlaceholder)(r.firstName,r.lastName);for(let[n,s]of Object.entries(r)){if(t&&n.endsWith("Name")||typeof s!="string")continue;let i=s.trim();i&&(e[n]=i)}return{accountData:e}}var I=class I{constructor(e,t={}){this.baseUrl=e.replace(/\/+$/,"");let n=Tt(t);this.telemetryHooks=n?t:void 0,this.directTelemetry=n||t.telemetry===!1?void 0:new w({billingApiUrl:this.baseUrl,sdkVersion:c.SDK_VERSION})}destroy(){this.directTelemetry?.destroy()}reportDirectFailure(e,t,n,s,i="unknown"){let o=(0,c.classifyTelemetryFailure)(e,t);this.directTelemetry?.error({...o,stage:n,requestCategory:s,paymentMethodCategory:i})}reportAccountSnapshotFailure(e,t){let n=(0,c.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()??R()}catch{return R()}}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,s){this.beginDirectTelemetryCheckout(e);let i=this.telemetryTimestamp(),o=i,a=0;this.directTelemetry?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let l={[c.FLO_SDK_VERSION_HEADER]:c.SDK_VERSION};t&&(l["x-checkout-session-token"]=t);let u=!1;try{let d=await z(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}`,{headers:l,signal:s},H,h=>{this.telemetryHooks?.onRetry?.("session_read",h),this.directTelemetry?.log({name:"operation.retry",stage:"session_read",requestCategory:"session_read",attempt:h})},h=>{a=h,o=this.telemetryTimestamp()});u=!0;let p=Math.max(0,this.telemetryTimestamp()-o);try{this.telemetryHooks?.onFirstByte?.(p,a)}catch{}let m=`${Math.floor(d.status/100)}xx`;if(this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:m,attempt:a}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:p,durationMode:"machine",requestCategory:"session_read",statusClass:m,attempt:a}),!d.ok)throw await E(d,"Failed to get checkout session");let f=await d.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(d){throw u&&(0,c.markSessionResponseReceived)(d),n&&this.directTelemetry?.error({...(0,c.classifyTelemetryFailure)(d,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"}),d}}cacheSessionDisplayData(e,t,n){W(e,t,n)}clearSessionDisplayData(e){ie(e)}async getVaultCapture(e,t){let n=`${this.baseUrl}\0${e}\0${t??""}`,s=I.activeVaultCaptureRequests.get(n);if(s!==void 0)return s;let i=this.requestVaultCapture(e,t);I.activeVaultCaptureRequests.set(n,i);try{return await i}finally{I.activeVaultCaptureRequests.get(n)===i&&I.activeVaultCaptureRequests.delete(n)}}async requestVaultCapture(e,t){let n=new AbortController,s=setTimeout(()=>n.abort(),ht);this.beginDirectTelemetryCheckout(e);let i=this.telemetryTimestamp();this.directTelemetry?.log({name:"vault.capture.requested",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card"});let o={"Content-Type":"application/json"};t&&(o["x-checkout-session-token"]=t);try{let a=await z(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/vault/capture`,{method:"POST",headers:o,signal:n.signal},H,u=>{this.telemetryHooks?.onRetry?.("vault_capture",u),this.directTelemetry?.log({name:"operation.retry",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card",attempt:u})});if(await yt(a))return this.directTelemetry?.performance({stage:"vault_request",durationMs:Math.max(0,this.telemetryTimestamp()-i),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"4xx"}),{verification:{required:!0,provider:"turnstile"}};if(!a.ok)throw await E(a,"Failed to load the secure card form");let l=await a.json();return this.directTelemetry?.performance({stage:"vault_request",durationMs:Math.max(0,this.telemetryTimestamp()-i),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"2xx"}),this.toVaultBlock(l)}catch(a){let l=n.signal.aborted?new c.FloPayError("Timed out while loading the secure card form. Please try again.","api_error",{code:"vault_capture_timeout"}):a;throw this.reportDirectFailure(l,"VAULT_LOAD_FAILED","vault_request","vault_capture","card"),l}finally{clearTimeout(s)}}async getUnifiedCheckoutSession(e,t){let n=await this.getCheckoutSession(e,t);return this.normalizeCheckoutSessionResponse(n)}async getUnifiedCheckoutSessionForRecovery(e,t,n){let s=await this.fetchCheckoutSession(e,t,!1,n);return this.normalizeCheckoutSessionResponse(s)}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,c.markSessionResponseReceived)(t)}}async processPayment(e,t,n){this.beginDirectTelemetryCheckout(t.sessionId);let s=t.paymentMethodCategory??"unknown";if(!t.nonce)throw this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"process_payment",paymentMethodCategory:s}),new c.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:s});let{nonce:o,paymentMethodCategory:a,...l}=t,u=ut(t.tokenizedData),d,p;try{d=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(t.sessionId)}/process`,{method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":o},body:JSON.stringify(l)}),p=d}catch(m){if(X(m))throw this.reportDirectFailure(m,"PAYMENT_PROCESSING_FAILED","processing","process_payment",s),m;d=await this.reconcileProcessPayment(t.sessionId,{...n,nonce:o,paymentMethodCategory:s,submittedIntentId:u})}if(!d.ok&&d.status!==202){let m=await ft(d);return m?this.directTelemetry?.terminal({outcome:m,stage:"processing",requestCategory:"process_payment",statusClass:"4xx",paymentMethodCategory:s}):this.directTelemetry?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",requestCategory:"process_payment",statusClass:(0,c.telemetryStatusClass)(d.status),failureCategory:d.status>=500?"server_error":void 0,paymentMethodCategory:s,...(0,c.readTelemetryHttpDiagnostics)(p)}),d}try{let m=await this.resolveProcessResponse(d,t.sessionId,{...n,nonce:o,paymentMethodCategory:s,submittedIntentId:u});return this.directTelemetry?.log({name:"payment.processing.completed",stage:"processing",requestCategory:"process_payment",statusClass:(0,c.telemetryStatusClass)(m.status),paymentMethodCategory:s}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-i),durationMode:"machine",requestCategory:"process_payment",statusClass:(0,c.telemetryStatusClass)(m.status),paymentMethodCategory:s}),m}catch(m){throw m instanceof c.FloPayError&&m.code==="checkout_processing_timeout"||this.reportDirectFailure(m,"PAYMENT_PROCESSING_FAILED","processing","process_payment",s),m}}async patchAccountSnapshot(e,t,n,s){this.beginDirectTelemetryCheckout(e);let i=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.state_transition",stage:"processing",requestCategory:"account_snapshot"});let o=s?.timeoutMs??mt,a=new AbortController,l=()=>a.abort();s?.signal&&(s.signal.aborted?a.abort():s.signal.addEventListener("abort",l,{once:!0}));let u=setTimeout(()=>a.abort(),o);try{let d;try{d=await z(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/account`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":t},body:JSON.stringify(n),signal:a.signal},H,p=>{this.telemetryHooks?.onRetry?.("account_snapshot",p),this.directTelemetry?.log({name:"operation.retry",stage:"processing",requestCategory:"account_snapshot",attempt:p})})}finally{clearTimeout(u),s?.signal?.removeEventListener("abort",l)}if(!d.ok)throw await E(d,"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(d){throw this.reportAccountSnapshotFailure(d,s?.telemetryMode??"blocking"),d}}async createSessionIntent(e,t,n,s){if(!t)throw new c.FloPayError("createSessionIntent requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let i=n,o=i.paymentMethodType,a=typeof o=="string"&&o.trim().toLowerCase()==="card",l=typeof o=="string"&&o.length>0&&!a&&(typeof i.paymentMethodId=="string"||i.paymentMethodId===null),u=i.provider==="stripe"&&(i.paymentMethodCategory==="wallet"||i.paymentMethodCategory==="apm")&&(i.intentKind==="payment"||i.intentKind==="setup"),d=i.provider==="paypal"&&i.paymentMethodCategory==="wallet"&&i.paymentMethodId===null&&(i.paymentMethodType==="paypal"&&i.intentKind==="payment"||i.paymentMethodType===c.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&(i.intentKind==="payment"||i.intentKind==="setup"));if(!l||!u&&!d)throw new c.FloPayError("Only wallet, APM, and PayPal session intents are supported.","validation_error",{code:"InvalidSessionIntentRequest"});let p=i.authorizationAttemptId;if(p!==void 0&&!(0,c.isUuidV4)(p))throw new c.FloPayError("authorizationAttemptId must be a v4 UUID identifying one buyer authorization attempt.","validation_error",{code:"InvalidAuthorizationAttemptId",param:"authorizationAttemptId"});let m=(0,c.isUuidV4)(p)?p:(0,c.randomUuidV4)();this.beginDirectTelemetryCheckout(e);let f=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.intent.started",stage:"processing",requestCategory:"intent_create"});let h={"Content-Type":"application/json","x-checkout-session-token":t,[c.IDEMPOTENCY_KEY_HEADER]:s?.idempotencyKey||m},g=!1;try{let C=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents`,{method:"POST",headers:h,body:JSON.stringify({...n,authorizationAttemptId:m}),signal:s?.signal});if(!C.ok){g=!0;let G=await E(C,"Failed to create checkout intent"),xe=(0,c.classifyTelemetryFailure)(G,"PAYMENT_PROCESSING_FAILED");throw be(G.statusCode)?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"intent_create",statusClass:"4xx"}):this.directTelemetry?.error({...xe,stage:"processing",requestCategory:"intent_create"}),G}let v=await C.json();if(C.status===202&&F(v)&&v.type==="checkout_processing")return g=!0,await this.settleProcessingSessionIntent(v,C,e,t,n);let _=v.data;if(!_||typeof _!="object")throw new c.FloPayError("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});let y=_,te=y.paymentMethodType,Ie=(y.paymentMethodCategory==="wallet"||y.paymentMethodCategory==="apm")&&typeof te=="string"&&te.trim().toLowerCase()!=="card"&&(typeof y.paymentMethodId=="string"||y.paymentMethodId===null)&&typeof y.providerObjectId=="string",De=y.provider==="stripe"&&(y.intentKind==="payment"||y.intentKind==="setup")&&typeof y.clientSecret=="string",Pe=y.provider==="paypal"&&y.paymentMethodCategory==="wallet"&&y.paymentMethodId===null&&(y.paymentMethodType==="paypal"&&y.intentKind==="payment"&&(y.providerObjectType==="order"||y.providerObjectType==="subscription")||y.paymentMethodType===c.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&y.intentKind==="payment"&&y.providerObjectType==="order"||y.paymentMethodType===c.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&y.intentKind==="setup"&&y.providerObjectType==="setup_token")&&y.clientSecret===null,Oe=y.provider===n.provider&&y.paymentMethodCategory===n.paymentMethodCategory&&y.paymentMethodType===n.paymentMethodType&&y.paymentMethodId===n.paymentMethodId&&y.intentKind===n.intentKind;if(!Ie||!De&&!Pe||!Oe)throw new c.FloPayError("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});return this.directTelemetry?.log({name:"payment.intent.completed",stage:"processing",requestCategory:"intent_create",statusClass:(0,c.telemetryStatusClass)(C.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-f),durationMode:"machine",requestCategory:"intent_create",statusClass:(0,c.telemetryStatusClass)(C.status)}),y}catch(C){throw g||this.reportDirectFailure(C,"PAYMENT_PROCESSING_FAILED","processing","intent_create"),C}}async settleProcessingSessionIntent(e,t,n,s,i){let o=this.toCheckoutProcessingPending(e,t,n);try{return{settled:!0,response:await this.resolveCheckoutProcessing(o,n,{nonce:s,paymentMethodCategory:i.provider==="paypal"?"paypal":i.paymentMethodCategory})}}catch(a){throw a instanceof c.FloPayError&&a.code==="checkout_processing_timeout"?new c.FloPayError(a.message,a.type,{code:a.code,statusCode:202,sessionId:o.sessionId,cause:a}):a}}async reportSessionIntentDecline(e,t,n,s){if(!t)throw new c.FloPayError("reportSessionIntentDecline requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let i=n,o=i.providerDeclineReason,a=i.paymentMethodType,l=i.providerIntentId,u=typeof o=="string"&&/^[a-z0-9][a-z0-9_.:-]{0,63}$/i.test(o)&&!/^(?:pm|pi|seti|tok|src|cus|sess|sk|pk)_/i.test(o),d=typeof a=="string"&&a.length>0&&a.trim().toLowerCase()!=="card"&&u,p=i.provider==="stripe"&&(i.paymentMethodCategory==="wallet"||i.paymentMethodCategory==="apm")&&(l===void 0||typeof l=="string"&&/^pi_[a-z0-9_]{1,252}$/i.test(l)),m=i.provider==="paypal"&&i.paymentMethodCategory==="wallet"&&i.paymentMethodType==="paypal"&&l===void 0;if(!d||!p&&!m)throw new c.FloPayError("Invalid non-card decline classification.","validation_error",{code:"InvalidSessionIntentDeclineRequest"});let f=m?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:o}:{provider:"stripe",paymentMethodCategory:i.paymentMethodCategory,paymentMethodType:i.paymentMethodType,providerDeclineReason:o,...typeof l=="string"?{providerIntentId:l}:{}},h=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:s?.signal});if(!h.ok)throw await E(h,"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 s=t?.page??1,i=t?.limit??1,o=new URLSearchParams({email:e,page:String(s),limit:String(i),sortField:"createdAt",sortDirection:"DESC"});try{let a=await fetch(`${this.baseUrl}/v1/payments?${o.toString()}`,{method:"GET",signal:t?.signal,keepalive:!0});if(!a.ok)throw(0,c.withTelemetryHttpDiagnostics)(new c.FloPayError("Failed to fetch payments","api_error",{statusCode:a.status}),a);let l=await a.json();return this.directTelemetry?.log({name:"operation.recovery.completed",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),this.directTelemetry?.performance({stage:"recovery",durationMs:Math.max(0,this.telemetryTimestamp()-n),durationMode:"machine",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),l}catch(a){throw this.reportDirectFailure(a,"RECOVERY_FAILED","recovery","other","saved"),a}}async createAndFetchSession(e){if((0,c.isDetachedSessionEligible)(e)){let i=e.account.email?.trim();if(i&&!(0,c.isValidEmail)(i))throw new c.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=D(e.timeoutMs??12e3),s={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,s);return this.adoptDirectTelemetryCheckout(i.data.session?.id),this.directTelemetry?.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:s.statusClass}),this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:"session_create",statusClass:s.statusClass,attempt:s.attempt}),i}catch(i){throw this.reportSessionCreateFailure(i,t,s),i}finally{n.clear()}}async createAndFetchSessionRequest(e,t,n){let s=e.products??(0,c.foldIntoProducts)(e.items,e.subscriptions);(0,c.assertCaptureMethodEligible)({captureMethod:e.captureMethod,products:s});let i=(0,c.resolveSessionCurrency)(e.currency,e.items,e.subscriptions,s);if(!i)throw new c.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 o={clientId:e.clientId,checkoutVersion:c.SDK_VERSION,successUrl:e.successUrl,cancelUrl:e.cancelUrl,currency:i,checkoutMode:e.checkoutMode??"full",products:s.map(u=>(0,c.buildProductPayload)(u,i)),accountData:Se(e.account),couponCodes:e.couponCodes??[]};e.captureMethod==="manual"&&(o.captureMethod=e.captureMethod),e.tokenizedData&&(o.tokenizedData=e.tokenizedData),Re(o,e);let a=await this.postCheckoutSessionCreate(o,e,t,n),l=!1;try{let u=await a.json();if(u.data&&"gateways"in u.data){this.autoCacheDisplayData(u.data.uuid,e);let m=this.mergeCachedDisplayData(u.data),f=this.normalizeRawSession(m);return u.vault&&f.data.session&&(f.data.session.vault=this.toVaultBlock(u.vault)),{...f,autoProcessingError:u.autoProcessingError,autoProcessingAttempted:u.autoProcessingAttempted,autoProcessingPending:u.autoProcessingPending}}let d=u.data?.uuid;if(!d)throw new c.FloPayError("No session ID returned","api_error",{code:"InvalidCheckoutSessionResponse"});return this.autoCacheDisplayData(d,e),this.adoptDirectTelemetryCheckout(d),l=!0,{...await this.getUnifiedCheckoutSession(d),autoProcessingError:u.autoProcessingError,autoProcessingAttempted:u.autoProcessingAttempted,autoProcessingPending:u.autoProcessingPending}}catch(u){throw l?u:(0,c.markSessionResponseReceived)(u)}}async postCheckoutSessionCreate(e,t,n,s){let i={"Content-Type":"application/json",[c.FLO_SDK_VERSION_HEADER]:c.SDK_VERSION},o=(0,c.resolveIdempotencyKey)(t.idempotencyKey);o&&(i[c.IDEMPOTENCY_KEY_HEADER]=o),t.checkoutMode==="auto"&&(i[c.FLO_SDK_CAPABILITIES_HEADER]=c.ASYNC_AUTO_CHECKOUT_CAPABILITY);let a,l=!1,u=vt(t),d=(m,f,h)=>{l||(l=!0,this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:h,attempt:m}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:Math.max(0,this.telemetryTimestamp()-f),durationMode:"machine",requestCategory:"session_create",statusClass:h,attempt:m}))},p=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++){s.attempt=m;let f=this.telemetryTimestamp();try{u?.onAttempt?.(m)}catch{}try{a=await fetch(`${this.baseUrl}/v1/checkouts/sessions?expand=true`,{method:"POST",headers:i,body:JSON.stringify(e),signal:n})}catch(C){if(s.statusClass=n.aborted||C instanceof Error&&C.name==="AbortError"?"timeout":"network_error",n.aborted||C instanceof Error&&C.name==="AbortError"||m>=2)throw C;let v=m+1;p(v),await q(m,n);continue}let h=(0,c.telemetryStatusClass)(a.status);if(s.statusClass=h,a.status===204)throw d(m,f,h),new c.FloPayError("Session auto-completed \u2014 payment method already on file","api_error",{code:"session_auto_completed"});if(a.ok){d(m,f,h);break}let g=await E(a,"Failed to create checkout session");if(g.code===c.IDEMPOTENCY_IN_PROGRESS_CODE&&m<2){p(m+1),await q(m,n);continue}throw d(m,f,h),g}if(!a)throw new TypeError("Checkout-session creation exhausted its retry budget.");return a}async createDetachedSession(e){this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp(),n=D(e.timeoutMs??12e3),s={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let i=e.products??(0,c.foldIntoProducts)(e.items,e.subscriptions);try{(0,c.assertCaptureMethodEligible)({captureMethod:e.captureMethod,products:i})}catch(v){throw n.clear(),this.reportSessionCreateFailure(v,t,s),v}let o=(0,c.resolveSessionCurrency)(e.currency,e.items,e.subscriptions,i);if(!o)throw n.clear(),this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),new c.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{_e(e,o,i)}catch(v){throw n.clear(),this.reportSessionCreateFailure(v,t,s),v}let a,l,u=!1;try{let v=await this.postCheckoutSessionCreate(bt(e,o),e,n.signal,s);if(u=!0,l=await v.json(),!l.data||!("gateways"in l.data))throw new c.FloPayError("The billing API returned no session shell for a detached create. It must support `deferDataAttachment` (TeamFloPay/backend#1099).","api_error",{code:"InvalidCheckoutSessionResponse"});a=this.normalizeRawSession(this.mergeCachedDisplayData(l.data)),l.vault&&a.data.session&&(a.data.session.vault=this.toVaultBlock(l.vault))}catch(v){throw n.clear(),u&&(0,c.markSessionResponseReceived)(v),this.reportSessionCreateFailure(v,t,s),v}let d=a.data.session?.id??l.data.uuid??"",p=a.data.session?.clientSecret??l.data.nonce??"";if(!d||!p){n.clear();let v=new c.FloPayError("Checkout session shell was created without a session id or nonce.","api_error",{code:"InvalidCheckoutSessionResponse"});throw this.reportSessionCreateFailure(v,t,s),v}n.clear(),this.adoptDirectTelemetryCheckout(d),this.directTelemetry?.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",statusClass:s.statusClass,paymentMethodCategory:"card"}),this.directTelemetry?.performance({stage:"session_shell",durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:"session_create",statusClass:s.statusClass,attempt:s.attempt,paymentMethodCategory:"card"});let m=!e.account.email?.trim(),f=D(e.timeoutMs??12e3),h=this.claimCheckoutSession(d,p,m?_t(e,o,i):_e(e,o,i),{params:e,startedAt:t,deadline:f,createAttempt:s.attempt}),g=m?void 0:h,C=(v={})=>{if(g!==void 0)return g;let _={...e,account:{...e.account,...v,email:v.email?.trim()||e.account.email?.trim()}};return(0,c.isValidEmail)(_.account.email)?(g=h.then(()=>{let y=this.telemetryTimestamp();return this.claimCheckoutSession(d,p,St(_.account),{params:_,startedAt:y,deadline:D(e.timeoutMs??12e3),createAttempt:0})}),g.catch(()=>{}),g):Promise.reject(new c.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}))};return h.catch(()=>{}),{shell:a,sessionId:d,nonce:p,claimed:h,claim:C}}async claimCheckoutSession(e,t,n,s){let i=s?.startedAt??this.telemetryTimestamp(),o=this.telemetryTimestamp(),a=s?.deadline??D(12e3),l=JSON.stringify(n),u="unknown",d=0,p=!1;this.directTelemetry?.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"});try{let m;for(d=0;d<3;d++){try{m=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/claim`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":t,[c.FLO_SDK_VERSION_HEADER]:c.SDK_VERSION},body:l,signal:a.signal})}catch(g){let C=a.signal.aborted||g instanceof Error&&g.name==="AbortError";if(u=C?"timeout":"network_error",C||d>=2)throw g;try{this.telemetryHooks?.onRetry?.("session_claim",d+1),this.directTelemetry?.log({name:"operation.retry",stage:"session_claim",requestCategory:"session_claim",attempt:d+1})}catch{}await q(d,a.signal);continue}if(u=(0,c.telemetryStatusClass)(m.status),m.ok)break;throw await E(m,"Failed to attach checkout session data")}if(!m)throw new TypeError("Checkout-session claim exhausted its retry budget.");p=!0;let f=await m.json();if(!f.data?.gateways)throw new c.FloPayError("The billing API returned no checkout session with gateways after claiming it.","api_error",{code:"InvalidCheckoutSessionResponse"});s?.params&&this.autoCacheDisplayData(f.data.uuid??e,s.params);let h=this.normalizeRawSession(this.mergeCachedDisplayData(f.data));return f.vault&&h.data.session&&(h.data.session.vault=this.toVaultBlock(f.vault)),this.directTelemetry?.log({name:"session.claim.completed",stage:"session_claim",requestCategory:"session_claim",statusClass:u}),this.directTelemetry?.performance({stage:"session_claim",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"session_claim",statusClass:u,attempt:d}),this.directTelemetry?.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:u}),this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-i),durationMode:"machine",requestCategory:"session_create",statusClass:u,attempt:s?.createAttempt??d}),h}catch(m){throw p&&(0,c.markSessionResponseReceived)(m),this.reportSessionCreateFailure(m,o,{attempt:d,statusClass:u},"session_claim"),m}finally{a.clear()}}reportSessionCreateFailure(e,t,n,s="session_create"){if(!(e instanceof c.FloPayError&&e.code==="session_auto_completed"))try{this.telemetryHooks?.onSessionCreateFailure?.(e)}catch{}let i=(0,c.classifyTelemetryFailure)(e,"CHECKOUT_SESSION_CREATE_FAILED");if(this.directTelemetry?.performance({stage:s,durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:s==="session_claim"?"session_claim":"session_create",statusClass:i.statusClass,attempt:n.attempt}),e instanceof c.FloPayError&&e.type==="validation_error"||e instanceof c.FloPayError&&be(e.statusCode)){this.directTelemetry?.terminal({outcome:"validation_rejected",stage:s,requestCategory:s==="session_claim"?"session_claim":"session_create",...e.type==="validation_error"?{}:{statusClass:"4xx"}});return}e instanceof c.FloPayError&&e.code==="session_auto_completed"||this.directTelemetry?.error({...i,stage:s,requestCategory:s==="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(),s=t?.paymentMethodCategory??"saved";this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:s});let i=t?.timeoutMs??B,o=Date.now()+i,a=new AbortController,l=!1,u,d=setTimeout(()=>{u=setTimeout(()=>{l=!0,a.abort()},ve)},i),p=()=>a.abort(t?.signal?.reason);t?.signal?.aborted?p():t?.signal?.addEventListener("abort",p,{once:!0});let m=this.clampRetryAfterMs(t?.initialDelayMs??fe),f=0;try{if(t?.statusUrl){let h=await this.waitForCheckoutStatus(e,{initialDelayMs:m,timeoutMs:i,nonce:t.nonce,statusUrl:t.statusUrl,pollAfterAction:t.continueAfterActionRequired,signal:a.signal});if(h){let g=await this.resolveCheckoutSessionStatus(e,h,t.nonce,a.signal,()=>l);return this.reportRecoveryCompleted(n,s,t.challengeAttemptId),g}}for(;;){let h=o-Date.now();if(h<=0)throw S();if(m>0){try{f+=1,this.telemetryHooks?.onRetry?.("session_read",f),this.directTelemetry?.log({name:"operation.retry",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:s,attempt:f})}catch{}if(await Z(Math.min(m,h),a.signal),Date.now()>=o)throw S()}let g=await this.getUnifiedCheckoutSessionForRecovery(e,t?.nonce,a.signal),C=g.data.session?.status;if(C==="authorized"||C==="complete"||C==="expired")return this.reportRecoveryCompleted(n,s,t?.challengeAttemptId),g;if(Date.now()>=o)throw S();m=this.clampRetryAfterMs(Math.max(m*2,Ce))}}catch(h){let g=l&&X(h)?S():h;throw this.reportDirectFailure(g,"RECOVERY_FAILED","recovery","session_read",s),g}finally{clearTimeout(d),clearTimeout(u),t?.signal?.removeEventListener("abort",p)}}reportRecoveryCompleted(e,t,n){let s={stage:"recovery",requestCategory:"session_read",paymentMethodCategory:t};if(this.directTelemetry?.log({name:"operation.recovery.completed",...s}),n)try{this.directTelemetry?.beginThreeDsChallenge({attemptId:n}).record("recovery_read_completed",{evidenceBasis:"server_status"})}catch{}this.directTelemetry?.performance({...s,durationMs:Math.max(0,this.telemetryTimestamp()-e),durationMode:"machine"})}async resolveCheckoutSessionStatus(e,t,n,s,i){let o=t.latestTransactionAttempt;if(this.rememberReportedFailure(e,t),o?.result==="DECLINE"){let u=o.code===c.STORED_PAYMENT_METHOD_UNSUPPORTED_CODE;throw new c.FloPayError(u?c.STORED_PAYMENT_METHOD_UNSUPPORTED_MESSAGE:"Payment was declined. Please choose another payment method.","api_error",{code:o.code??o.declineReason??"authorization_declined",statusCode:400})}if(o?.result==="ERROR"||t.status==="voided")throw new c.FloPayError("Payment could not be completed. Please try again.","api_error",{code:o?.code??"payment_processing_error",statusCode:500});let a;try{a=await this.getUnifiedCheckoutSessionForRecovery(e,n,s)}catch(u){if(!i?.()||!X(u))throw u;a={providers:[],mode:"tokenize",data:{},raw:t}}let l=a.data.session;return l&&o?.result==="SUCCESS"?{...a,data:{...a.data,session:{...l,status:"complete"}}}:l&&o?.result==="AUTHORIZED"?{...a,data:{...a.data,session:{...l,status:"authorized",paymentId:t.paymentId??void 0,authorizationExpiresAt:t.authorizationExpiresAt??void 0}}}:l&&t.status==="completed"?{...a,data:{...a.data,session:{...l,status:"complete"}}}:l&&t.status==="authorized"?{...a,data:{...a.data,session:{...l,status:"authorized",paymentId:t.paymentId??void 0,authorizationExpiresAt:t.authorizationExpiresAt??void 0}}}:l&&t.status==="expired"?{...a,data:{...a.data,session:{...l,status:"expired"}}}:o?.result!=="ACTION_REQUIRED"?a:o.gateway==="paypal"&&o.providerIntentId?{...a,autoProcessingError:{type:"paypal_direct_required",message:"PayPal authorization required",orderId:o.providerIntentId,checkoutMethod:"paypal"}}:o.nextActionRedirectUrl?{...a,autoProcessingError:{type:"3ds_required",message:"Additional authentication is required.",nextActionRedirectUrl:o.nextActionRedirectUrl}}:a}async waitForCheckoutStatus(e,t){let n=t.timeoutMs??B,s=Date.now()+n,i=this.clampRetryAfterMs(t.initialDelayMs);for(;;){let o=s-Date.now();if(o<=0||i>0&&(await Z(Math.min(i,o),t.signal),Date.now()>=s))throw S();let a=s-Date.now();if(a<=0)throw S();let l=new AbortController,u,d=t.signal?new Promise((_,y)=>{u=y}):null,p=()=>{l.abort(t.signal?.reason),u?.(t.signal?.reason??Object.assign(new Error("The operation was aborted."),{name:"AbortError"}))};t.signal?.aborted?p():t.signal?.addEventListener("abort",p,{once:!0});let m,f=t.signal?null:new Promise((_,y)=>{m=setTimeout(()=>{y(S()),l.abort()},a+ve)}),h;try{let _=this.fetchCheckoutStatus(e,t.nonce,t.statusUrl,l.signal);h=await Promise.race([_,f,d].filter(y=>y!==null))}finally{m!==void 0&&clearTimeout(m),t.signal?.removeEventListener("abort",p)}if(!h)return null;let g=ge(h.latestTransactionAttempt)&&!this.isOwnFailedAttempt(e,h,t.submittedIntentId);if(h.status==="completed"||h.status==="authorized"||h.status==="expired"||h.status==="voided")return g?{...h,latestTransactionAttempt:null}:h;let C=h.latestTransactionAttempt?.result,v=t.pollAfterAction===!0&&C==="ACTION_REQUIRED";if(!g&&C!==void 0&&C!=="PENDING"&&!v)return h;i=this.clampRetryAfterMs(Math.max(i*2,Ce))}}isOwnFailedAttempt(e,t,n){let s=t.latestTransactionAttempt?.providerIntentId??null;return n!==void 0?s===n:s===null?!0:!ct(t.uuid||e,s)}rememberReportedFailure(e,t){let n=t.latestTransactionAttempt;!ge(n)||!n.providerIntentId||lt(t.uuid||e,n.providerIntentId)}async fetchCheckoutStatus(e,t,n,s){let i=`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/status`,o=i;if(n)try{let d=new URL(n,`${this.baseUrl}/`),p=new URL(i);d.origin===p.origin&&(o=d.toString())}catch{}let a={[c.FLO_SDK_VERSION_HEADER]:c.SDK_VERSION};t&&(a["x-checkout-session-token"]=t);let l=await z(o,{headers:a,signal:s});if(l.status===404||l.status===405)return null;if(!l.ok)throw await E(l,"Failed to get checkout session status");let u=await l.json();return F(u.data)&&"latestTransactionAttempt"in u.data?u.data:null}normalizeRawSession(e){let t=e.gateways??{},n=[],s={session:this.toCheckoutSession(e)},i=t.stripe;if(i?.publishableKey){n.push("stripe");let l=[e.stripeClientSecret,i.stripeClientSecret].find(u=>typeof u=="string"&&u.length>0);s.stripe={clientSecret:l??"",publishableKey:i.publishableKey??void 0,paypalPublishableKey:i.paypalPublishableKey??void 0,environment:i.environment,enabledPaymentMethods:Array.isArray(i.enabledPaymentMethods)?i.enabledPaymentMethods.filter(u=>typeof u=="string"):void 0}}let o=t.paypal;return o?.publishableKey&&(n.push("paypal"),s.paypal={publishableKey:o.publishableKey,environment:o.environment,providerObjectType:o.providerObjectType,approvalPresentation:o.approvalPresentation}),{providers:n,mode:"tokenize",...e.checkoutMetadata===void 0?{}:{checkoutMetadata:e.checkoutMetadata},data:s,raw:{data:e}}}toCheckoutSession(e){let t=e.products??[],n=typeof e.totalAmount=="number"&&Number.isFinite(e.totalAmount),s=t.reduce((u,d)=>u+(d.overrideAmount??d.totalAmount??0),0),i=n?e.totalAmount:s,o=Math.round(i*100),a=e.currency??t[0]?.currency??"USD",l="payment";return e.checkoutMode==="setup"?l="setup":t.some(u=>u.type==="subscription")&&(l="subscription"),{id:e.uuid,clientSecret:e.nonce,mode:l,status:this.toCheckoutSessionStatus(e.status),amount:o,currency:a,captureMethod:e.captureMethod,paymentId:e.paymentId,authorizationExpiresAt:e.authorizationExpiresAt,failureOutcome:(0,c.normalizeCheckoutFailureOutcome)(e.outcome)??(0,c.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}:{},...rt(e.futureUse)?{futureUse:e.futureUse}:{},...Array.isArray(e.futureUseUnsupported)?{futureUseUnsupported:e.futureUseUnsupported.filter(nt)}:{},buyerIdentified:e.buyerIdentified,providerPaymentMethodId:typeof e.providerPaymentMethodId=="string"?e.providerPaymentMethodId:null,products:t.map(u=>({...u,totalAmount:typeof u.totalAmount=="number"?u.totalAmount:void 0,overrideAmount:typeof u.overrideAmount=="number"?u.overrideAmount:null,currency:typeof u.currency=="string"?u.currency:void 0,metadata:u.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=gt(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 s=await e.json().catch(()=>null),i=this.toCheckoutProcessingPending(s,e,t);return this.resolveCheckoutProcessing(i,t,n)}async resolveCheckoutProcessing(e,t,n){let s=n?.pollTimeoutMs??B,i=Date.now()+s;if(e.statusUrl){let a=await this.waitForCheckoutStatus(e.sessionId,{initialDelayMs:e.retryAfterMs,timeoutMs:s,nonce:n?.nonce,statusUrl:e.statusUrl,submittedIntentId:n?.submittedIntentId});if(a)return this.toProcessResponseFromStatus(a,t,n?.nonce)}let o=await this.waitForCheckoutSessionCompletion(e.sessionId,{initialDelayMs:e.retryAfterMs,timeoutMs:i-Date.now(),nonce:n?.nonce,paymentMethodCategory:n?.paymentMethodCategory});return this.toProcessResponseFromSession(o,t)}async toProcessResponseFromStatus(e,t,n){let s=e.latestTransactionAttempt?.result,i={[it]:ot},o={"Content-Type":"application/json",...i};if(e.status==="completed"||s==="SUCCESS")return new Response(null,{status:204,statusText:"No Content",headers:i});if(e.status==="authorized"||s==="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:o});if(e.status==="expired"){let a=await this.resolveCheckoutSessionStatus(t,e,n);return this.toProcessResponseFromSession(a,t)}if(this.rememberReportedFailure(t,e),s==="DECLINE"){let a=e.latestTransactionAttempt,l=a?.code===c.STORED_PAYMENT_METHOD_UNSUPPORTED_CODE,u=a?.declineReason??void 0;return new Response(JSON.stringify({type:u??"authorization_declined",message:l?c.STORED_PAYMENT_METHOD_UNSUPPORTED_MESSAGE:"Payment was declined. Please choose another payment method.",code:a?.code??u??"authorization_declined",...u?{declineCode:u}:{}}),{status:400,headers:o})}if(s==="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:o});if(s==="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:o});if(s==="ERROR"||e.status==="voided")return new Response(JSON.stringify({type:"unknown",code:e.latestTransactionAttempt?.code??"payment_processing_error",message:st(e)??"Payment could not be completed. Please try again."}),{status:500,headers:o});throw S()}async reconcileProcessPayment(e,t){let n=t?.pollTimeoutMs??B,s=Date.now()+n,i=null;try{i=await this.waitForCheckoutStatus(e,{initialDelayMs:0,timeoutMs:n,nonce:t?.nonce,submittedIntentId:t?.submittedIntentId})}catch(l){if(this.reportDirectFailure(l,"RECOVERY_FAILED","recovery","session_read",t?.paymentMethodCategory??"saved"),l instanceof c.FloPayError&&l.code==="checkout_processing_timeout")throw l}if(i)return this.toProcessResponseFromStatus(i,e,t?.nonce);let o=s-Date.now();if(o<=0)throw S();let a=await this.waitForCheckoutSessionCompletion(e,{initialDelayMs:0,timeoutMs:o,nonce:t?.nonce,paymentMethodCategory:t?.paymentMethodCategory});return this.toProcessResponseFromSession(a,e)}toProcessResponseFromSession(e,t){if(e.data.session?.status==="complete")return new Response(null,{status:204,statusText:"No Content"});if(e.data.session?.status==="authorized"){let n=e.data.session;return new Response(JSON.stringify({status:"authorized",paymentId:n.paymentId,sessionId:n.id||t,authorizationExpiresAt:n.authorizationExpiresAt}),{status:200,headers:{"Content-Type":"application/json"}})}if(e.data.session?.status==="expired"){let n=e.data.session.failureOutcome==="authorization_expired"||e.data.session.captureMethod==="manual";throw new c.FloPayError(n?"Authorization has expired.":"Checkout session has expired.","api_error",{code:n?"authorization_expired":"checkout_session_expired"})}throw S()}toCheckoutProcessingPending(e,t,n){let s=t.headers.get("Retry-After"),i=s===null||s.trim()===""?void 0:Number(s),o=i!==void 0&&Number.isFinite(i)?i*1e3:void 0;return{type:"checkout_processing",sessionId:k(e,"sessionId")??n,retryAfterMs:this.clampRetryAfterMs(pt(e,"retryAfterMs")??o??fe),statusUrl:k(e,"statusUrl"),sessionUrl:k(e,"sessionUrl")}}clampRetryAfterMs(e){return Math.max(0,Math.min(e,dt))}autoCacheDisplayData(e,t){if(!e)return;let n=t.products??(0,c.foldIntoProducts)(t.items,t.subscriptions);if(n.length===0&&!t.currency)return;let s=t.products!==void 0,i=(0,c.resolveSessionCurrency)(t.currency,s?void 0:t.items,s?void 0:t.subscriptions,n);W(e,{currency:i??void 0,products:n.map(o=>({code:o.code??o.providerItemId??o.providerPlanId,type:o.type,name:o.name??o.itemName??o.providerItemName??o.subscriptionName??o.providerPlanName??null,totalAmount:o.totalAmount,overrideAmount:o.overrideAmount,currency:o.currency??i??void 0}))})}mergeCachedDisplayData(e){let t=se(e.uuid),n=new Map,s=o=>o?`code:${o}`:void 0;for(let o of t?.products??[]){let a=s(o.code);a&&n.set(a,o)}let i=(e.products??[]).map(o=>{let a=s(o.code),l=a?n.get(a):void 0;return{...o,name:o.name??l?.name??null,totalAmount:o.totalAmount??l?.totalAmount,overrideAmount:o.overrideAmount??l?.overrideAmount,currency:o.currency??l?.currency}});return{...e,currency:e.currency??t?.currency,products:i}}};I.activeVaultCaptureRequests=new Map;var j=I;var T=require("@flopay/shared");var Rt=4,ee="flopay-vault",At=3e4,wt=T.THREE_DS_CHALLENGE_WINDOW_MS+At,Et="Card authentication timed out.",Ae={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 kt(r){return r.class==="lifecycle"?r.name:r.class==="technical_error"?r.code:r.class==="expected_outcome"?r.outcome:"sdk.performance"}function P(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:kt(r),data:e})}catch{}}function U(r,e){return(0,T.buildTelemetryLogEvent)({eventId:"11111111-1111-4111-8111-111111111111",name:r,stage:e,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}var Mt=new Set(["authorization_declined","authentication_required","authorization_expired","capture_failed"]);function It(r){return typeof r=="string"&&Mt.has(r)?r:"unknown"}var Dt=new Set(["verification_failed","verification_expired"]);function Pt(r){return r==null?!0:typeof r=="string"&&Dt.has(r)}var Ot="vault_mount";function xt(r){return r.failureStage===Ot}function we(r,e){return r&&!xt(e)?{errorCode:"VAULT_SUBMIT_FAILED",stage:"vault_submit",failureCategory:"provider_runtime",reason:It(e.failureOutcome)}:{errorCode:"VAULT_LOAD_FAILED",stage:"vault_mount",failureCategory:"provider_runtime"}}function Ee(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 Ft(r,e,t,n="checkout"){let{type:s}=r;if(s==="complete"||s==="decline")return(0,T.buildTelemetryTerminalEvent)({eventId:"22222222-2222-4222-8222-222222222222",outcome:Ee(r,t,n),sequence:0,provider:"pcivault",paymentMethodCategory:"card"});if(s==="error"){let a=we(e,r);return(0,T.buildTelemetryErrorEvent)({eventId:"33333333-3333-4333-8333-333333333333",...a,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}let[i,o]=Ae[s];return U(i,o)}function Ut(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===ee&&(e.type==="ready"||e.type==="submitting"||e.type==="blocked"||e.type==="complete"||e.type==="decline"||e.type==="error"||e.type==="action_required")}function qt(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 Lt(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 Nt(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===ee&&e.type==="validation"&&Array.isArray(e.messages)}function Vt(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===ee&&e.type==="resize"&&typeof e.height=="number"&&Number.isFinite(e.height)}var K=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 w({billingApiUrl:(0,T.resolveBillingApiUrl)(e.billingApiUrl),sdkVersion:T.SDK_VERSION}):void 0)}async mount(e,t){this.ownsTelemetryReporter&&!this.telemetryReporter&&(this.telemetryReporter=new w({billingApiUrl:(0,T.resolveBillingApiUrl)(this.config.billingApiUrl),sdkVersion:T.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?.()??R(),this.vaultReadyReported=!1,this.submissionStarted=!1,this.submissionStartedAt=null,typeof window>"u"||typeof document>"u")throw this.reportVaultLoadFailure(),new T.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 T.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(s){throw this.reportVaultLoadFailure(),s}this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),this.postSubmitLabel(),P(U("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?.()??R())-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 s of n){let i=document.createElement("script");for(let o of Array.from(s.attributes))i.setAttribute(o.name,o.value);i.text=s.text,s.replaceWith(i)}}attachMessageListener(){if(this.messageHandler)return;let e=t=>{if(this.expectedOrigin&&t.origin!==this.expectedOrigin)return;let n=t.data;if(Vt(n)){if(this.messageToken&&n.messageToken!==this.messageToken)return;this.applyHeight(n.height);return}if(Nt(n)){if(this.messageToken&&n.messageToken!==this.messageToken)return;let u=n.messages.filter(d=>typeof d=="string"&&d.trim()).join(" ");this.emit("validation",{sessionId:this.config.sessionId,message:u||void 0});return}if(!Ut(n)||this.messageToken&&n.messageToken!==this.messageToken)return;let s=this.config.sessionId,i=typeof n.sessionId=="string"?n.sessionId:void 0;if(s&&i&&i!==s||(n.type==="complete"||n.type==="decline")&&s&&i!==s)return;let o=Lt(n.paymentMethod),a=qt(n.vaultOutcome),l={...n.sessionId??this.config.sessionId?{sessionId:n.sessionId??this.config.sessionId}:{},...n.outcome?{outcome:n.outcome}:{},...n.paymentId?{paymentId:n.paymentId}:{},...n.authorizationExpiresAt?{authorizationExpiresAt:n.authorizationExpiresAt}:{},...n.failureOutcome?{failureOutcome:n.failureOutcome}:{},...n.intentId?{intentId:n.intentId}:{},...n.declineReason?{declineReason:n.declineReason}:{},...n.message?{message:n.message}:{},...a?{vaultOutcome:a}:{},...o?{paymentMethod:o}:{}};n.type==="submitting"&&(this.submissionStarted=!0,this.submissionStartedAt=this.telemetryReporter?.now?.()??R()),this.isVerificationStateError(n)?(P(U("operation.state_transition","vault_mount")),this.telemetryReporter?.log({name:"operation.state_transition",stage:"vault_mount",provider:"pcivault",paymentMethodCategory:"card"})):(P(Ft(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,l)};this.messageHandler=e,window.addEventListener("message",e)}isVerificationStateError(e){return e.type==="error"&&this.verificationRequired&&!this.submissionStarted&&Pt(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:Ee(e,this.config.captureMethod,this.config.operation),provider:"pcivault",paymentMethodCategory:"card"});return}if(n==="error"){let o=we(this.submissionStarted,e);t.log({name:"vault.terminal",stage:o.stage,provider:"pcivault",paymentMethodCategory:"card"}),t.error({...o,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 o=this.submissionStartedAt;this.submissionStartedAt=null,o!==null&&t.performance({stage:"three_ds_handoff",durationMs:Math.max(0,t.now()-o),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:"action_required",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"});return}let[s,i]=Ae[n];t.log({name:s,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:s}=this;e===void 0||!t||!n||!s||this.postToHostedWindow({source:"flopay-vault-host",type:"submitLabel",sessionId:t,messageToken:n,label:e},s)}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 h=this.actionOverlay.querySelector("iframe");h instanceof HTMLIFrameElement&&h.src!==e&&(h.src=e),this.armActionRequiredTimeout();return}this.actionOverlayPreviousFocus=document.activeElement instanceof HTMLElement?document.activeElement:null;let t=ce(this.beginActionChallengeAttempt()),n=de(e),s=!1,i=h=>{if(s)return;let g=ue(h,n);g&&(s=!0,t.record("policy_violation",{reason:g,evidenceBasis:"parent_csp_event"}))},o=()=>{t.record("pagehide_observed",{evidenceBasis:"page_lifecycle_event"})},a={telemetry:t,loaded:!1,detach:()=>{document.removeEventListener("securitypolicyviolation",i),window.removeEventListener("pagehide",o)}};this.actionChallenge=a,this.lastChallengeTelemetry=t,t.record("handoff_planned"),J(e)==="invalid"&&t.record("action_invalid",{reason:"invalid_url"}),document.addEventListener("securitypolicyviolation",i),window.addEventListener("pagehide",o);let l=document.createElement("div");l.setAttribute("data-flopay-action-required","1"),l.setAttribute("role","dialog"),l.setAttribute("aria-modal","true"),l.setAttribute("aria-label","Card authentication"),l.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let u=document.createElement("iframe");u.setAttribute("title","Card authentication"),u.setAttribute("allow","payment"),u.tabIndex=0,u.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(";"),u.addEventListener("load",()=>{a.loaded||(a.loaded=!0,t.record("iframe_load",{evidenceBasis:"iframe_load_event"}))}),u.src=e,l.appendChild(u);let d=document.createElement("button");d.type="button",d.setAttribute("aria-label","Close card authentication"),d.textContent="\xD7",d.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(";"),d.addEventListener("click",()=>this.abandonActionRequiredOverlay()),l.appendChild(d),l.addEventListener("click",h=>{h.target===l&&this.abandonActionRequiredOverlay()});let p=0,m=h=>{let g=h.data,C=!!g&&typeof g=="object"&&g.source==="flopay-vault-3ds-return";if(h.source!==u.contentWindow){C&&p<Rt&&(p+=1,t.record("return_rejected",{reason:"untrusted_source",evidenceBasis:"message_origin_check"}));return}C&&(t.record("trusted_return",{evidenceBasis:"message_origin_check"}),t.terminal("trusted_return",{evidenceBasis:"message_origin_check"}),P(U("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(l)}catch(h){throw t.record("render_failed"),this.hideActionRequiredOverlay(),this.actionOverlayPreviousFocus=null,h}t.record("container_attached"),t.record("navigation_assigned");let f=le(l);f&&t.record("container_visibility",{reason:f,evidenceBasis:"parent_computed_style"}),this.actionOverlay=l,u.focus(),this.armActionRequiredTimeout(),P(U("vault.three_ds.handoff","three_ds_handoff"))}armActionRequiredTimeout(){this.actionOverlayTimer&&clearTimeout(this.actionOverlayTimer),this.actionOverlayTimer=setTimeout(()=>{this.actionOverlayTimer=null,this.actionOverlay&&this.timeOutActionRequiredOverlay()},wt)}reportChallengeAbandoned(){P((0,T.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:Et})}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`}};var Bt=["setup_intent","setup_intent_client_secret","redirect_status"];function ke(){if(typeof window>"u")return null;let r=new URLSearchParams(window.location.search);return!r.has("setup_intent")||!r.has("redirect_status")?null:{failed:r.get("redirect_status")==="failed"}}function Me(){if(typeof window>"u")return;let r=new URL(window.location.href),e=!1;for(let t of Bt)r.searchParams.has(t)&&(r.searchParams.delete(t),e=!0);e&&window.history.replaceState(window.history.state,"",r.toString())}0&&(module.exports={PaymentAPI,PciVaultCardCapture,clearSetupRedirectParams,readSetupRedirectReturn});
1
+ "use strict";var $=Object.defineProperty;var Fe=Object.getOwnPropertyDescriptor;var Ue=Object.getOwnPropertyNames;var qe=Object.prototype.hasOwnProperty;var Le=(r,e)=>{for(var t in e)$(r,t,{get:e[t],enumerable:!0})},Ne=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ue(e))!qe.call(r,s)&&s!==t&&$(r,s,{get:()=>e[s],enumerable:!(n=Fe(e,s))||n.enumerable});return r};var Ve=r=>Ne($({},"__esModule",{value:!0}),r);var zt={};Le(zt,{PaymentAPI:()=>j,PciVaultCardCapture:()=>K,clearSetupRedirectParams:()=>Me,readSetupRedirectReturn:()=>ke});module.exports=Ve(zt);var c=require("@flopay/shared");function re(r){return typeof r=="string"&&r.trim()?r:void 0}function ne(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 D(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 Be(){return Object.assign(new Error("The operation was aborted."),{name:"AbortError"})}function q(r,e){let t=150*2**r,n=Math.round(t*(.75+Math.random()*.5));return new Promise((s,i)=>{let o,a=()=>e.removeEventListener("abort",l),l=()=>{o!==void 0&&clearTimeout(o),a(),i(Be())};if(e.aborted){l();return}o=setTimeout(()=>{a(),s()},n),e.addEventListener("abort",l,{once:!0})})}var ze="flopay_session_display:";var L=new Map;function N(r){return`${ze}${r}`}function Y(){if(typeof window>"u")return null;try{return window.sessionStorage}catch{return null}}function W(r,e,t){if(!r)return;let n=t?.ttlMs??36e5,s={data:e,expiresAt:Date.now()+n},i=Y();if(i)try{i.setItem(N(r),JSON.stringify(s));return}catch{}L.set(r,s)}function se(r){if(!r)return null;let e=Y();if(e)try{let n=e.getItem(N(r));if(n){let s=JSON.parse(n);if(s&&typeof s.expiresAt=="number"&&s.expiresAt>Date.now())return s.data;e.removeItem(N(r))}}catch{}let t=L.get(r);if(t){if(t.expiresAt>Date.now())return t.data;L.delete(r)}return null}function ie(r){if(!r)return;L.delete(r);let e=Y();if(e)try{e.removeItem(N(r))}catch{}}var b=require("@flopay/shared");var J=require("@flopay/shared"),He=32,oe=Symbol.for("@flopay/js.three-ds-challenge.attempts.v1");function je(){let r=globalThis,e=r[oe];if(e instanceof Map)return e;let t=new Map;try{Object.defineProperty(r,oe,{configurable:!0,enumerable:!1,writable:!1,value:t})}catch{}return t}function Ke(r,e){let t=je(),n=t.get(r);if(n)return n;for(;t.size>=He;){let i=t.keys().next();if(i.done)break;t.delete(i.value)}let s={nextSequence:0,startedAt:e,terminated:!1,reconciled:new Set,provider:"unknown"};return t.set(r,s),s}var Ge=new Set(["pagehide_observed","cancel_requested","abort_observed","browser_terminal"]),$e=new Set(["teardown","recovery_read_completed","provider_reconciled"]);function ae(r,e={}){let t=(0,J.isThreeDsChallengeAttemptId)(e.attemptId)?e.attemptId.toLowerCase():r.newAttemptId(),n=()=>{try{let a=r.now();return Number.isFinite(a)?a:0}catch{return 0}},s=Ke(t,n());(e.provider==="stripe"||e.provider==="worldpay")&&(s.provider=e.provider);let i=s.provider,o=(a,l)=>{if(s.terminated&&!$e.has(a))return;let u={attemptId:t,phase:a,attemptSequence:s.nextSequence,elapsedMs:Math.max(0,n()-s.startedAt),provider:i};s.nextSequence+=1,l.reason!==void 0&&(u.reason=l.reason),l.evidenceBasis!==void 0&&(u.evidenceBasis=l.evidenceBasis),l.terminalSource!==void 0&&(u.terminalSource=l.terminalSource),l.providerOutcome!==void 0&&(u.providerOutcome=l.providerOutcome);try{r.emit(u,Ge.has(a))}catch{}};return{attemptId:t,record(a,l={}){a==="browser_terminal"||a==="provider_reconciled"||o(a,{reason:l.reason,evidenceBasis:l.evidenceBasis})},terminal(a,l={}){s.terminated||(o("browser_terminal",{terminalSource:a,reason:l.reason,evidenceBasis:l.evidenceBasis}),s.terminated=!0)},reconcile(a){s.reconciled.has(a)||(s.reconciled.add(a),o("provider_reconciled",{providerOutcome:a,evidenceBasis:"provider_fact"}))}}}function ce(r){let e=null;try{e=(0,J.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 Q(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 le(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 ue(r,e){if(!e)return null;try{let t=r,n=String(t.effectiveDirective||t.violatedDirective||"").trim().split(/\s+/)[0],s=null;return n==="frame-src"&&(s="frame_src"),n==="child-src"&&(s="child_src"),!s||typeof t.blockedURI!="string"?null:new URL(t.blockedURI).origin===e?s:null}catch{return null}}function de(r){try{return Q(r)==="valid"?new URL(r).origin:null}catch{return null}}var Ye="/v1/sdk-telemetry/events",V=16,me=64,We=1500,he=1e3,Je=64,Qe="00000000-0000-4000-8000-000000000000",Xe={technical_error:8,lifecycle:32,expected_outcome:32,performance:24},Ze=48;function w(){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 et(r){try{return new TextEncoder().encode(r).byteLength}catch{return r.length}}function tt(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 R(){return globalThis.performance?.now()??0}var E=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(/\/+$/,"")}${Ye}`,this.sdkPackage=e.sdkPackage??"@flopay/js",this.sdkVersion=e.sdkVersion,this.correlationId=w(),this.merchantEnabled=e.enabled!==!1,this.clock=e.clock??R,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,b.buildTelemetryLogEvent)({...this.checkoutContext,...e,eventId:w(),sequence:this.sequence++}))}error(e){if(this.notify({...e,class:"technical_error"}),!this.canCollect())return;let t=(0,b.buildTelemetryErrorEvent)({...this.checkoutContext,...e,eventId:Qe,sequence:0}),n=tt(t),s=this.now();this.pruneReportedFailures(s);let i=this.reportedFailures.get(n);if(i!==void 0&&s>=i&&s-i<he){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,s),this.enqueue((0,b.buildTelemetryErrorEvent)({...this.checkoutContext,...e,eventId:w(),sequence:this.sequence++}))}performance(e){this.canCollect()&&this.enqueue((0,b.buildTelemetryPerformanceEvent)({...this.checkoutContext,...e,eventId:w(),sequence:this.sequence++}))}terminal(e){if(this.canCollect()&&(this.enqueue((0,b.buildTelemetryTerminalEvent)({...this.checkoutContext,...e,eventId:w(),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 ae({now:()=>this.now(),newAttemptId:w,emit:(t,n)=>this.recordThreeDsChallenge(t,n)},e)}recordThreeDsChallenge(e,t){if(!this.canCollect()||this.threeDsChallengeCount>=Ze)return;let n=(0,b.buildTelemetryLogEvent)({...this.checkoutContext,...e,name:"three_ds.challenge",stage:"three_ds_handoff",eventId:w(),sequence:this.sequence++});if(!(this.queue.length>=me)){if(this.threeDsChallengeCount+=1,this.queue.push(n),t){this.drainQueue();return}if(this.queue.length>=V){this.flush();return}this.scheduleFlush()}}now(){try{return this.clock()}catch{return R()}}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>=he)&&this.reportedFailures.delete(t)}rememberReportedFailure(e,t){for(;this.reportedFailures.size>=Je;){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>=me||this.eventCounts[e.class]>=Xe[e.class])){if(this.eventCounts[e.class]+=1,this.queue.push(e),this.queue.length>=V){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,V);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,V);this.sendBatch(e)}}async sendBatch(e){if(!this.browserTransportAvailable||this.ingestionDisabled)return;let t=(0,b.serializeTelemetryBatch)(e,{correlationId:this.correlationId,sdkPackage:this.sdkPackage,sdkVersion:this.sdkVersion,batchId:w()});if(et(t)>b.TELEMETRY_MAX_BATCH_BYTES)return;let n=typeof AbortController>"u"?null:new AbortController,s=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 l=>{if(l.status!==202)return null;let u=null;try{u=await l.json()}catch{}return u?.status==="disabled"?"disabled":null}).catch(()=>null),o=new Promise(l=>{s=setTimeout(()=>{n?.abort(),l(null)},We)});await Promise.race([i,o])==="disabled"&&this.disableFromIngestion()}catch{}finally{s&&clearTimeout(s)}}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)}},pe=Symbol.for("@flopay/js.telemetry.reporter-factory.v1"),ye=globalThis;ye[pe]===void 0&&Object.defineProperty(ye,pe,{configurable:!0,enumerable:!1,writable:!1,value:r=>new E(r)});function rt(r){return r==="on_session"||r==="off_session"}function nt(r){if(!r||typeof r!="object")return!1;let e=r;return typeof e.paymentMethodType=="string"&&typeof e.reason=="string"}function st(r){let e=r.vaultOutcome;if(!(!e||e.code!==c.CHECKOUT_SESSION_BUYER_EMAIL_REQUIRED))return typeof e.message=="string"&&e.message.trim()!==""?e.message:void 0}var it="x-flopay-process-result-source",ot="status";function ge(r){return r?.result==="DECLINE"||r?.result==="ERROR"}var at=50,M=new Map;function ct(r,e){return M.get(r)?.has(e)===!0}function lt(r,e){let t=M.get(r)??new Set;if(t.add(e),M.delete(r),M.set(r,t),M.size>at){let n=M.keys().next().value;n!==void 0&&M.delete(n)}}function ut(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 fe=0,Ce=500,B=15e3,ve=15e3,dt=3e3,mt=1e4,ht=1e4;function F(r){return typeof r=="object"&&r!==null}function k(r,e){return re(r?.[e])}function Te(r,e){return ne(r?.[e])}function pt(r,e){let t=r?.[e];return typeof t=="number"&&Number.isFinite(t)?t:void 0}function Z(r,e){return e?new Promise((t,n)=>{let s=()=>{clearTimeout(i),n(e.reason??Object.assign(new Error("The operation was aborted."),{name:"AbortError"}))},i=setTimeout(()=>{e.removeEventListener("abort",s),t()},r);e.aborted?s():e.addEventListener("abort",s,{once:!0})}):new Promise(t=>setTimeout(t,r))}function X(r){return r instanceof Error&&r.name==="AbortError"}function S(){return new c.FloPayError(c.CHECKOUT_PROCESSING_TIMEOUT_MESSAGE,"api_error",{code:"checkout_processing_timeout"})}async function A(r,e){let t=await r.json().catch(()=>null),n=F(t?.error)?t.error:null,s=Te(t,"message")??Te(n,"message")??e,i=k(t,"code")??k(t,"gatewayErrorCode")??k(n,"code")??`http_${r.status}`;return(0,c.withTelemetryHttpDiagnostics)(new c.FloPayError(s,"api_error",{code:i,statusCode:r.status}),r)}async function yt(r){if(r.status!==403)return!1;let e=await r.clone().json().catch(()=>null),t=F(e?.error)?e.error:null;return(k(e,"code")??k(t,"code"))==="verification_required"}function gt(r){if(!(!F(r)||typeof r.required!="boolean"))return{required:r.required,provider:"turnstile"}}async function ft(r){let e=r.status===400?await r.clone().json().catch(()=>null):null;return(0,c.classifyPaymentRejection)(r.status,e)}function be(r){return r===400||r===422}var H=2;async function z(r,e,t=H,n,s){let i;for(let o=0;;o++)try{return s?.(o),await fetch(r,e)}catch(a){if(e?.signal?.aborted||a instanceof Error&&a.name==="AbortError")throw a;if(i=a,o>=t)throw i;try{n?.(o+1)}catch{}await Z(150*2**o,e?.signal??void 0)}}var Ct=Symbol.for("@flopay/js.session-create.telemetry.v1");function vt(r){return r[Ct]}function Tt(r){return"now"in r||"onFirstByte"in r||"onSessionCreateFailure"in r||"onRetry"in r}function Se(r){let e=(0,c.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 Re(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 bt(r,e){let t={clientId:r.clientId,checkoutVersion:c.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}),Re(t,r),t}function _e(r,e,t){return{currency:e,products:t.map(n=>(0,c.buildProductPayload)(n,e)),couponCodes:r.couponCodes??[],accountData:Se(r.account)}}function _t(r,e,t){return{currency:e,products:t.map(n=>(0,c.buildProductPayload)(n,e)),couponCodes:r.couponCodes??[]}}function St(r){let e={},t=(0,c.isCardHolderNamePlaceholder)(r.firstName,r.lastName);for(let[n,s]of Object.entries(r)){if(t&&n.endsWith("Name")||typeof s!="string")continue;let i=s.trim();i&&(e[n]=i)}return{accountData:e}}var I=class I{constructor(e,t={}){this.baseUrl=e.replace(/\/+$/,"");let n=Tt(t);this.telemetryHooks=n?t:void 0,this.directTelemetry=n||t.telemetry===!1?void 0:new E({billingApiUrl:this.baseUrl,sdkVersion:c.SDK_VERSION})}destroy(){this.directTelemetry?.destroy()}reportDirectFailure(e,t,n,s,i="unknown"){let o=(0,c.classifyTelemetryFailure)(e,t);this.directTelemetry?.error({...o,stage:n,requestCategory:s,paymentMethodCategory:i})}reportAccountSnapshotFailure(e,t){let n=(0,c.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()??R()}catch{return R()}}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,s){this.beginDirectTelemetryCheckout(e);let i=this.telemetryTimestamp(),o=i,a=0;this.directTelemetry?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let l={[c.FLO_SDK_VERSION_HEADER]:c.SDK_VERSION};t&&(l["x-checkout-session-token"]=t);let u=!1;try{let d=await z(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}`,{headers:l,signal:s},H,h=>{this.telemetryHooks?.onRetry?.("session_read",h),this.directTelemetry?.log({name:"operation.retry",stage:"session_read",requestCategory:"session_read",attempt:h})},h=>{a=h,o=this.telemetryTimestamp()});u=!0;let p=Math.max(0,this.telemetryTimestamp()-o);try{this.telemetryHooks?.onFirstByte?.(p,a)}catch{}let m=`${Math.floor(d.status/100)}xx`;if(this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:m,attempt:a}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:p,durationMode:"machine",requestCategory:"session_read",statusClass:m,attempt:a}),!d.ok)throw await A(d,"Failed to get checkout session");let f=await d.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(d){throw u&&(0,c.markSessionResponseReceived)(d),n&&this.directTelemetry?.error({...(0,c.classifyTelemetryFailure)(d,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"}),d}}cacheSessionDisplayData(e,t,n){W(e,t,n)}clearSessionDisplayData(e){ie(e)}async getVaultCapture(e,t){let n=`${this.baseUrl}\0${e}\0${t??""}`,s=I.activeVaultCaptureRequests.get(n);if(s!==void 0)return s;let i=this.requestVaultCapture(e,t);I.activeVaultCaptureRequests.set(n,i);try{return await i}finally{I.activeVaultCaptureRequests.get(n)===i&&I.activeVaultCaptureRequests.delete(n)}}async requestVaultCapture(e,t){let n=new AbortController,s=setTimeout(()=>n.abort(),ht);this.beginDirectTelemetryCheckout(e);let i=this.telemetryTimestamp();this.directTelemetry?.log({name:"vault.capture.requested",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card"});let o={"Content-Type":"application/json"};t&&(o["x-checkout-session-token"]=t);try{let a=await z(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/vault/capture`,{method:"POST",headers:o,signal:n.signal},H,u=>{this.telemetryHooks?.onRetry?.("vault_capture",u),this.directTelemetry?.log({name:"operation.retry",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card",attempt:u})});if(await yt(a))return this.directTelemetry?.performance({stage:"vault_request",durationMs:Math.max(0,this.telemetryTimestamp()-i),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"4xx"}),{verification:{required:!0,provider:"turnstile"}};if(!a.ok)throw await A(a,"Failed to load the secure card form");let l=await a.json();return this.directTelemetry?.performance({stage:"vault_request",durationMs:Math.max(0,this.telemetryTimestamp()-i),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"2xx"}),this.toVaultBlock(l)}catch(a){let l=n.signal.aborted?new c.FloPayError("Timed out while loading the secure card form. Please try again.","api_error",{code:"vault_capture_timeout"}):a;throw this.reportDirectFailure(l,"VAULT_LOAD_FAILED","vault_request","vault_capture","card"),l}finally{clearTimeout(s)}}async getUnifiedCheckoutSession(e,t){let n=await this.getCheckoutSession(e,t);return this.normalizeCheckoutSessionResponse(n)}async getUnifiedCheckoutSessionForRecovery(e,t,n){let s=await this.fetchCheckoutSession(e,t,!1,n);return this.normalizeCheckoutSessionResponse(s)}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,c.markSessionResponseReceived)(t)}}async processPayment(e,t,n){this.beginDirectTelemetryCheckout(t.sessionId);let s=t.paymentMethodCategory??"unknown";if(!t.nonce)throw this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"process_payment",paymentMethodCategory:s}),new c.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:s});let{nonce:o,paymentMethodCategory:a,...l}=t,u=ut(t.tokenizedData),d,p;try{d=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(t.sessionId)}/process`,{method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":o},body:JSON.stringify(l)}),p=d}catch(m){if(X(m))throw this.reportDirectFailure(m,"PAYMENT_PROCESSING_FAILED","processing","process_payment",s),m;d=await this.reconcileProcessPayment(t.sessionId,{...n,nonce:o,paymentMethodCategory:s,submittedIntentId:u})}if(!d.ok&&d.status!==202){let m=await ft(d);return m?this.directTelemetry?.terminal({outcome:m,stage:"processing",requestCategory:"process_payment",statusClass:"4xx",paymentMethodCategory:s}):this.directTelemetry?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",requestCategory:"process_payment",statusClass:(0,c.telemetryStatusClass)(d.status),failureCategory:d.status>=500?"server_error":void 0,paymentMethodCategory:s,...(0,c.readTelemetryHttpDiagnostics)(p)}),d}try{let m=await this.resolveProcessResponse(d,t.sessionId,{...n,nonce:o,paymentMethodCategory:s,submittedIntentId:u});return this.directTelemetry?.log({name:"payment.processing.completed",stage:"processing",requestCategory:"process_payment",statusClass:(0,c.telemetryStatusClass)(m.status),paymentMethodCategory:s}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-i),durationMode:"machine",requestCategory:"process_payment",statusClass:(0,c.telemetryStatusClass)(m.status),paymentMethodCategory:s}),m}catch(m){throw m instanceof c.FloPayError&&m.code==="checkout_processing_timeout"||this.reportDirectFailure(m,"PAYMENT_PROCESSING_FAILED","processing","process_payment",s),m}}async patchAccountSnapshot(e,t,n,s){this.beginDirectTelemetryCheckout(e);let i=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.state_transition",stage:"processing",requestCategory:"account_snapshot"});let o=s?.timeoutMs??mt,a=new AbortController,l=()=>a.abort();s?.signal&&(s.signal.aborted?a.abort():s.signal.addEventListener("abort",l,{once:!0}));let u=setTimeout(()=>a.abort(),o);try{let d;try{d=await z(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/account`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":t},body:JSON.stringify(n),signal:a.signal},H,p=>{this.telemetryHooks?.onRetry?.("account_snapshot",p),this.directTelemetry?.log({name:"operation.retry",stage:"processing",requestCategory:"account_snapshot",attempt:p})})}finally{clearTimeout(u),s?.signal?.removeEventListener("abort",l)}if(!d.ok)throw await A(d,"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(d){throw this.reportAccountSnapshotFailure(d,s?.telemetryMode??"blocking"),d}}async createSessionIntent(e,t,n,s){if(!t)throw new c.FloPayError("createSessionIntent requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let i=n,o=i.paymentMethodType,a=typeof o=="string"&&o.trim().toLowerCase()==="card",l=typeof o=="string"&&o.length>0&&!a&&(typeof i.paymentMethodId=="string"||i.paymentMethodId===null),u=i.provider==="stripe"&&(i.paymentMethodCategory==="wallet"||i.paymentMethodCategory==="apm")&&(i.intentKind==="payment"||i.intentKind==="setup"),d=i.provider==="paypal"&&i.paymentMethodCategory==="wallet"&&i.paymentMethodId===null&&(i.paymentMethodType==="paypal"&&i.intentKind==="payment"||i.paymentMethodType===c.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&(i.intentKind==="payment"||i.intentKind==="setup"));if(!l||!u&&!d)throw new c.FloPayError("Only wallet, APM, and PayPal session intents are supported.","validation_error",{code:"InvalidSessionIntentRequest"});let p=i.authorizationAttemptId;if(p!==void 0&&!(0,c.isUuidV4)(p))throw new c.FloPayError("authorizationAttemptId must be a v4 UUID identifying one buyer authorization attempt.","validation_error",{code:"InvalidAuthorizationAttemptId",param:"authorizationAttemptId"});let m=(0,c.isUuidV4)(p)?p:(0,c.randomUuidV4)();this.beginDirectTelemetryCheckout(e);let f=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.intent.started",stage:"processing",requestCategory:"intent_create"});let h={"Content-Type":"application/json","x-checkout-session-token":t,[c.IDEMPOTENCY_KEY_HEADER]:s?.idempotencyKey||m},g=!1;try{let C=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents`,{method:"POST",headers:h,body:JSON.stringify({...n,authorizationAttemptId:m}),signal:s?.signal});if(!C.ok){g=!0;let G=await A(C,"Failed to create checkout intent"),xe=(0,c.classifyTelemetryFailure)(G,"PAYMENT_PROCESSING_FAILED");throw be(G.statusCode)?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"intent_create",statusClass:"4xx"}):this.directTelemetry?.error({...xe,stage:"processing",requestCategory:"intent_create"}),G}let v=await C.json();if(C.status===202&&F(v)&&v.type==="checkout_processing")return g=!0,await this.settleProcessingSessionIntent(v,C,e,t,n);let _=v.data;if(!_||typeof _!="object")throw new c.FloPayError("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});let y=_,te=y.paymentMethodType,Ie=(y.paymentMethodCategory==="wallet"||y.paymentMethodCategory==="apm")&&typeof te=="string"&&te.trim().toLowerCase()!=="card"&&(typeof y.paymentMethodId=="string"||y.paymentMethodId===null)&&typeof y.providerObjectId=="string",De=y.provider==="stripe"&&(y.intentKind==="payment"||y.intentKind==="setup")&&typeof y.clientSecret=="string",Pe=y.provider==="paypal"&&y.paymentMethodCategory==="wallet"&&y.paymentMethodId===null&&(y.paymentMethodType==="paypal"&&y.intentKind==="payment"&&(y.providerObjectType==="order"||y.providerObjectType==="subscription")||y.paymentMethodType===c.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&y.intentKind==="payment"&&y.providerObjectType==="order"||y.paymentMethodType===c.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&y.intentKind==="setup"&&y.providerObjectType==="setup_token")&&y.clientSecret===null,Oe=y.provider===n.provider&&y.paymentMethodCategory===n.paymentMethodCategory&&y.paymentMethodType===n.paymentMethodType&&y.paymentMethodId===n.paymentMethodId&&y.intentKind===n.intentKind;if(!Ie||!De&&!Pe||!Oe)throw new c.FloPayError("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});return this.directTelemetry?.log({name:"payment.intent.completed",stage:"processing",requestCategory:"intent_create",statusClass:(0,c.telemetryStatusClass)(C.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-f),durationMode:"machine",requestCategory:"intent_create",statusClass:(0,c.telemetryStatusClass)(C.status)}),y}catch(C){throw g||this.reportDirectFailure(C,"PAYMENT_PROCESSING_FAILED","processing","intent_create"),C}}async settleProcessingSessionIntent(e,t,n,s,i){let o=this.toCheckoutProcessingPending(e,t,n);try{return{settled:!0,response:await this.resolveCheckoutProcessing(o,n,{nonce:s,paymentMethodCategory:i.provider==="paypal"?"paypal":i.paymentMethodCategory})}}catch(a){throw a instanceof c.FloPayError&&a.code==="checkout_processing_timeout"?new c.FloPayError(a.message,a.type,{code:a.code,statusCode:202,sessionId:o.sessionId,cause:a}):a}}async reportSessionIntentDecline(e,t,n,s){if(!t)throw new c.FloPayError("reportSessionIntentDecline requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let i=n,o=i.providerDeclineReason,a=i.paymentMethodType,l=i.providerIntentId,u=typeof o=="string"&&/^[a-z0-9][a-z0-9_.:-]{0,63}$/i.test(o)&&!/^(?:pm|pi|seti|tok|src|cus|sess|sk|pk)_/i.test(o),d=typeof a=="string"&&a.length>0&&a.trim().toLowerCase()!=="card"&&u,p=i.provider==="stripe"&&(i.paymentMethodCategory==="wallet"||i.paymentMethodCategory==="apm")&&(l===void 0||typeof l=="string"&&/^pi_[a-z0-9_]{1,252}$/i.test(l)),m=i.provider==="paypal"&&i.paymentMethodCategory==="wallet"&&i.paymentMethodType==="paypal"&&l===void 0;if(!d||!p&&!m)throw new c.FloPayError("Invalid non-card decline classification.","validation_error",{code:"InvalidSessionIntentDeclineRequest"});let f=m?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:o}:{provider:"stripe",paymentMethodCategory:i.paymentMethodCategory,paymentMethodType:i.paymentMethodType,providerDeclineReason:o,...typeof l=="string"?{providerIntentId:l}:{}},h=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:s?.signal});if(!h.ok)throw await A(h,"Failed to report checkout decline")}async resolvePaymentMethodLayout(e,t,n,s){if(!t)throw new c.FloPayError("resolvePaymentMethodLayout requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let i=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/payment-method-layout`,{method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":t,[c.FLO_SDK_VERSION_HEADER]:c.SDK_VERSION},body:JSON.stringify(n),signal:s?.signal});if(i.status===404||i.status===405)return null;if(!i.ok)throw await A(i,"Failed to resolve the payment method layout");let o=await i.json();return(0,c.normalizePaymentMethodLayout)(o?.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 s=t?.page??1,i=t?.limit??1,o=new URLSearchParams({email:e,page:String(s),limit:String(i),sortField:"createdAt",sortDirection:"DESC"});try{let a=await fetch(`${this.baseUrl}/v1/payments?${o.toString()}`,{method:"GET",signal:t?.signal,keepalive:!0});if(!a.ok)throw(0,c.withTelemetryHttpDiagnostics)(new c.FloPayError("Failed to fetch payments","api_error",{statusCode:a.status}),a);let l=await a.json();return this.directTelemetry?.log({name:"operation.recovery.completed",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),this.directTelemetry?.performance({stage:"recovery",durationMs:Math.max(0,this.telemetryTimestamp()-n),durationMode:"machine",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),l}catch(a){throw this.reportDirectFailure(a,"RECOVERY_FAILED","recovery","other","saved"),a}}async createAndFetchSession(e){if((0,c.isDetachedSessionEligible)(e)){let i=e.account.email?.trim();if(i&&!(0,c.isValidEmail)(i))throw new c.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=D(e.timeoutMs??12e3),s={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,s);return this.adoptDirectTelemetryCheckout(i.data.session?.id),this.directTelemetry?.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:s.statusClass}),this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:"session_create",statusClass:s.statusClass,attempt:s.attempt}),i}catch(i){throw this.reportSessionCreateFailure(i,t,s),i}finally{n.clear()}}async createAndFetchSessionRequest(e,t,n){let s=e.products??(0,c.foldIntoProducts)(e.items,e.subscriptions);(0,c.assertCaptureMethodEligible)({captureMethod:e.captureMethod,products:s});let i=(0,c.resolveSessionCurrency)(e.currency,e.items,e.subscriptions,s);if(!i)throw new c.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 o={clientId:e.clientId,checkoutVersion:c.SDK_VERSION,successUrl:e.successUrl,cancelUrl:e.cancelUrl,currency:i,checkoutMode:e.checkoutMode??"full",products:s.map(u=>(0,c.buildProductPayload)(u,i)),accountData:Se(e.account),couponCodes:e.couponCodes??[]};e.captureMethod==="manual"&&(o.captureMethod=e.captureMethod),e.tokenizedData&&(o.tokenizedData=e.tokenizedData),Re(o,e);let a=await this.postCheckoutSessionCreate(o,e,t,n),l=!1;try{let u=await a.json();if(u.data&&"gateways"in u.data){this.autoCacheDisplayData(u.data.uuid,e);let m=this.mergeCachedDisplayData(u.data),f=this.normalizeRawSession(m);return u.vault&&f.data.session&&(f.data.session.vault=this.toVaultBlock(u.vault)),{...f,autoProcessingError:u.autoProcessingError,autoProcessingAttempted:u.autoProcessingAttempted,autoProcessingPending:u.autoProcessingPending}}let d=u.data?.uuid;if(!d)throw new c.FloPayError("No session ID returned","api_error",{code:"InvalidCheckoutSessionResponse"});return this.autoCacheDisplayData(d,e),this.adoptDirectTelemetryCheckout(d),l=!0,{...await this.getUnifiedCheckoutSession(d),autoProcessingError:u.autoProcessingError,autoProcessingAttempted:u.autoProcessingAttempted,autoProcessingPending:u.autoProcessingPending}}catch(u){throw l?u:(0,c.markSessionResponseReceived)(u)}}async postCheckoutSessionCreate(e,t,n,s){let i={"Content-Type":"application/json",[c.FLO_SDK_VERSION_HEADER]:c.SDK_VERSION},o=(0,c.resolveIdempotencyKey)(t.idempotencyKey);o&&(i[c.IDEMPOTENCY_KEY_HEADER]=o),t.checkoutMode==="auto"&&(i[c.FLO_SDK_CAPABILITIES_HEADER]=c.ASYNC_AUTO_CHECKOUT_CAPABILITY);let a,l=!1,u=vt(t),d=(m,f,h)=>{l||(l=!0,this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:h,attempt:m}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:Math.max(0,this.telemetryTimestamp()-f),durationMode:"machine",requestCategory:"session_create",statusClass:h,attempt:m}))},p=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++){s.attempt=m;let f=this.telemetryTimestamp();try{u?.onAttempt?.(m)}catch{}try{a=await fetch(`${this.baseUrl}/v1/checkouts/sessions?expand=true`,{method:"POST",headers:i,body:JSON.stringify(e),signal:n})}catch(C){if(s.statusClass=n.aborted||C instanceof Error&&C.name==="AbortError"?"timeout":"network_error",n.aborted||C instanceof Error&&C.name==="AbortError"||m>=2)throw C;let v=m+1;p(v),await q(m,n);continue}let h=(0,c.telemetryStatusClass)(a.status);if(s.statusClass=h,a.status===204)throw d(m,f,h),new c.FloPayError("Session auto-completed \u2014 payment method already on file","api_error",{code:"session_auto_completed"});if(a.ok){d(m,f,h);break}let g=await A(a,"Failed to create checkout session");if(g.code===c.IDEMPOTENCY_IN_PROGRESS_CODE&&m<2){p(m+1),await q(m,n);continue}throw d(m,f,h),g}if(!a)throw new TypeError("Checkout-session creation exhausted its retry budget.");return a}async createDetachedSession(e){this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp(),n=D(e.timeoutMs??12e3),s={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let i=e.products??(0,c.foldIntoProducts)(e.items,e.subscriptions);try{(0,c.assertCaptureMethodEligible)({captureMethod:e.captureMethod,products:i})}catch(v){throw n.clear(),this.reportSessionCreateFailure(v,t,s),v}let o=(0,c.resolveSessionCurrency)(e.currency,e.items,e.subscriptions,i);if(!o)throw n.clear(),this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),new c.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{_e(e,o,i)}catch(v){throw n.clear(),this.reportSessionCreateFailure(v,t,s),v}let a,l,u=!1;try{let v=await this.postCheckoutSessionCreate(bt(e,o),e,n.signal,s);if(u=!0,l=await v.json(),!l.data||!("gateways"in l.data))throw new c.FloPayError("The billing API returned no session shell for a detached create. It must support `deferDataAttachment` (TeamFloPay/backend#1099).","api_error",{code:"InvalidCheckoutSessionResponse"});a=this.normalizeRawSession(this.mergeCachedDisplayData(l.data)),l.vault&&a.data.session&&(a.data.session.vault=this.toVaultBlock(l.vault))}catch(v){throw n.clear(),u&&(0,c.markSessionResponseReceived)(v),this.reportSessionCreateFailure(v,t,s),v}let d=a.data.session?.id??l.data.uuid??"",p=a.data.session?.clientSecret??l.data.nonce??"";if(!d||!p){n.clear();let v=new c.FloPayError("Checkout session shell was created without a session id or nonce.","api_error",{code:"InvalidCheckoutSessionResponse"});throw this.reportSessionCreateFailure(v,t,s),v}n.clear(),this.adoptDirectTelemetryCheckout(d),this.directTelemetry?.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",statusClass:s.statusClass,paymentMethodCategory:"card"}),this.directTelemetry?.performance({stage:"session_shell",durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:"session_create",statusClass:s.statusClass,attempt:s.attempt,paymentMethodCategory:"card"});let m=!e.account.email?.trim(),f=D(e.timeoutMs??12e3),h=this.claimCheckoutSession(d,p,m?_t(e,o,i):_e(e,o,i),{params:e,startedAt:t,deadline:f,createAttempt:s.attempt}),g=m?void 0:h,C=(v={})=>{if(g!==void 0)return g;let _={...e,account:{...e.account,...v,email:v.email?.trim()||e.account.email?.trim()}};return(0,c.isValidEmail)(_.account.email)?(g=h.then(()=>{let y=this.telemetryTimestamp();return this.claimCheckoutSession(d,p,St(_.account),{params:_,startedAt:y,deadline:D(e.timeoutMs??12e3),createAttempt:0})}),g.catch(()=>{}),g):Promise.reject(new c.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}))};return h.catch(()=>{}),{shell:a,sessionId:d,nonce:p,claimed:h,claim:C}}async claimCheckoutSession(e,t,n,s){let i=s?.startedAt??this.telemetryTimestamp(),o=this.telemetryTimestamp(),a=s?.deadline??D(12e3),l=JSON.stringify(n),u="unknown",d=0,p=!1;this.directTelemetry?.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"});try{let m;for(d=0;d<3;d++){try{m=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/claim`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":t,[c.FLO_SDK_VERSION_HEADER]:c.SDK_VERSION},body:l,signal:a.signal})}catch(g){let C=a.signal.aborted||g instanceof Error&&g.name==="AbortError";if(u=C?"timeout":"network_error",C||d>=2)throw g;try{this.telemetryHooks?.onRetry?.("session_claim",d+1),this.directTelemetry?.log({name:"operation.retry",stage:"session_claim",requestCategory:"session_claim",attempt:d+1})}catch{}await q(d,a.signal);continue}if(u=(0,c.telemetryStatusClass)(m.status),m.ok)break;throw await A(m,"Failed to attach checkout session data")}if(!m)throw new TypeError("Checkout-session claim exhausted its retry budget.");p=!0;let f=await m.json();if(!f.data?.gateways)throw new c.FloPayError("The billing API returned no checkout session with gateways after claiming it.","api_error",{code:"InvalidCheckoutSessionResponse"});s?.params&&this.autoCacheDisplayData(f.data.uuid??e,s.params);let h=this.normalizeRawSession(this.mergeCachedDisplayData(f.data));return f.vault&&h.data.session&&(h.data.session.vault=this.toVaultBlock(f.vault)),this.directTelemetry?.log({name:"session.claim.completed",stage:"session_claim",requestCategory:"session_claim",statusClass:u}),this.directTelemetry?.performance({stage:"session_claim",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"session_claim",statusClass:u,attempt:d}),this.directTelemetry?.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:u}),this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-i),durationMode:"machine",requestCategory:"session_create",statusClass:u,attempt:s?.createAttempt??d}),h}catch(m){throw p&&(0,c.markSessionResponseReceived)(m),this.reportSessionCreateFailure(m,o,{attempt:d,statusClass:u},"session_claim"),m}finally{a.clear()}}reportSessionCreateFailure(e,t,n,s="session_create"){if(!(e instanceof c.FloPayError&&e.code==="session_auto_completed"))try{this.telemetryHooks?.onSessionCreateFailure?.(e)}catch{}let i=(0,c.classifyTelemetryFailure)(e,"CHECKOUT_SESSION_CREATE_FAILED");if(this.directTelemetry?.performance({stage:s,durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:s==="session_claim"?"session_claim":"session_create",statusClass:i.statusClass,attempt:n.attempt}),e instanceof c.FloPayError&&e.type==="validation_error"||e instanceof c.FloPayError&&be(e.statusCode)){this.directTelemetry?.terminal({outcome:"validation_rejected",stage:s,requestCategory:s==="session_claim"?"session_claim":"session_create",...e.type==="validation_error"?{}:{statusClass:"4xx"}});return}e instanceof c.FloPayError&&e.code==="session_auto_completed"||this.directTelemetry?.error({...i,stage:s,requestCategory:s==="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(),s=t?.paymentMethodCategory??"saved";this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:s});let i=t?.timeoutMs??B,o=Date.now()+i,a=new AbortController,l=!1,u,d=setTimeout(()=>{u=setTimeout(()=>{l=!0,a.abort()},ve)},i),p=()=>a.abort(t?.signal?.reason);t?.signal?.aborted?p():t?.signal?.addEventListener("abort",p,{once:!0});let m=this.clampRetryAfterMs(t?.initialDelayMs??fe),f=0;try{if(t?.statusUrl){let h=await this.waitForCheckoutStatus(e,{initialDelayMs:m,timeoutMs:i,nonce:t.nonce,statusUrl:t.statusUrl,pollAfterAction:t.continueAfterActionRequired,signal:a.signal});if(h){let g=await this.resolveCheckoutSessionStatus(e,h,t.nonce,a.signal,()=>l);return this.reportRecoveryCompleted(n,s,t.challengeAttemptId),g}}for(;;){let h=o-Date.now();if(h<=0)throw S();if(m>0){try{f+=1,this.telemetryHooks?.onRetry?.("session_read",f),this.directTelemetry?.log({name:"operation.retry",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:s,attempt:f})}catch{}if(await Z(Math.min(m,h),a.signal),Date.now()>=o)throw S()}let g=await this.getUnifiedCheckoutSessionForRecovery(e,t?.nonce,a.signal),C=g.data.session?.status;if(C==="authorized"||C==="complete"||C==="expired")return this.reportRecoveryCompleted(n,s,t?.challengeAttemptId),g;if(Date.now()>=o)throw S();m=this.clampRetryAfterMs(Math.max(m*2,Ce))}}catch(h){let g=l&&X(h)?S():h;throw this.reportDirectFailure(g,"RECOVERY_FAILED","recovery","session_read",s),g}finally{clearTimeout(d),clearTimeout(u),t?.signal?.removeEventListener("abort",p)}}reportRecoveryCompleted(e,t,n){let s={stage:"recovery",requestCategory:"session_read",paymentMethodCategory:t};if(this.directTelemetry?.log({name:"operation.recovery.completed",...s}),n)try{this.directTelemetry?.beginThreeDsChallenge({attemptId:n}).record("recovery_read_completed",{evidenceBasis:"server_status"})}catch{}this.directTelemetry?.performance({...s,durationMs:Math.max(0,this.telemetryTimestamp()-e),durationMode:"machine"})}async resolveCheckoutSessionStatus(e,t,n,s,i){let o=t.latestTransactionAttempt;if(this.rememberReportedFailure(e,t),o?.result==="DECLINE"){let u=o.code===c.STORED_PAYMENT_METHOD_UNSUPPORTED_CODE;throw new c.FloPayError(u?c.STORED_PAYMENT_METHOD_UNSUPPORTED_MESSAGE:"Payment was declined. Please choose another payment method.","api_error",{code:o.code??o.declineReason??"authorization_declined",statusCode:400})}if(o?.result==="ERROR"||t.status==="voided")throw new c.FloPayError("Payment could not be completed. Please try again.","api_error",{code:o?.code??"payment_processing_error",statusCode:500});let a;try{a=await this.getUnifiedCheckoutSessionForRecovery(e,n,s)}catch(u){if(!i?.()||!X(u))throw u;a={providers:[],mode:"tokenize",data:{},raw:t}}let l=a.data.session;return l&&o?.result==="SUCCESS"?{...a,data:{...a.data,session:{...l,status:"complete"}}}:l&&o?.result==="AUTHORIZED"?{...a,data:{...a.data,session:{...l,status:"authorized",paymentId:t.paymentId??void 0,authorizationExpiresAt:t.authorizationExpiresAt??void 0}}}:l&&t.status==="completed"?{...a,data:{...a.data,session:{...l,status:"complete"}}}:l&&t.status==="authorized"?{...a,data:{...a.data,session:{...l,status:"authorized",paymentId:t.paymentId??void 0,authorizationExpiresAt:t.authorizationExpiresAt??void 0}}}:l&&t.status==="expired"?{...a,data:{...a.data,session:{...l,status:"expired"}}}:o?.result!=="ACTION_REQUIRED"?a:o.gateway==="paypal"&&o.providerIntentId?{...a,autoProcessingError:{type:"paypal_direct_required",message:"PayPal authorization required",orderId:o.providerIntentId,checkoutMethod:"paypal"}}:o.nextActionRedirectUrl?{...a,autoProcessingError:{type:"3ds_required",message:"Additional authentication is required.",nextActionRedirectUrl:o.nextActionRedirectUrl}}:a}async waitForCheckoutStatus(e,t){let n=t.timeoutMs??B,s=Date.now()+n,i=this.clampRetryAfterMs(t.initialDelayMs);for(;;){let o=s-Date.now();if(o<=0||i>0&&(await Z(Math.min(i,o),t.signal),Date.now()>=s))throw S();let a=s-Date.now();if(a<=0)throw S();let l=new AbortController,u,d=t.signal?new Promise((_,y)=>{u=y}):null,p=()=>{l.abort(t.signal?.reason),u?.(t.signal?.reason??Object.assign(new Error("The operation was aborted."),{name:"AbortError"}))};t.signal?.aborted?p():t.signal?.addEventListener("abort",p,{once:!0});let m,f=t.signal?null:new Promise((_,y)=>{m=setTimeout(()=>{y(S()),l.abort()},a+ve)}),h;try{let _=this.fetchCheckoutStatus(e,t.nonce,t.statusUrl,l.signal);h=await Promise.race([_,f,d].filter(y=>y!==null))}finally{m!==void 0&&clearTimeout(m),t.signal?.removeEventListener("abort",p)}if(!h)return null;let g=ge(h.latestTransactionAttempt)&&!this.isOwnFailedAttempt(e,h,t.submittedIntentId);if(h.status==="completed"||h.status==="authorized"||h.status==="expired"||h.status==="voided")return g?{...h,latestTransactionAttempt:null}:h;let C=h.latestTransactionAttempt?.result,v=t.pollAfterAction===!0&&C==="ACTION_REQUIRED";if(!g&&C!==void 0&&C!=="PENDING"&&!v)return h;i=this.clampRetryAfterMs(Math.max(i*2,Ce))}}isOwnFailedAttempt(e,t,n){let s=t.latestTransactionAttempt?.providerIntentId??null;return n!==void 0?s===n:s===null?!0:!ct(t.uuid||e,s)}rememberReportedFailure(e,t){let n=t.latestTransactionAttempt;!ge(n)||!n.providerIntentId||lt(t.uuid||e,n.providerIntentId)}async fetchCheckoutStatus(e,t,n,s){let i=`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/status`,o=i;if(n)try{let d=new URL(n,`${this.baseUrl}/`),p=new URL(i);d.origin===p.origin&&(o=d.toString())}catch{}let a={[c.FLO_SDK_VERSION_HEADER]:c.SDK_VERSION};t&&(a["x-checkout-session-token"]=t);let l=await z(o,{headers:a,signal:s});if(l.status===404||l.status===405)return null;if(!l.ok)throw await A(l,"Failed to get checkout session status");let u=await l.json();return F(u.data)&&"latestTransactionAttempt"in u.data?u.data:null}normalizeRawSession(e){let t=e.gateways??{},n=[],s={session:this.toCheckoutSession(e)},i=t.stripe;if(i?.publishableKey){n.push("stripe");let l=[e.stripeClientSecret,i.stripeClientSecret].find(u=>typeof u=="string"&&u.length>0);s.stripe={clientSecret:l??"",publishableKey:i.publishableKey??void 0,paypalPublishableKey:i.paypalPublishableKey??void 0,environment:i.environment,enabledPaymentMethods:Array.isArray(i.enabledPaymentMethods)?i.enabledPaymentMethods.filter(u=>typeof u=="string"):void 0}}let o=t.paypal;return o?.publishableKey&&(n.push("paypal"),s.paypal={publishableKey:o.publishableKey,environment:o.environment,providerObjectType:o.providerObjectType,approvalPresentation:o.approvalPresentation}),{providers:n,mode:"tokenize",...e.checkoutMetadata===void 0?{}:{checkoutMetadata:e.checkoutMetadata},data:s,raw:{data:e}}}toCheckoutSession(e){let t=e.products??[],n=typeof e.totalAmount=="number"&&Number.isFinite(e.totalAmount),s=t.reduce((u,d)=>u+(d.overrideAmount??d.totalAmount??0),0),i=n?e.totalAmount:s,o=Math.round(i*100),a=e.currency??t[0]?.currency??"USD",l="payment";return e.checkoutMode==="setup"?l="setup":t.some(u=>u.type==="subscription")&&(l="subscription"),{id:e.uuid,clientSecret:e.nonce,mode:l,status:this.toCheckoutSessionStatus(e.status),amount:o,currency:a,captureMethod:e.captureMethod,paymentId:e.paymentId,authorizationExpiresAt:e.authorizationExpiresAt,failureOutcome:(0,c.normalizeCheckoutFailureOutcome)(e.outcome)??(0,c.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}:{},...rt(e.futureUse)?{futureUse:e.futureUse}:{},...Array.isArray(e.futureUseUnsupported)?{futureUseUnsupported:e.futureUseUnsupported.filter(nt)}:{},buyerIdentified:e.buyerIdentified,providerPaymentMethodId:typeof e.providerPaymentMethodId=="string"?e.providerPaymentMethodId:null,products:t.map(u=>({...u,totalAmount:typeof u.totalAmount=="number"?u.totalAmount:void 0,overrideAmount:typeof u.overrideAmount=="number"?u.overrideAmount:null,currency:typeof u.currency=="string"?u.currency:void 0,metadata:u.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=gt(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 s=await e.json().catch(()=>null),i=this.toCheckoutProcessingPending(s,e,t);return this.resolveCheckoutProcessing(i,t,n)}async resolveCheckoutProcessing(e,t,n){let s=n?.pollTimeoutMs??B,i=Date.now()+s;if(e.statusUrl){let a=await this.waitForCheckoutStatus(e.sessionId,{initialDelayMs:e.retryAfterMs,timeoutMs:s,nonce:n?.nonce,statusUrl:e.statusUrl,submittedIntentId:n?.submittedIntentId});if(a)return this.toProcessResponseFromStatus(a,t,n?.nonce)}let o=await this.waitForCheckoutSessionCompletion(e.sessionId,{initialDelayMs:e.retryAfterMs,timeoutMs:i-Date.now(),nonce:n?.nonce,paymentMethodCategory:n?.paymentMethodCategory});return this.toProcessResponseFromSession(o,t)}async toProcessResponseFromStatus(e,t,n){let s=e.latestTransactionAttempt?.result,i={[it]:ot},o={"Content-Type":"application/json",...i};if(e.status==="completed"||s==="SUCCESS")return new Response(null,{status:204,statusText:"No Content",headers:i});if(e.status==="authorized"||s==="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:o});if(e.status==="expired"){let a=await this.resolveCheckoutSessionStatus(t,e,n);return this.toProcessResponseFromSession(a,t)}if(this.rememberReportedFailure(t,e),s==="DECLINE"){let a=e.latestTransactionAttempt,l=a?.code===c.STORED_PAYMENT_METHOD_UNSUPPORTED_CODE,u=a?.declineReason??void 0;return new Response(JSON.stringify({type:u??"authorization_declined",message:l?c.STORED_PAYMENT_METHOD_UNSUPPORTED_MESSAGE:"Payment was declined. Please choose another payment method.",code:a?.code??u??"authorization_declined",...u?{declineCode:u}:{}}),{status:400,headers:o})}if(s==="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:o});if(s==="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:o});if(s==="ERROR"||e.status==="voided")return new Response(JSON.stringify({type:"unknown",code:e.latestTransactionAttempt?.code??"payment_processing_error",message:st(e)??"Payment could not be completed. Please try again."}),{status:500,headers:o});throw S()}async reconcileProcessPayment(e,t){let n=t?.pollTimeoutMs??B,s=Date.now()+n,i=null;try{i=await this.waitForCheckoutStatus(e,{initialDelayMs:0,timeoutMs:n,nonce:t?.nonce,submittedIntentId:t?.submittedIntentId})}catch(l){if(this.reportDirectFailure(l,"RECOVERY_FAILED","recovery","session_read",t?.paymentMethodCategory??"saved"),l instanceof c.FloPayError&&l.code==="checkout_processing_timeout")throw l}if(i)return this.toProcessResponseFromStatus(i,e,t?.nonce);let o=s-Date.now();if(o<=0)throw S();let a=await this.waitForCheckoutSessionCompletion(e,{initialDelayMs:0,timeoutMs:o,nonce:t?.nonce,paymentMethodCategory:t?.paymentMethodCategory});return this.toProcessResponseFromSession(a,e)}toProcessResponseFromSession(e,t){if(e.data.session?.status==="complete")return new Response(null,{status:204,statusText:"No Content"});if(e.data.session?.status==="authorized"){let n=e.data.session;return new Response(JSON.stringify({status:"authorized",paymentId:n.paymentId,sessionId:n.id||t,authorizationExpiresAt:n.authorizationExpiresAt}),{status:200,headers:{"Content-Type":"application/json"}})}if(e.data.session?.status==="expired"){let n=e.data.session.failureOutcome==="authorization_expired"||e.data.session.captureMethod==="manual";throw new c.FloPayError(n?"Authorization has expired.":"Checkout session has expired.","api_error",{code:n?"authorization_expired":"checkout_session_expired"})}throw S()}toCheckoutProcessingPending(e,t,n){let s=t.headers.get("Retry-After"),i=s===null||s.trim()===""?void 0:Number(s),o=i!==void 0&&Number.isFinite(i)?i*1e3:void 0;return{type:"checkout_processing",sessionId:k(e,"sessionId")??n,retryAfterMs:this.clampRetryAfterMs(pt(e,"retryAfterMs")??o??fe),statusUrl:k(e,"statusUrl"),sessionUrl:k(e,"sessionUrl")}}clampRetryAfterMs(e){return Math.max(0,Math.min(e,dt))}autoCacheDisplayData(e,t){if(!e)return;let n=t.products??(0,c.foldIntoProducts)(t.items,t.subscriptions);if(n.length===0&&!t.currency)return;let s=t.products!==void 0,i=(0,c.resolveSessionCurrency)(t.currency,s?void 0:t.items,s?void 0:t.subscriptions,n);W(e,{currency:i??void 0,products:n.map(o=>({code:o.code??o.providerItemId??o.providerPlanId,type:o.type,name:o.name??o.itemName??o.providerItemName??o.subscriptionName??o.providerPlanName??null,totalAmount:o.totalAmount,overrideAmount:o.overrideAmount,currency:o.currency??i??void 0}))})}mergeCachedDisplayData(e){let t=se(e.uuid),n=new Map,s=o=>o?`code:${o}`:void 0;for(let o of t?.products??[]){let a=s(o.code);a&&n.set(a,o)}let i=(e.products??[]).map(o=>{let a=s(o.code),l=a?n.get(a):void 0;return{...o,name:o.name??l?.name??null,totalAmount:o.totalAmount??l?.totalAmount,overrideAmount:o.overrideAmount??l?.overrideAmount,currency:o.currency??l?.currency}});return{...e,currency:e.currency??t?.currency,products:i}}};I.activeVaultCaptureRequests=new Map;var j=I;var T=require("@flopay/shared");var Rt=4,ee="flopay-vault",At=3e4,wt=T.THREE_DS_CHALLENGE_WINDOW_MS+At,Et="Card authentication timed out.",Ae={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 kt(r){return r.class==="lifecycle"?r.name:r.class==="technical_error"?r.code:r.class==="expected_outcome"?r.outcome:"sdk.performance"}function P(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:kt(r),data:e})}catch{}}function U(r,e){return(0,T.buildTelemetryLogEvent)({eventId:"11111111-1111-4111-8111-111111111111",name:r,stage:e,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}var Mt=new Set(["authorization_declined","authentication_required","authorization_expired","capture_failed"]);function It(r){return typeof r=="string"&&Mt.has(r)?r:"unknown"}var Dt=new Set(["verification_failed","verification_expired"]);function Pt(r){return r==null?!0:typeof r=="string"&&Dt.has(r)}var Ot="vault_mount";function xt(r){return r.failureStage===Ot}function we(r,e){return r&&!xt(e)?{errorCode:"VAULT_SUBMIT_FAILED",stage:"vault_submit",failureCategory:"provider_runtime",reason:It(e.failureOutcome)}:{errorCode:"VAULT_LOAD_FAILED",stage:"vault_mount",failureCategory:"provider_runtime"}}function Ee(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 Ft(r,e,t,n="checkout"){let{type:s}=r;if(s==="complete"||s==="decline")return(0,T.buildTelemetryTerminalEvent)({eventId:"22222222-2222-4222-8222-222222222222",outcome:Ee(r,t,n),sequence:0,provider:"pcivault",paymentMethodCategory:"card"});if(s==="error"){let a=we(e,r);return(0,T.buildTelemetryErrorEvent)({eventId:"33333333-3333-4333-8333-333333333333",...a,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}let[i,o]=Ae[s];return U(i,o)}function Ut(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===ee&&(e.type==="ready"||e.type==="submitting"||e.type==="blocked"||e.type==="complete"||e.type==="decline"||e.type==="error"||e.type==="action_required")}function qt(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 Lt(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 Nt(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===ee&&e.type==="validation"&&Array.isArray(e.messages)}function Vt(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===ee&&e.type==="resize"&&typeof e.height=="number"&&Number.isFinite(e.height)}var K=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 E({billingApiUrl:(0,T.resolveBillingApiUrl)(e.billingApiUrl),sdkVersion:T.SDK_VERSION}):void 0)}async mount(e,t){this.ownsTelemetryReporter&&!this.telemetryReporter&&(this.telemetryReporter=new E({billingApiUrl:(0,T.resolveBillingApiUrl)(this.config.billingApiUrl),sdkVersion:T.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?.()??R(),this.vaultReadyReported=!1,this.submissionStarted=!1,this.submissionStartedAt=null,typeof window>"u"||typeof document>"u")throw this.reportVaultLoadFailure(),new T.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 T.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(s){throw this.reportVaultLoadFailure(),s}this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),this.postSubmitLabel(),P(U("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?.()??R())-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 s of n){let i=document.createElement("script");for(let o of Array.from(s.attributes))i.setAttribute(o.name,o.value);i.text=s.text,s.replaceWith(i)}}attachMessageListener(){if(this.messageHandler)return;let e=t=>{if(this.expectedOrigin&&t.origin!==this.expectedOrigin)return;let n=t.data;if(Vt(n)){if(this.messageToken&&n.messageToken!==this.messageToken)return;this.applyHeight(n.height);return}if(Nt(n)){if(this.messageToken&&n.messageToken!==this.messageToken)return;let u=n.messages.filter(d=>typeof d=="string"&&d.trim()).join(" ");this.emit("validation",{sessionId:this.config.sessionId,message:u||void 0});return}if(!Ut(n)||this.messageToken&&n.messageToken!==this.messageToken)return;let s=this.config.sessionId,i=typeof n.sessionId=="string"?n.sessionId:void 0;if(s&&i&&i!==s||(n.type==="complete"||n.type==="decline")&&s&&i!==s)return;let o=Lt(n.paymentMethod),a=qt(n.vaultOutcome),l={...n.sessionId??this.config.sessionId?{sessionId:n.sessionId??this.config.sessionId}:{},...n.outcome?{outcome:n.outcome}:{},...n.paymentId?{paymentId:n.paymentId}:{},...n.authorizationExpiresAt?{authorizationExpiresAt:n.authorizationExpiresAt}:{},...n.failureOutcome?{failureOutcome:n.failureOutcome}:{},...n.intentId?{intentId:n.intentId}:{},...n.declineReason?{declineReason:n.declineReason}:{},...n.message?{message:n.message}:{},...a?{vaultOutcome:a}:{},...o?{paymentMethod:o}:{}};n.type==="submitting"&&(this.submissionStarted=!0,this.submissionStartedAt=this.telemetryReporter?.now?.()??R()),this.isVerificationStateError(n)?(P(U("operation.state_transition","vault_mount")),this.telemetryReporter?.log({name:"operation.state_transition",stage:"vault_mount",provider:"pcivault",paymentMethodCategory:"card"})):(P(Ft(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,l)};this.messageHandler=e,window.addEventListener("message",e)}isVerificationStateError(e){return e.type==="error"&&this.verificationRequired&&!this.submissionStarted&&Pt(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:Ee(e,this.config.captureMethod,this.config.operation),provider:"pcivault",paymentMethodCategory:"card"});return}if(n==="error"){let o=we(this.submissionStarted,e);t.log({name:"vault.terminal",stage:o.stage,provider:"pcivault",paymentMethodCategory:"card"}),t.error({...o,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 o=this.submissionStartedAt;this.submissionStartedAt=null,o!==null&&t.performance({stage:"three_ds_handoff",durationMs:Math.max(0,t.now()-o),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:"action_required",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"});return}let[s,i]=Ae[n];t.log({name:s,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:s}=this;e===void 0||!t||!n||!s||this.postToHostedWindow({source:"flopay-vault-host",type:"submitLabel",sessionId:t,messageToken:n,label:e},s)}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 h=this.actionOverlay.querySelector("iframe");h instanceof HTMLIFrameElement&&h.src!==e&&(h.src=e),this.armActionRequiredTimeout();return}this.actionOverlayPreviousFocus=document.activeElement instanceof HTMLElement?document.activeElement:null;let t=ce(this.beginActionChallengeAttempt()),n=de(e),s=!1,i=h=>{if(s)return;let g=ue(h,n);g&&(s=!0,t.record("policy_violation",{reason:g,evidenceBasis:"parent_csp_event"}))},o=()=>{t.record("pagehide_observed",{evidenceBasis:"page_lifecycle_event"})},a={telemetry:t,loaded:!1,detach:()=>{document.removeEventListener("securitypolicyviolation",i),window.removeEventListener("pagehide",o)}};this.actionChallenge=a,this.lastChallengeTelemetry=t,t.record("handoff_planned"),Q(e)==="invalid"&&t.record("action_invalid",{reason:"invalid_url"}),document.addEventListener("securitypolicyviolation",i),window.addEventListener("pagehide",o);let l=document.createElement("div");l.setAttribute("data-flopay-action-required","1"),l.setAttribute("role","dialog"),l.setAttribute("aria-modal","true"),l.setAttribute("aria-label","Card authentication"),l.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let u=document.createElement("iframe");u.setAttribute("title","Card authentication"),u.setAttribute("allow","payment"),u.tabIndex=0,u.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(";"),u.addEventListener("load",()=>{a.loaded||(a.loaded=!0,t.record("iframe_load",{evidenceBasis:"iframe_load_event"}))}),u.src=e,l.appendChild(u);let d=document.createElement("button");d.type="button",d.setAttribute("aria-label","Close card authentication"),d.textContent="\xD7",d.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(";"),d.addEventListener("click",()=>this.abandonActionRequiredOverlay()),l.appendChild(d),l.addEventListener("click",h=>{h.target===l&&this.abandonActionRequiredOverlay()});let p=0,m=h=>{let g=h.data,C=!!g&&typeof g=="object"&&g.source==="flopay-vault-3ds-return";if(h.source!==u.contentWindow){C&&p<Rt&&(p+=1,t.record("return_rejected",{reason:"untrusted_source",evidenceBasis:"message_origin_check"}));return}C&&(t.record("trusted_return",{evidenceBasis:"message_origin_check"}),t.terminal("trusted_return",{evidenceBasis:"message_origin_check"}),P(U("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(l)}catch(h){throw t.record("render_failed"),this.hideActionRequiredOverlay(),this.actionOverlayPreviousFocus=null,h}t.record("container_attached"),t.record("navigation_assigned");let f=le(l);f&&t.record("container_visibility",{reason:f,evidenceBasis:"parent_computed_style"}),this.actionOverlay=l,u.focus(),this.armActionRequiredTimeout(),P(U("vault.three_ds.handoff","three_ds_handoff"))}armActionRequiredTimeout(){this.actionOverlayTimer&&clearTimeout(this.actionOverlayTimer),this.actionOverlayTimer=setTimeout(()=>{this.actionOverlayTimer=null,this.actionOverlay&&this.timeOutActionRequiredOverlay()},wt)}reportChallengeAbandoned(){P((0,T.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:Et})}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`}};var Bt=["setup_intent","setup_intent_client_secret","redirect_status"];function ke(){if(typeof window>"u")return null;let r=new URLSearchParams(window.location.search);return!r.has("setup_intent")||!r.has("redirect_status")?null:{failed:r.get("redirect_status")==="failed"}}function Me(){if(typeof window>"u")return;let r=new URL(window.location.href),e=!1;for(let t of Bt)r.searchParams.has(t)&&(r.searchParams.delete(t),e=!0);e&&window.history.replaceState(window.history.state,"",r.toString())}0&&(module.exports={PaymentAPI,PciVaultCardCapture,clearSetupRedirectParams,readSetupRedirectReturn});
@@ -1 +1 @@
1
- import{q as a,s as n}from"./chunk-2ZB6JO3E.mjs";var i=["setup_intent","setup_intent_client_secret","redirect_status"];function o(){if(typeof window>"u")return null;let e=new URLSearchParams(window.location.search);return!e.has("setup_intent")||!e.has("redirect_status")?null:{failed:e.get("redirect_status")==="failed"}}function u(){if(typeof window>"u")return;let e=new URL(window.location.href),t=!1;for(let r of i)e.searchParams.has(r)&&(e.searchParams.delete(r),t=!0);t&&window.history.replaceState(window.history.state,"",e.toString())}export{a as PaymentAPI,n as PciVaultCardCapture,u as clearSetupRedirectParams,o as readSetupRedirectReturn};
1
+ import{q as a,s as n}from"./chunk-QFFZVSUD.mjs";var i=["setup_intent","setup_intent_client_secret","redirect_status"];function o(){if(typeof window>"u")return null;let e=new URLSearchParams(window.location.search);return!e.has("setup_intent")||!e.has("redirect_status")?null:{failed:e.get("redirect_status")==="failed"}}function u(){if(typeof window>"u")return;let e=new URL(window.location.href),t=!1;for(let r of i)e.searchParams.has(r)&&(e.searchParams.delete(r),t=!0);t&&window.history.replaceState(window.history.state,"",e.toString())}export{a as PaymentAPI,n as PciVaultCardCapture,u as clearSetupRedirectParams,o as readSetupRedirectReturn};