@flopay/js 1.11.0 → 1.11.2

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.
@@ -457,6 +457,15 @@ declare class PaymentAPI {
457
457
  private reportRecoveryCompleted;
458
458
  private resolveCheckoutSessionStatus;
459
459
  private waitForCheckoutStatus;
460
+ /**
461
+ * Whether a failed status attempt answers this caller. A caller that names its submitted
462
+ * provider intent only accepts a failure for exactly that intent: another intent, or none, is
463
+ * unmatched. A caller that cannot name one accepts any failure the SDK has not already
464
+ * reported on the session, through this client or any other on the page (TeamFloPay/sdk#439).
465
+ */
466
+ private isOwnFailedAttempt;
467
+ /** Record a failed status attempt the SDK is about to report to its caller. */
468
+ private rememberReportedFailure;
460
469
  private fetchCheckoutStatus;
461
470
  /** Normalize a raw session into a provider-agnostic shape. */
462
471
  private normalizeRawSession;
@@ -457,6 +457,15 @@ declare class PaymentAPI {
457
457
  private reportRecoveryCompleted;
458
458
  private resolveCheckoutSessionStatus;
459
459
  private waitForCheckoutStatus;
460
+ /**
461
+ * Whether a failed status attempt answers this caller. A caller that names its submitted
462
+ * provider intent only accepts a failure for exactly that intent: another intent, or none, is
463
+ * unmatched. A caller that cannot name one accepts any failure the SDK has not already
464
+ * reported on the session, through this client or any other on the page (TeamFloPay/sdk#439).
465
+ */
466
+ private isOwnFailedAttempt;
467
+ /** Record a failed status attempt the SDK is about to report to its caller. */
468
+ private rememberReportedFailure;
460
469
  private fetchCheckoutStatus;
461
470
  /** Normalize a raw session into a provider-agnostic shape. */
462
471
  private normalizeRawSession;
@@ -1 +1 @@
1
- "use strict";var j=Object.defineProperty;var _e=Object.getOwnPropertyDescriptor;var Se=Object.getOwnPropertyNames;var Ae=Object.prototype.hasOwnProperty;var ke=(n,e)=>{for(var t in e)j(n,t,{get:e[t],enumerable:!0})},Re=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Se(e))!Ae.call(n,s)&&s!==t&&j(n,s,{get:()=>e[s],enumerable:!(r=_e(e,s))||r.enumerable});return n};var Me=n=>Re(j({},"__esModule",{value:!0}),n);var ut={};ke(ut,{PaymentAPI:()=>V,PciVaultCardCapture:()=>H});module.exports=Me(ut);var a=require("@flopay/shared");function X(n){return typeof n=="string"&&n.trim()?n:void 0}function Z(n){if(typeof n=="string")return n.trim()?n:void 0;if(Array.isArray(n))return n.filter(t=>typeof t=="string"&&t.trim().length>0).join("; ")||void 0}function E(n=12e3){let e=Number.isFinite(n)&&n>=0?n:12e3,t=new AbortController,r=setTimeout(()=>t.abort(),e);return{signal:t.signal,clear:()=>clearTimeout(r)}}function Ee(){return Object.assign(new Error("The operation was aborted."),{name:"AbortError"})}function x(n,e){let t=150*2**n,r=Math.round(t*(.75+Math.random()*.5));return new Promise((s,o)=>{let i,u=()=>e.removeEventListener("abort",c),c=()=>{i!==void 0&&clearTimeout(i),u(),o(Ee())};if(e.aborted){c();return}i=setTimeout(()=>{u(),s()},r),e.addEventListener("abort",c,{once:!0})})}var we="flopay_session_display:";var F=new Map;function U(n){return`${we}${n}`}function K(){if(typeof window>"u")return null;try{return window.sessionStorage}catch{return null}}function G(n,e,t){if(!n)return;let r=t?.ttlMs??36e5,s={data:e,expiresAt:Date.now()+r},o=K();if(o)try{o.setItem(U(n),JSON.stringify(s));return}catch{}F.set(n,s)}function ee(n){if(!n)return null;let e=K();if(e)try{let r=e.getItem(U(n));if(r){let s=JSON.parse(r);if(s&&typeof s.expiresAt=="number"&&s.expiresAt>Date.now())return s.data;e.removeItem(U(n))}}catch{}let t=F.get(n);if(t){if(t.expiresAt>Date.now())return t.data;F.delete(n)}return null}function te(n){if(!n)return;F.delete(n);let e=K();if(e)try{e.removeItem(U(n))}catch{}}var T=require("@flopay/shared"),Ie="/v1/sdk-telemetry/events",$=16,Pe=64,De=1500,re=1e3,Oe=64,xe="00000000-0000-4000-8000-000000000000",Fe={technical_error:8,lifecycle:32,expected_outcome:32,performance:24};function w(){try{return globalThis.crypto.randomUUID()}catch{let n=new Uint8Array(16);try{globalThis.crypto.getRandomValues(n)}catch{for(let t=0;t<n.length;t+=1)n[t]=Math.floor(Math.random()*256)}n[6]=(n[6]??0)&15|64,n[8]=(n[8]??0)&63|128;let e=[...n].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 Ue(n){try{return new TextEncoder().encode(n).byteLength}catch{return n.length}}function qe(n){return JSON.stringify([n.code,n.failureCategory,n.reason,n.stage,n.provider,n.attempt,n.statusClass,n.requestCategory,n.paymentMethodCategory,n.walletType,n.operationOutcome,n.checkoutMode,n.layout,n.inAppBrowser,n.appFamily,n.popupCapability,n.presentationMode,n.terminalReason])}function A(){return globalThis.performance?.now()??0}var k=class{constructor(e){this.ingestionDisabled=!1;this.queue=[];this.sequence=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(/\/+$/,"")}${Ie}`,this.sdkPackage=e.sdkPackage??"@flopay/js",this.sdkVersion=e.sdkVersion,this.correlationId=w(),this.merchantEnabled=e.enabled!==!1,this.clock=e.clock??A,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,T.buildTelemetryLogEvent)({...this.checkoutContext,...e,eventId:w(),sequence:this.sequence++}))}error(e){if(this.notify({...e,class:"technical_error"}),!this.canCollect())return;let t=(0,T.buildTelemetryErrorEvent)({...this.checkoutContext,...e,eventId:xe,sequence:0}),r=qe(t),s=this.now();this.pruneReportedFailures(s);let o=this.reportedFailures.get(r);if(o!==void 0&&s>=o&&s-o<re){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(r,s),this.enqueue((0,T.buildTelemetryErrorEvent)({...this.checkoutContext,...e,eventId:w(),sequence:this.sequence++}))}performance(e){this.canCollect()&&this.enqueue((0,T.buildTelemetryPerformanceEvent)({...this.checkoutContext,...e,eventId:w(),sequence:this.sequence++}))}terminal(e){if(this.canCollect()&&(this.enqueue((0,T.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"})}}now(){try{return this.clock()}catch{return A()}}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,r]of this.reportedFailures)(e<r||e-r>=re)&&this.reportedFailures.delete(t)}rememberReportedFailure(e,t){for(;this.reportedFailures.size>=Oe;){let r=this.reportedFailures.keys().next();if(r.done)break;this.reportedFailures.delete(r.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.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>=Pe||this.eventCounts[e.class]>=Fe[e.class])){if(this.eventCounts[e.class]+=1,this.queue.push(e),this.queue.length>=$){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,$);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,$);this.sendBatch(e)}}async sendBatch(e){if(!this.browserTransportAvailable||this.ingestionDisabled)return;let t=(0,T.serializeTelemetryBatch)(e,{correlationId:this.correlationId,sdkPackage:this.sdkPackage,sdkVersion:this.sdkVersion,batchId:w()});if(Ue(t)>T.TELEMETRY_MAX_BATCH_BYTES)return;let r=typeof AbortController>"u"?null:new AbortController,s=null;try{let o=fetch(this.endpoint,{method:"POST",headers:{"content-type":"text/plain;charset=UTF-8"},body:t,credentials:"omit",keepalive:!0,referrerPolicy:"no-referrer",signal:r?.signal}).then(async c=>{if(c.status!==202)return null;let l=null;try{l=await c.json()}catch{}return l?.status==="disabled"?"disabled":null}).catch(()=>null),i=new Promise(c=>{s=setTimeout(()=>{r?.abort(),c(null)},De)});await Promise.race([o,i])==="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)}},ne=Symbol.for("@flopay/js.telemetry.reporter-factory.v1"),se=globalThis;se[ne]===void 0&&Object.defineProperty(se,ne,{configurable:!0,enumerable:!1,writable:!1,value:n=>new k(n)});function Le(n){return n==="on_session"||n==="off_session"}function Ne(n){if(!n||typeof n!="object")return!1;let e=n;return typeof e.paymentMethodType=="string"&&typeof e.reason=="string"}var oe=0,ie=500,q=15e3,ae=15e3,Ve=3e3,ze=1e4,He=1e4;function de(n){return typeof n=="object"&&n!==null}function I(n,e){return X(n?.[e])}function ue(n,e){return Z(n?.[e])}function Be(n,e){let t=n?.[e];return typeof t=="number"&&Number.isFinite(t)?t:void 0}function W(n,e){return e?new Promise((t,r)=>{let s=()=>{clearTimeout(o),r(e.reason??Object.assign(new Error("The operation was aborted."),{name:"AbortError"}))},o=setTimeout(()=>{e.removeEventListener("abort",s),t()},n);e.aborted?s():e.addEventListener("abort",s,{once:!0})}):new Promise(t=>setTimeout(t,n))}function Y(n){return n instanceof Error&&n.name==="AbortError"}function _(){return new a.FloPayError(a.CHECKOUT_PROCESSING_TIMEOUT_MESSAGE,"api_error",{code:"checkout_processing_timeout"})}async function R(n,e){let t=await n.json().catch(()=>null),r=de(t?.error)?t.error:null,s=ue(t,"message")??ue(r,"message")??e,o=I(t,"code")??I(t,"gatewayErrorCode")??I(r,"code")??`http_${n.status}`;return new a.FloPayError(s,"api_error",{code:o,statusCode:n.status})}async function je(n){let e=n.status===400?await n.clone().json().catch(()=>null):null;return(0,a.classifyPaymentRejection)(n.status,e)}function ce(n){return n===400||n===422}var N=2;async function L(n,e,t=N,r,s){let o;for(let i=0;;i++)try{return s?.(i),await fetch(n,e)}catch(u){if(e?.signal?.aborted||u instanceof Error&&u.name==="AbortError")throw u;if(o=u,i>=t)throw o;try{r?.(i+1)}catch{}await W(150*2**i,e?.signal??void 0)}}var Ke=Symbol.for("@flopay/js.session-create.telemetry.v1");function Ge(n){return n[Ke]}function $e(n){return"now"in n||"onFirstByte"in n||"onSessionCreateFailure"in n||"onRetry"in n}function me(n){let e=(0,a.isCardHolderNamePlaceholder)(n.firstName,n.lastName);return{userId:n.userId,firstName:e?null:n.firstName??null,lastName:e?null:n.lastName??null,email:n.email,country:n.country??null,gender:n.gender??null,city:n.city??null,state:n.state??null,zip:n.zip??null,addressLine1:n.addressLine1??null,addressLine2:n.addressLine2??null}}function pe(n,e){e.checkoutMetadata!==void 0&&(n.checkoutMetadata=e.checkoutMetadata),e.tagsData&&(n.tagsData=e.tagsData),e.utmMetadata&&e.utmMetadata.length>0&&(n.utmMetadata=e.utmMetadata),e.avsCheck!==void 0&&(n.avsCheck=e.avsCheck),e.checkoutType&&(n.checkoutType=e.checkoutType),e.checkoutLayout&&(n.checkoutLayout=e.checkoutLayout),e.avsConfig&&(n.avsConfig=e.avsConfig)}function Ye(n,e){let t={clientId:n.clientId,checkoutVersion:a.SDK_VERSION,successUrl:n.successUrl,cancelUrl:n.cancelUrl,currency:e,checkoutMode:"full",deferDataAttachment:!0};return n.captureMethod==="manual"&&(t.captureMethod=n.captureMethod),n.account.country&&(t.accountData={country:n.account.country}),pe(t,n),t}function le(n,e,t){return{currency:e,products:t.map(r=>(0,a.buildProductPayload)(r,e)),couponCodes:n.couponCodes??[],accountData:me(n.account)}}function We(n,e,t){return{currency:e,products:t.map(r=>(0,a.buildProductPayload)(r,e)),couponCodes:n.couponCodes??[]}}function Je(n){let e={},t=(0,a.isCardHolderNamePlaceholder)(n.firstName,n.lastName);for(let[r,s]of Object.entries(n)){if(t&&r.endsWith("Name")||typeof s!="string")continue;let o=s.trim();o&&(e[r]=o)}return{accountData:e}}var M=class M{constructor(e,t={}){this.baseUrl=e.replace(/\/+$/,"");let r=$e(t);this.telemetryHooks=r?t:void 0,this.directTelemetry=r||t.telemetry===!1?void 0:new k({billingApiUrl:this.baseUrl,sdkVersion:a.SDK_VERSION})}destroy(){this.directTelemetry?.destroy()}reportDirectFailure(e,t,r,s,o="unknown"){let i=(0,a.classifyTelemetryFailure)(e,t);this.directTelemetry?.error({...i,stage:r,requestCategory:s,paymentMethodCategory:o})}reportAccountSnapshotFailure(e,t){let r=(0,a.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED");if(t==="best_effort"&&r.errorCode==="REQUEST_TIMEOUT"){this.directTelemetry?.log({name:"operation.fallback",stage:"processing",requestCategory:"account_snapshot",statusClass:"timeout"});return}this.directTelemetry?.error({...r,stage:"processing",requestCategory:"account_snapshot",paymentMethodCategory:"unknown"})}telemetryTimestamp(){try{return this.telemetryHooks?.now?.()??this.directTelemetry?.now()??A()}catch{return A()}}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,r=!0,s){this.beginDirectTelemetryCheckout(e);let o=this.telemetryTimestamp(),i=o,u=0;this.directTelemetry?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let c={[a.FLO_SDK_VERSION_HEADER]:a.SDK_VERSION};t&&(c["x-checkout-session-token"]=t);try{let l=await L(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}`,{headers:c,signal:s},N,f=>{this.telemetryHooks?.onRetry?.("session_read",f),this.directTelemetry?.log({name:"operation.retry",stage:"session_read",requestCategory:"session_read",attempt:f})},f=>{u=f,i=this.telemetryTimestamp()}),d=Math.max(0,this.telemetryTimestamp()-i);try{this.telemetryHooks?.onFirstByte?.(d,u)}catch{}let p=`${Math.floor(l.status/100)}xx`;if(this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:p,attempt:u}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:d,durationMode:"machine",requestCategory:"session_read",statusClass:p,attempt:u}),!l.ok)throw await R(l,"Failed to get checkout session");let m=await l.json();return this.directTelemetry?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:p}),this.directTelemetry?.performance({stage:"session_complete",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"session_read",statusClass:p}),{...m,data:this.mergeCachedDisplayData(m.data)}}catch(l){throw r&&this.directTelemetry?.error({...(0,a.classifyTelemetryFailure)(l,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"}),l}}cacheSessionDisplayData(e,t,r){G(e,t,r)}clearSessionDisplayData(e){te(e)}async getVaultCapture(e,t){let r=`${this.baseUrl}\0${e}\0${t??""}`,s=M.activeVaultCaptureRequests.get(r);if(s)return s;let o=this.requestVaultCapture(e,t);M.activeVaultCaptureRequests.set(r,o);try{return await o}finally{M.activeVaultCaptureRequests.get(r)===o&&M.activeVaultCaptureRequests.delete(r)}}async requestVaultCapture(e,t){let r=new AbortController,s=setTimeout(()=>r.abort(),He);this.beginDirectTelemetryCheckout(e);let o=this.telemetryTimestamp();this.directTelemetry?.log({name:"vault.capture.requested",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card"});let i={"Content-Type":"application/json"};t&&(i["x-checkout-session-token"]=t);try{let u=await L(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/vault/capture`,{method:"POST",headers:i,signal:r.signal},N,l=>{this.telemetryHooks?.onRetry?.("vault_capture",l),this.directTelemetry?.log({name:"operation.retry",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card",attempt:l})});if(!u.ok)throw await R(u,"Failed to load the secure card form");let c=await u.json();return this.directTelemetry?.performance({stage:"vault_request",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"2xx"}),this.toVaultBlock(c)}catch(u){let c=r.signal.aborted?new a.FloPayError("Timed out while loading the secure card form. Please try again.","api_error",{code:"vault_capture_timeout"}):u;throw this.reportDirectFailure(c,"VAULT_LOAD_FAILED","vault_request","vault_capture","card"),c}finally{clearTimeout(s)}}async getUnifiedCheckoutSession(e,t){let r=await this.getCheckoutSession(e,t);return this.normalizeCheckoutSessionResponse(r)}async getUnifiedCheckoutSessionForRecovery(e,t,r){let s=await this.fetchCheckoutSession(e,t,!1,r);return this.normalizeCheckoutSessionResponse(s)}normalizeCheckoutSessionResponse(e){let t=this.normalizeRawSession(e.data),r=e.vault;return r&&t.data.session&&(t.data.session.vault=this.toVaultBlock(r)),t}async processPayment(e,t,r){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 a.FloPayError("processPayment requires `nonce` \u2014 pass the value returned from session creation.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let o=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.processing.started",stage:"processing",requestCategory:"process_payment",paymentMethodCategory:s});let{nonce:i,paymentMethodCategory:u,...c}=t,l;try{l=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(t.sessionId)}/process`,{method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":i},body:JSON.stringify(c)})}catch(d){if(Y(d))throw this.reportDirectFailure(d,"PAYMENT_PROCESSING_FAILED","processing","process_payment",s),d;l=await this.reconcileProcessPayment(t.sessionId,{...r,nonce:i,paymentMethodCategory:s})}if(!l.ok&&l.status!==202){let d=await je(l);return d?this.directTelemetry?.terminal({outcome:d,stage:"processing",requestCategory:"process_payment",statusClass:"4xx",paymentMethodCategory:s}):this.directTelemetry?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",requestCategory:"process_payment",statusClass:(0,a.telemetryStatusClass)(l.status),failureCategory:l.status>=500?"server_error":void 0,paymentMethodCategory:s}),l}try{let d=await this.resolveProcessResponse(l,t.sessionId,{...r,nonce:i,paymentMethodCategory:s});return this.directTelemetry?.log({name:"payment.processing.completed",stage:"processing",requestCategory:"process_payment",statusClass:(0,a.telemetryStatusClass)(d.status),paymentMethodCategory:s}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"process_payment",statusClass:(0,a.telemetryStatusClass)(d.status),paymentMethodCategory:s}),d}catch(d){throw d instanceof a.FloPayError&&d.code==="checkout_processing_timeout"||this.reportDirectFailure(d,"PAYMENT_PROCESSING_FAILED","processing","process_payment",s),d}}async patchAccountSnapshot(e,t,r,s){this.beginDirectTelemetryCheckout(e);let o=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.state_transition",stage:"processing",requestCategory:"account_snapshot"});let i=s?.timeoutMs??ze,u=new AbortController,c=()=>u.abort();s?.signal&&(s.signal.aborted?u.abort():s.signal.addEventListener("abort",c,{once:!0}));let l=setTimeout(()=>u.abort(),i);try{let d;try{d=await L(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/account`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":t},body:JSON.stringify(r),signal:u.signal},N,p=>{this.telemetryHooks?.onRetry?.("account_snapshot",p),this.directTelemetry?.log({name:"operation.retry",stage:"processing",requestCategory:"account_snapshot",attempt:p})})}finally{clearTimeout(l),s?.signal?.removeEventListener("abort",c)}if(!d.ok)throw await R(d,"Failed to persist account snapshot");this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"account_snapshot",statusClass:"2xx"})}catch(d){throw this.reportAccountSnapshotFailure(d,s?.telemetryMode??"blocking"),d}}async createSessionIntent(e,t,r,s){if(!t)throw new a.FloPayError("createSessionIntent requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let o=r,i=o.paymentMethodType,u=typeof i=="string"&&i.trim().toLowerCase()==="card",c=typeof i=="string"&&i.length>0&&!u&&(typeof o.paymentMethodId=="string"||o.paymentMethodId===null),l=o.provider==="stripe"&&(o.paymentMethodCategory==="wallet"||o.paymentMethodCategory==="apm")&&(o.intentKind==="payment"||o.intentKind==="setup"),d=o.provider==="paypal"&&o.paymentMethodCategory==="wallet"&&o.paymentMethodId===null&&(o.paymentMethodType==="paypal"&&o.intentKind==="payment"||o.paymentMethodType===a.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&(o.intentKind==="payment"||o.intentKind==="setup"));if(!c||!l&&!d)throw new a.FloPayError("Only wallet, APM, and PayPal session intents are supported.","validation_error",{code:"InvalidSessionIntentRequest"});let p=o.authorizationAttemptId;if(p!==void 0&&!(0,a.isUuidV4)(p))throw new a.FloPayError("authorizationAttemptId must be a v4 UUID identifying one buyer authorization attempt.","validation_error",{code:"InvalidAuthorizationAttemptId",param:"authorizationAttemptId"});let m=(0,a.isUuidV4)(p)?p:(0,a.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,[a.IDEMPOTENCY_KEY_HEADER]:s?.idempotencyKey||m},C=!1;try{let y=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents`,{method:"POST",headers:h,body:JSON.stringify({...r,authorizationAttemptId:m}),signal:s?.signal});if(!y.ok){C=!0;let B=await R(y,"Failed to create checkout intent"),be=(0,a.classifyTelemetryFailure)(B,"PAYMENT_PROCESSING_FAILED");throw ce(B.statusCode)?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"intent_create",statusClass:"4xx"}):this.directTelemetry?.error({...be,stage:"processing",requestCategory:"intent_create"}),B}let b=(await y.json()).data;if(!b||typeof b!="object")throw new a.FloPayError("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});let g=b,Q=g.paymentMethodType,fe=(g.paymentMethodCategory==="wallet"||g.paymentMethodCategory==="apm")&&typeof Q=="string"&&Q.trim().toLowerCase()!=="card"&&(typeof g.paymentMethodId=="string"||g.paymentMethodId===null)&&typeof g.providerObjectId=="string",Ce=g.provider==="stripe"&&(g.intentKind==="payment"||g.intentKind==="setup")&&typeof g.clientSecret=="string",ve=g.provider==="paypal"&&g.paymentMethodCategory==="wallet"&&g.paymentMethodId===null&&(g.paymentMethodType==="paypal"&&g.intentKind==="payment"&&(g.providerObjectType==="order"||g.providerObjectType==="subscription")||g.paymentMethodType===a.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&g.intentKind==="payment"&&g.providerObjectType==="order"||g.paymentMethodType===a.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&g.intentKind==="setup"&&g.providerObjectType==="setup_token")&&g.clientSecret===null,Te=g.provider===r.provider&&g.paymentMethodCategory===r.paymentMethodCategory&&g.paymentMethodType===r.paymentMethodType&&g.paymentMethodId===r.paymentMethodId&&g.intentKind===r.intentKind;if(!fe||!Ce&&!ve||!Te)throw new a.FloPayError("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});return this.directTelemetry?.log({name:"payment.intent.completed",stage:"processing",requestCategory:"intent_create",statusClass:(0,a.telemetryStatusClass)(y.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-f),durationMode:"machine",requestCategory:"intent_create",statusClass:(0,a.telemetryStatusClass)(y.status)}),g}catch(y){throw C||this.reportDirectFailure(y,"PAYMENT_PROCESSING_FAILED","processing","intent_create"),y}}async reportSessionIntentDecline(e,t,r,s){if(!t)throw new a.FloPayError("reportSessionIntentDecline requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let o=r,i=o.providerDeclineReason,u=o.paymentMethodType,c=o.providerIntentId,l=typeof i=="string"&&/^[a-z0-9][a-z0-9_.:-]{0,63}$/i.test(i)&&!/^(?:pm|pi|seti|tok|src|cus|sess|sk|pk)_/i.test(i),d=typeof u=="string"&&u.length>0&&u.trim().toLowerCase()!=="card"&&l,p=o.provider==="stripe"&&(o.paymentMethodCategory==="wallet"||o.paymentMethodCategory==="apm")&&(c===void 0||typeof c=="string"&&/^pi_[a-z0-9_]{1,252}$/i.test(c)),m=o.provider==="paypal"&&o.paymentMethodCategory==="wallet"&&o.paymentMethodType==="paypal"&&c===void 0;if(!d||!p&&!m)throw new a.FloPayError("Invalid non-card decline classification.","validation_error",{code:"InvalidSessionIntentDeclineRequest"});let f=m?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:i}:{provider:"stripe",paymentMethodCategory:o.paymentMethodCategory,paymentMethodType:o.paymentMethodType,providerDeclineReason:i,...typeof c=="string"?{providerIntentId:c}:{}},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 R(h,"Failed to report checkout decline")}async getPaymentsByEmail(e,t){this.beginDirectTelemetryOperation();let r=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved"});let s=t?.page??1,o=t?.limit??1,i=new URLSearchParams({email:e,page:String(s),limit:String(o),sortField:"createdAt",sortDirection:"DESC"});try{let u=await fetch(`${this.baseUrl}/v1/payments?${i.toString()}`,{method:"GET",signal:t?.signal,keepalive:!0});if(!u.ok)throw new a.FloPayError("Failed to fetch payments","api_error",{statusCode:u.status});let c=await u.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()-r),durationMode:"machine",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),c}catch(u){throw this.reportDirectFailure(u,"RECOVERY_FAILED","recovery","other","saved"),u}}async createAndFetchSession(e){if((0,a.isDetachedSessionEligible)(e)){let o=e.account.email?.trim();if(o&&!(0,a.isValidEmail)(o))throw new a.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(),r=E(e.timeoutMs??12e3),s={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});try{let o=await this.createAndFetchSessionRequest(e,r.signal,s);return this.adoptDirectTelemetryCheckout(o.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}),o}catch(o){throw this.reportSessionCreateFailure(o,t,s),o}finally{r.clear()}}async createAndFetchSessionRequest(e,t,r){let s=e.products??(0,a.foldIntoProducts)(e.items,e.subscriptions);(0,a.assertCaptureMethodEligible)({captureMethod:e.captureMethod,products:s});let o=(0,a.resolveSessionCurrency)(e.currency,e.items,e.subscriptions,s);if(!o)throw new a.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 i={clientId:e.clientId,checkoutVersion:a.SDK_VERSION,successUrl:e.successUrl,cancelUrl:e.cancelUrl,currency:o,checkoutMode:e.checkoutMode??"full",products:s.map(p=>(0,a.buildProductPayload)(p,o)),accountData:me(e.account),couponCodes:e.couponCodes??[]};e.captureMethod==="manual"&&(i.captureMethod=e.captureMethod),e.tokenizedData&&(i.tokenizedData=e.tokenizedData),pe(i,e);let c=await(await this.postCheckoutSessionCreate(i,e,t,r)).json();if(c.data&&"gateways"in c.data){this.autoCacheDisplayData(c.data.uuid,e);let p=this.mergeCachedDisplayData(c.data),m=this.normalizeRawSession(p);return c.vault&&m.data.session&&(m.data.session.vault=this.toVaultBlock(c.vault)),{...m,autoProcessingError:c.autoProcessingError,autoProcessingAttempted:c.autoProcessingAttempted,autoProcessingPending:c.autoProcessingPending}}let l=c.data?.uuid;if(!l)throw new a.FloPayError("No session ID returned","api_error",{code:"InvalidCheckoutSessionResponse"});return this.autoCacheDisplayData(l,e),this.adoptDirectTelemetryCheckout(l),{...await this.getUnifiedCheckoutSession(l),autoProcessingError:c.autoProcessingError,autoProcessingAttempted:c.autoProcessingAttempted,autoProcessingPending:c.autoProcessingPending}}async postCheckoutSessionCreate(e,t,r,s){let o={"Content-Type":"application/json",[a.FLO_SDK_VERSION_HEADER]:a.SDK_VERSION},i=(0,a.resolveIdempotencyKey)(t.idempotencyKey);i&&(o[a.IDEMPOTENCY_KEY_HEADER]=i),t.checkoutMode==="auto"&&(o[a.FLO_SDK_CAPABILITIES_HEADER]=a.ASYNC_AUTO_CHECKOUT_CAPABILITY);let u,c=!1,l=Ge(t),d=(m,f,h)=>{c||(c=!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{l?.onAttempt?.(m)}catch{}try{u=await fetch(`${this.baseUrl}/v1/checkouts/sessions?expand=true`,{method:"POST",headers:o,body:JSON.stringify(e),signal:r})}catch(y){if(s.statusClass=r.aborted||y instanceof Error&&y.name==="AbortError"?"timeout":"network_error",r.aborted||y instanceof Error&&y.name==="AbortError"||m>=2)throw y;let S=m+1;p(S),await x(m,r);continue}let h=(0,a.telemetryStatusClass)(u.status);if(s.statusClass=h,u.status===204)throw d(m,f,h),new a.FloPayError("Session auto-completed \u2014 payment method already on file","api_error",{code:"session_auto_completed"});if(u.ok){d(m,f,h);break}let C=await R(u,"Failed to create checkout session");if(C.code===a.IDEMPOTENCY_IN_PROGRESS_CODE&&m<2){p(m+1),await x(m,r);continue}throw d(m,f,h),C}if(!u)throw new TypeError("Checkout-session creation exhausted its retry budget.");return u}async createDetachedSession(e){this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp(),r=E(e.timeoutMs??12e3),s={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let o=e.products??(0,a.foldIntoProducts)(e.items,e.subscriptions);try{(0,a.assertCaptureMethodEligible)({captureMethod:e.captureMethod,products:o})}catch(y){throw r.clear(),this.reportSessionCreateFailure(y,t,s),y}let i=(0,a.resolveSessionCurrency)(e.currency,e.items,e.subscriptions,o);if(!i)throw r.clear(),this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),new a.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{le(e,i,o)}catch(y){throw r.clear(),this.reportSessionCreateFailure(y,t,s),y}let u,c;try{if(c=await(await this.postCheckoutSessionCreate(Ye(e,i),e,r.signal,s)).json(),!c.data||!("gateways"in c.data))throw new a.FloPayError("The billing API returned no session shell for a detached create. It must support `deferDataAttachment` (TeamFloPay/backend#1099).","api_error",{code:"InvalidCheckoutSessionResponse"});u=this.normalizeRawSession(this.mergeCachedDisplayData(c.data)),c.vault&&u.data.session&&(u.data.session.vault=this.toVaultBlock(c.vault))}catch(y){throw r.clear(),this.reportSessionCreateFailure(y,t,s),y}let l=u.data.session?.id??c.data.uuid??"",d=u.data.session?.clientSecret??c.data.nonce??"";if(!l||!d){r.clear();let y=new a.FloPayError("Checkout session shell was created without a session id or nonce.","api_error",{code:"InvalidCheckoutSessionResponse"});throw this.reportSessionCreateFailure(y,t,s),y}r.clear(),this.adoptDirectTelemetryCheckout(l),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 p=!e.account.email?.trim(),m=E(e.timeoutMs??12e3),f=this.claimCheckoutSession(l,d,p?We(e,i,o):le(e,i,o),{params:e,startedAt:t,deadline:m,createAttempt:s.attempt}),h=p?void 0:f,C=(y={})=>{if(h!==void 0)return h;let S={...e,account:{...e.account,...y,email:y.email?.trim()||e.account.email?.trim()}};return(0,a.isValidEmail)(S.account.email)?(h=f.then(()=>{let b=this.telemetryTimestamp();return this.claimCheckoutSession(l,d,Je(S.account),{params:S,startedAt:b,deadline:E(e.timeoutMs??12e3),createAttempt:0})}),h.catch(()=>{}),h):Promise.reject(new a.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}))};return f.catch(()=>{}),{shell:u,sessionId:l,nonce:d,claimed:f,claim:C}}async claimCheckoutSession(e,t,r,s){let o=s?.startedAt??this.telemetryTimestamp(),i=this.telemetryTimestamp(),u=s?.deadline??E(12e3),c=JSON.stringify(r),l="unknown",d=0;this.directTelemetry?.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"});try{let p;for(d=0;d<3;d++){try{p=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/claim`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":t,[a.FLO_SDK_VERSION_HEADER]:a.SDK_VERSION},body:c,signal:u.signal})}catch(h){let C=u.signal.aborted||h instanceof Error&&h.name==="AbortError";if(l=C?"timeout":"network_error",C||d>=2)throw h;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 x(d,u.signal);continue}if(l=(0,a.telemetryStatusClass)(p.status),p.ok)break;throw await R(p,"Failed to attach checkout session data")}if(!p)throw new TypeError("Checkout-session claim exhausted its retry budget.");let m=await p.json();if(!m.data?.gateways)throw new a.FloPayError("The billing API returned no checkout session with gateways after claiming it.","api_error",{code:"InvalidCheckoutSessionResponse"});s?.params&&this.autoCacheDisplayData(m.data.uuid??e,s.params);let f=this.normalizeRawSession(this.mergeCachedDisplayData(m.data));return m.vault&&f.data.session&&(f.data.session.vault=this.toVaultBlock(m.vault)),this.directTelemetry?.log({name:"session.claim.completed",stage:"session_claim",requestCategory:"session_claim",statusClass:l}),this.directTelemetry?.performance({stage:"session_claim",durationMs:Math.max(0,this.telemetryTimestamp()-i),durationMode:"machine",requestCategory:"session_claim",statusClass:l,attempt:d}),this.directTelemetry?.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:l}),this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"session_create",statusClass:l,attempt:s?.createAttempt??d}),f}catch(p){throw this.reportSessionCreateFailure(p,i,{attempt:d,statusClass:l},"session_claim"),p}finally{u.clear()}}reportSessionCreateFailure(e,t,r,s="session_create"){if(!(e instanceof a.FloPayError&&e.code==="session_auto_completed"))try{this.telemetryHooks?.onSessionCreateFailure?.(e)}catch{}let o=(0,a.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:o.statusClass,attempt:r.attempt}),e instanceof a.FloPayError&&e.type==="validation_error"||e instanceof a.FloPayError&&ce(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 a.FloPayError&&e.code==="session_auto_completed"||this.directTelemetry?.error({...o,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"})}async waitForCheckoutSessionCompletion(e,t){this.beginDirectTelemetryCheckout(e);let r=this.telemetryTimestamp(),s=t?.paymentMethodCategory??"saved";this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:s});let o=t?.timeoutMs??q,i=Date.now()+o,u=new AbortController,c=!1,l,d=setTimeout(()=>{l=setTimeout(()=>{c=!0,u.abort()},ae)},o),p=()=>u.abort(t?.signal?.reason);t?.signal?.aborted?p():t?.signal?.addEventListener("abort",p,{once:!0});let m=this.clampRetryAfterMs(t?.initialDelayMs??oe),f=0;try{if(t?.statusUrl){let h=await this.waitForCheckoutStatus(e,{initialDelayMs:m,timeoutMs:o,nonce:t.nonce,statusUrl:t.statusUrl,pollAfterAction:t.continueAfterActionRequired,signal:u.signal});if(h){let C=await this.resolveCheckoutSessionStatus(e,h,t.nonce,u.signal,()=>c);return this.reportRecoveryCompleted(r,s),C}}for(;;){let h=i-Date.now();if(h<=0)throw _();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 W(Math.min(m,h),u.signal),Date.now()>=i)throw _()}let C=await this.getUnifiedCheckoutSessionForRecovery(e,t?.nonce,u.signal),y=C.data.session?.status;if(y==="authorized"||y==="complete"||y==="expired")return this.reportRecoveryCompleted(r,s),C;if(Date.now()>=i)throw _();m=this.clampRetryAfterMs(Math.max(m*2,ie))}}catch(h){let C=c&&Y(h)?_():h;throw this.reportDirectFailure(C,"RECOVERY_FAILED","recovery","session_read",s),C}finally{clearTimeout(d),clearTimeout(l),t?.signal?.removeEventListener("abort",p)}}reportRecoveryCompleted(e,t){let r={stage:"recovery",requestCategory:"session_read",paymentMethodCategory:t};this.directTelemetry?.log({name:"operation.recovery.completed",...r}),this.directTelemetry?.performance({...r,durationMs:Math.max(0,this.telemetryTimestamp()-e),durationMode:"machine"})}async resolveCheckoutSessionStatus(e,t,r,s,o){let i=t.latestTransactionAttempt;if(i?.result==="DECLINE"){let l=i.code===a.STORED_PAYMENT_METHOD_UNSUPPORTED_CODE;throw new a.FloPayError(l?a.STORED_PAYMENT_METHOD_UNSUPPORTED_MESSAGE:"Payment was declined. Please choose another payment method.","api_error",{code:i.code??i.declineReason??"authorization_declined",statusCode:400})}if(i?.result==="ERROR"||t.status==="voided")throw new a.FloPayError("Payment could not be completed. Please try again.","api_error",{code:i?.code??"payment_processing_error",statusCode:500});let u;try{u=await this.getUnifiedCheckoutSessionForRecovery(e,r,s)}catch(l){if(!o?.()||!Y(l))throw l;u={providers:[],mode:"tokenize",data:{},raw:t}}let c=u.data.session;return c&&i?.result==="SUCCESS"?{...u,data:{...u.data,session:{...c,status:"complete"}}}:c&&i?.result==="AUTHORIZED"?{...u,data:{...u.data,session:{...c,status:"authorized",paymentId:t.paymentId??void 0,authorizationExpiresAt:t.authorizationExpiresAt??void 0}}}:c&&t.status==="completed"?{...u,data:{...u.data,session:{...c,status:"complete"}}}:c&&t.status==="authorized"?{...u,data:{...u.data,session:{...c,status:"authorized",paymentId:t.paymentId??void 0,authorizationExpiresAt:t.authorizationExpiresAt??void 0}}}:c&&t.status==="expired"?{...u,data:{...u.data,session:{...c,status:"expired"}}}:i?.result!=="ACTION_REQUIRED"?u:i.gateway==="paypal"&&i.providerIntentId?{...u,autoProcessingError:{type:"paypal_direct_required",message:"PayPal authorization required",orderId:i.providerIntentId,checkoutMethod:"paypal"}}:i.nextActionRedirectUrl?{...u,autoProcessingError:{type:"3ds_required",message:"Additional authentication is required.",nextActionRedirectUrl:i.nextActionRedirectUrl}}:u}async waitForCheckoutStatus(e,t){let r=t.timeoutMs??q,s=Date.now()+r,o=this.clampRetryAfterMs(t.initialDelayMs);for(;;){let i=s-Date.now();if(i<=0||o>0&&(await W(Math.min(o,i),t.signal),Date.now()>=s))throw _();let u=s-Date.now();if(u<=0)throw _();let c=new AbortController,l,d=t.signal?new Promise((S,b)=>{l=b}):null,p=()=>{c.abort(t.signal?.reason),l?.(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((S,b)=>{m=setTimeout(()=>{b(_()),c.abort()},u+ae)}),h;try{let S=this.fetchCheckoutStatus(e,t.nonce,t.statusUrl,c.signal);h=await Promise.race([S,f,d].filter(b=>b!==null))}finally{m!==void 0&&clearTimeout(m),t.signal?.removeEventListener("abort",p)}if(!h)return null;let C=h.latestTransactionAttempt?.result,y=t.pollAfterAction===!0&&C==="ACTION_REQUIRED";if(h.status==="completed"||h.status==="authorized"||h.status==="expired"||h.status==="voided"||C!==void 0&&C!=="PENDING"&&!y)return h;o=this.clampRetryAfterMs(Math.max(o*2,ie))}}async fetchCheckoutStatus(e,t,r,s){let o=`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/status`,i=o;if(r)try{let d=new URL(r,`${this.baseUrl}/`),p=new URL(o);d.origin===p.origin&&(i=d.toString())}catch{}let u={[a.FLO_SDK_VERSION_HEADER]:a.SDK_VERSION};t&&(u["x-checkout-session-token"]=t);let c=await L(i,{headers:u,signal:s});if(c.status===404||c.status===405)return null;if(!c.ok)throw await R(c,"Failed to get checkout session status");let l=await c.json();return de(l.data)&&"latestTransactionAttempt"in l.data?l.data:null}normalizeRawSession(e){let t=e.gateways??{},r=[],s={session:this.toCheckoutSession(e)},o=t.stripe;if(o?.publishableKey){r.push("stripe");let c=[e.stripeClientSecret,o.stripeClientSecret].find(l=>typeof l=="string"&&l.length>0);s.stripe={clientSecret:c??"",publishableKey:o.publishableKey??void 0,paypalPublishableKey:o.paypalPublishableKey??void 0,environment:o.environment,enabledPaymentMethods:Array.isArray(o.enabledPaymentMethods)?o.enabledPaymentMethods.filter(l=>typeof l=="string"):void 0}}let i=t.paypal;return i?.publishableKey&&(r.push("paypal"),s.paypal={publishableKey:i.publishableKey,environment:i.environment,providerObjectType:i.providerObjectType,approvalPresentation:i.approvalPresentation}),{providers:r,mode:"tokenize",...e.checkoutMetadata===void 0?{}:{checkoutMetadata:e.checkoutMetadata},data:s,raw:{data:e}}}toCheckoutSession(e){let t=e.products??[],r=typeof e.totalAmount=="number"&&Number.isFinite(e.totalAmount),s=t.reduce((l,d)=>l+(d.overrideAmount??d.totalAmount??0),0),o=r?e.totalAmount:s,i=Math.round(o*100),u=e.currency??t[0]?.currency??"USD",c="payment";return e.checkoutMode==="setup"?c="setup":t.some(l=>l.type==="subscription")&&(c="subscription"),{id:e.uuid,clientSecret:e.nonce,mode:c,status:this.toCheckoutSessionStatus(e.status),amount:i,currency:u,captureMethod:e.captureMethod,paymentId:e.paymentId,authorizationExpiresAt:e.authorizationExpiresAt,failureOutcome:(0,a.normalizeCheckoutFailureOutcome)(e.outcome)??(0,a.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}:{},...Le(e.futureUse)?{futureUse:e.futureUse}:{},...Array.isArray(e.futureUseUnsupported)?{futureUseUnsupported:e.futureUseUnsupported.filter(Ne)}:{},buyerIdentified:e.buyerIdentified,providerPaymentMethodId:typeof e.providerPaymentMethodId=="string"?e.providerPaymentMethodId:null,products:t.map(l=>({...l,totalAmount:typeof l.totalAmount=="number"?l.totalAmount:void 0,overrideAmount:typeof l.overrideAmount=="number"?l.overrideAmount:null,currency:typeof l.currency=="string"?l.currency:void 0,metadata:l.metadata??null})),successUrl:e.successUrl,cancelUrl:e.cancelUrl,coupons:e.coupons,subtotalAmount:e.subtotalAmount,discountAmount:e.discountAmount,totalAmount:e.totalAmount,createdAt:e.createdAt,gateways:e.gateways,accountData:e.accountData,tagsData:e.tagsData}}toVaultBlock(e){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}}toCheckoutSessionStatus(e){return e==="completed"?"complete":e==="authorized"?"authorized":e==="expired"?"expired":"open"}async resolveProcessResponse(e,t,r){if(e.status!==202)return e;let s=await e.json().catch(()=>null),o=this.toCheckoutProcessingPending(s,e,t),i=r?.pollTimeoutMs??q,u=Date.now()+i;if(o.statusUrl){let l=await this.waitForCheckoutStatus(o.sessionId,{initialDelayMs:o.retryAfterMs,timeoutMs:i,nonce:r?.nonce,statusUrl:o.statusUrl});if(l)return this.toProcessResponseFromStatus(l,t,r?.nonce)}let c=await this.waitForCheckoutSessionCompletion(o.sessionId,{initialDelayMs:o.retryAfterMs,timeoutMs:u-Date.now(),nonce:r?.nonce,paymentMethodCategory:r?.paymentMethodCategory});return this.toProcessResponseFromSession(c,t)}async toProcessResponseFromStatus(e,t,r){let s=e.latestTransactionAttempt?.result;if(e.status==="completed"||s==="SUCCESS")return new Response(null,{status:204,statusText:"No Content"});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:{"Content-Type":"application/json"}});if(e.status==="expired"){let o=await this.resolveCheckoutSessionStatus(t,e,r);return this.toProcessResponseFromSession(o,t)}if(s==="DECLINE"){let o=e.latestTransactionAttempt,i=o?.code===a.STORED_PAYMENT_METHOD_UNSUPPORTED_CODE;return new Response(JSON.stringify({type:o?.declineReason??"authorization_declined",message:i?a.STORED_PAYMENT_METHOD_UNSUPPORTED_MESSAGE:"Payment was declined. Please choose another payment method.",...o?.code?{code:o.code}:{}}),{status:400,headers:{"Content-Type":"application/json"}})}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:{"Content-Type":"application/json"}});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:{"Content-Type":"application/json"}});if(s==="ERROR"||e.status==="voided")return new Response(JSON.stringify({type:"unknown",code:e.latestTransactionAttempt?.code??"payment_processing_error",message:"Payment could not be completed. Please try again."}),{status:500,headers:{"Content-Type":"application/json"}});throw _()}async reconcileProcessPayment(e,t){let r=t?.pollTimeoutMs??q,s=Date.now()+r,o=null;try{o=await this.waitForCheckoutStatus(e,{initialDelayMs:0,timeoutMs:r,nonce:t?.nonce})}catch(c){if(this.reportDirectFailure(c,"RECOVERY_FAILED","recovery","session_read",t?.paymentMethodCategory??"saved"),c instanceof a.FloPayError&&c.code==="checkout_processing_timeout")throw c}if(o)return this.toProcessResponseFromStatus(o,e,t?.nonce);let i=s-Date.now();if(i<=0)throw _();let u=await this.waitForCheckoutSessionCompletion(e,{initialDelayMs:0,timeoutMs:i,nonce:t?.nonce,paymentMethodCategory:t?.paymentMethodCategory});return this.toProcessResponseFromSession(u,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 r=e.data.session;return new Response(JSON.stringify({status:"authorized",paymentId:r.paymentId,sessionId:r.id||t,authorizationExpiresAt:r.authorizationExpiresAt}),{status:200,headers:{"Content-Type":"application/json"}})}if(e.data.session?.status==="expired"){let r=e.data.session.failureOutcome==="authorization_expired"||e.data.session.captureMethod==="manual";throw new a.FloPayError(r?"Authorization has expired.":"Checkout session has expired.","api_error",{code:r?"authorization_expired":"checkout_session_expired"})}throw _()}toCheckoutProcessingPending(e,t,r){let s=t.headers.get("Retry-After"),o=s===null||s.trim()===""?void 0:Number(s),i=o!==void 0&&Number.isFinite(o)?o*1e3:void 0;return{type:"checkout_processing",sessionId:I(e,"sessionId")??r,retryAfterMs:this.clampRetryAfterMs(Be(e,"retryAfterMs")??i??oe),statusUrl:I(e,"statusUrl"),sessionUrl:I(e,"sessionUrl")}}clampRetryAfterMs(e){return Math.max(0,Math.min(e,Ve))}autoCacheDisplayData(e,t){if(!e)return;let r=t.products??(0,a.foldIntoProducts)(t.items,t.subscriptions);if(r.length===0&&!t.currency)return;let s=t.products!==void 0,o=(0,a.resolveSessionCurrency)(t.currency,s?void 0:t.items,s?void 0:t.subscriptions,r);G(e,{currency:o??void 0,products:r.map(i=>({code:i.code??i.providerItemId??i.providerPlanId,type:i.type,name:i.name??i.itemName??i.providerItemName??i.subscriptionName??i.providerPlanName??null,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency??o??void 0}))})}mergeCachedDisplayData(e){let t=ee(e.uuid),r=new Map,s=i=>i?`code:${i}`:void 0;for(let i of t?.products??[]){let u=s(i.code);u&&r.set(u,i)}let o=(e.products??[]).map(i=>{let u=s(i.code),c=u?r.get(u):void 0;return{...i,name:i.name??c?.name??null,totalAmount:i.totalAmount??c?.totalAmount,overrideAmount:i.overrideAmount??c?.overrideAmount,currency:i.currency??c?.currency}});return{...e,currency:e.currency??t?.currency,products:o}}};M.activeVaultCaptureRequests=new Map;var V=M;var v=require("@flopay/shared");var J="flopay-vault",Qe=3e4,Xe=v.THREE_DS_CHALLENGE_WINDOW_MS+Qe,Ze="Card authentication timed out.",he={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 et(n){return n.class==="lifecycle"?n.name:n.class==="technical_error"?n.code:n.class==="expected_outcome"?n.outcome:"sdk.performance"}function O(n){let e={class:n.class,stage:n.stage};"code"in n&&(e.code=n.code),"provider"in n&&n.provider&&(e.provider=n.provider),"paymentMethodCategory"in n&&n.paymentMethodCategory&&(e.paymentMethodCategory=n.paymentMethodCategory),"outcome"in n&&(e.outcome=n.outcome),"durationMs"in n&&n.durationMs!==void 0&&(e.durationMs=n.durationMs),"durationMode"in n&&n.durationMode&&(e.durationMode=n.durationMode);try{globalThis.Sentry?.addBreadcrumb?.({category:"flopay.telemetry",level:n.class==="technical_error"?"error":"info",message:et(n),data:e})}catch{}}function z(n,e){return(0,v.buildTelemetryLogEvent)({eventId:"11111111-1111-4111-8111-111111111111",name:n,stage:e,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}var tt=new Set(["authorization_declined","authentication_required","authorization_expired","capture_failed"]);function rt(n){return typeof n=="string"&&tt.has(n)?n:"unknown"}function ye(n,e){return n?{errorCode:"VAULT_SUBMIT_FAILED",stage:"vault_submit",failureCategory:"provider_runtime",reason:rt(e.failureOutcome)}:{errorCode:"VAULT_LOAD_FAILED",stage:"vault_mount",failureCategory:"provider_runtime"}}function ge(n,e,t="checkout"){return t==="card_setup"?n.type==="decline"?"card_setup_declined":"card_setup_succeeded":n.type==="decline"?"payment_declined":n.outcome==="authorized"||e==="manual"?"payment_authorized":"payment_succeeded"}function nt(n,e,t,r="checkout"){let{type:s}=n;if(s==="complete"||s==="decline")return(0,v.buildTelemetryTerminalEvent)({eventId:"22222222-2222-4222-8222-222222222222",outcome:ge(n,t,r),sequence:0,provider:"pcivault",paymentMethodCategory:"card"});if(s==="error"){let u=ye(e,n);return(0,v.buildTelemetryErrorEvent)({eventId:"33333333-3333-4333-8333-333333333333",...u,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}let[o,i]=he[s];return z(o,i)}function st(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===J&&(e.type==="ready"||e.type==="submitting"||e.type==="blocked"||e.type==="complete"||e.type==="decline"||e.type==="error"||e.type==="action_required")}function ot(n){if(typeof n!="object"||n===null)return;let e=n,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 it(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===J&&e.type==="validation"&&Array.isArray(e.messages)}function at(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===J&&e.type==="resize"&&typeof e.height=="number"&&Number.isFinite(e.height)}var H=class{constructor(e={},t){this.provider="pcivault";this.container=null;this.messageHandler=null;this.actionOverlay=null;this.threeDsReturnHandler=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.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 k({billingApiUrl:(0,v.resolveBillingApiUrl)(e.billingApiUrl),sdkVersion:v.SDK_VERSION}):void 0)}async mount(e,t){this.ownsTelemetryReporter&&!this.telemetryReporter&&(this.telemetryReporter=new k({billingApiUrl:(0,v.resolveBillingApiUrl)(this.config.billingApiUrl),sdkVersion:v.SDK_VERSION}));let r=this.telemetryReporter;if(this.config.operation==="card_setup"&&r&&this.setupTelemetryReporter!==r){this.setupTelemetryReporter=r;try{r.beginCheckout({checkoutMode:"setup"})}catch{}}if(this.mountStartedAt=this.telemetryReporter?.now?.()??A(),this.vaultReadyReported=!1,this.submissionStarted=!1,this.submissionStartedAt=null,typeof window>"u"||typeof document>"u")throw this.reportVaultLoadFailure(),new v.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 v.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.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(),O(z("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?.()??A())-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 r=this.listeners.get(e);return r||(r=new Set,this.listeners.set(e,r)),r.add(t),()=>{this.listeners.get(e)?.delete(t)}}unmount(){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 r=Array.from(e.querySelectorAll("script"));for(let s of r){let o=document.createElement("script");for(let i of Array.from(s.attributes))o.setAttribute(i.name,i.value);o.text=s.text,s.replaceWith(o)}}attachMessageListener(){if(this.messageHandler)return;let e=t=>{if(this.expectedOrigin&&t.origin!==this.expectedOrigin)return;let r=t.data;if(at(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;this.applyHeight(r.height);return}if(it(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;let c=r.messages.filter(l=>typeof l=="string"&&l.trim()).join(" ");this.emit("validation",{sessionId:this.config.sessionId,message:c||void 0});return}if(!st(r)||this.messageToken&&r.messageToken!==this.messageToken)return;let s=this.config.sessionId,o=typeof r.sessionId=="string"?r.sessionId:void 0;if(s&&o&&o!==s||(r.type==="complete"||r.type==="decline")&&s&&o!==s)return;let i=ot(r.paymentMethod),u={...r.sessionId??this.config.sessionId?{sessionId:r.sessionId??this.config.sessionId}:{},...r.outcome?{outcome:r.outcome}:{},...r.paymentId?{paymentId:r.paymentId}:{},...r.authorizationExpiresAt?{authorizationExpiresAt:r.authorizationExpiresAt}:{},...r.failureOutcome?{failureOutcome:r.failureOutcome}:{},...r.intentId?{intentId:r.intentId}:{},...r.declineReason?{declineReason:r.declineReason}:{},...r.message?{message:r.message}:{},...i?{paymentMethod:i}:{}};r.type==="submitting"&&(this.submissionStarted=!0,this.submissionStartedAt=this.telemetryReporter?.now?.()??A()),O(nt(r,this.submissionStarted,this.config.captureMethod,this.config.operation)),this.reportOutcome(r),r.type==="ready"&&(this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),this.postSubmitLabel()),r.type==="action_required"&&r.nextActionRedirectUrl&&this.showActionRequiredOverlay(r.nextActionRedirectUrl),(r.type==="complete"||r.type==="decline"||r.type==="error"||r.type==="submitting")&&this.hideActionRequiredOverlay(),r.type!=="action_required"&&this.emit(r.type,u)};this.messageHandler=e,window.addEventListener("message",e)}reportOutcome(e){let t=this.telemetryReporter;if(!t)return;let{type:r}=e;if(r==="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"})),r==="complete"||r==="decline"){t.log({name:"vault.terminal",stage:"completion",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:ge(e,this.config.captureMethod,this.config.operation),provider:"pcivault",paymentMethodCategory:"card"});return}if(r==="error"){let i=ye(this.submissionStarted,e);t.log({name:"vault.terminal",stage:i.stage,provider:"pcivault",paymentMethodCategory:"card"}),t.error({...i,provider:"pcivault",paymentMethodCategory:"card"});return}if(r==="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 i=this.submissionStartedAt;this.submissionStartedAt=null,i!==null&&t.performance({stage:"three_ds_handoff",durationMs:Math.max(0,t.now()-i),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:"action_required",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"});return}let[s,o]=he[r];t.log({name:s,stage:o,provider:"pcivault",paymentMethodCategory:"card"})}applyTheme(e){this.theme=e,this.postTheme()}postTheme(){this.theme!==void 0&&this.postToHostedWindow({source:"flopay-vault-host",type:"theme",theme:this.theme},this.directiveTargetOrigin())}setSubmitGate(e){this.submitGateBlocked=e,this.postSubmitGate()}postSubmitGate(){this.postToHostedWindow({source:"flopay-vault-host",type:"gate",blocked:this.submitGateBlocked},this.directiveTargetOrigin())}setCardFieldOrder(e,t){this.cardFieldOrder=e,this.cardAutoFocus=t,this.postCardFieldOrder()}postCardFieldOrder(){this.postToHostedWindow({source:"flopay-vault-host",type:"fieldOrder",order:this.cardFieldOrder,autoFocus:this.cardAutoFocus},this.directiveTargetOrigin())}setSubmitLabel(e){this.submitLabel=e,this.postSubmitLabel()}postSubmitLabel(){let e=this.submitLabel,t=this.config.sessionId,{messageToken:r,expectedOrigin:s}=this;e===void 0||!t||!r||!s||this.postToHostedWindow({source:"flopay-vault-host",type:"submitLabel",sessionId:t,messageToken:r,label:e},s)}hostedWindow(){return this.container?.querySelector("iframe")?.contentWindow??null}postToHostedWindow(e,t){let r=this.hostedWindow();if(r)try{r.postMessage(e,t)}catch{}}directiveTargetOrigin(){return this.expectedOrigin??"*"}emit(e,t){for(let r of this.listeners.get(e)??[])r(t)}showActionRequiredOverlay(e){if(typeof document>"u")return;if(this.actionOverlay){let i=this.actionOverlay.querySelector("iframe");i instanceof HTMLIFrameElement&&i.src!==e&&(i.src=e),this.armActionRequiredTimeout();return}this.actionOverlayPreviousFocus=document.activeElement instanceof HTMLElement?document.activeElement:null;let t=document.createElement("div");t.setAttribute("data-flopay-action-required","1"),t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-label","Card authentication"),t.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 r=document.createElement("iframe");r.setAttribute("title","Card authentication"),r.setAttribute("allow","payment"),r.tabIndex=0,r.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(";"),r.src=e,t.appendChild(r);let s=document.createElement("button");s.type="button",s.setAttribute("aria-label","Close card authentication"),s.textContent="\xD7",s.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(";"),s.addEventListener("click",()=>this.abandonActionRequiredOverlay()),t.appendChild(s),t.addEventListener("click",i=>{i.target===t&&this.abandonActionRequiredOverlay()});let o=i=>{if(i.source!==r.contentWindow)return;let u=i.data;!u||typeof u!="object"||u.source!=="flopay-vault-3ds-return"||(O(z("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",o),this.threeDsReturnHandler=o,document.body.appendChild(t),this.actionOverlay=t,r.focus(),this.armActionRequiredTimeout(),O(z("vault.three_ds.handoff","three_ds_handoff"))}armActionRequiredTimeout(){this.actionOverlayTimer&&clearTimeout(this.actionOverlayTimer),this.actionOverlayTimer=setTimeout(()=>{this.actionOverlayTimer=null,this.actionOverlay&&this.timeOutActionRequiredOverlay()},Xe)}reportChallengeAbandoned(){O((0,v.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(){this.reportChallengeAbandoned(),this.hideActionRequiredOverlay(),this.emit("error",{...this.config.sessionId?{sessionId:this.config.sessionId}:{},message:Ze})}abandonActionRequiredOverlay(){this.actionOverlay&&(this.reportChallengeAbandoned(),this.hideActionRequiredOverlay(),this.emit("challenge_dismissed",{...this.config.sessionId?{sessionId:this.config.sessionId}:{}}))}hideActionRequiredOverlay(){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 r=Math.max(0,Math.min(Math.ceil(e),2e3));t.style.height=`${r}px`}};0&&(module.exports={PaymentAPI,PciVaultCardCapture});
1
+ "use strict";var K=Object.defineProperty;var Re=Object.getOwnPropertyDescriptor;var Ae=Object.getOwnPropertyNames;var ke=Object.prototype.hasOwnProperty;var Ee=(n,e)=>{for(var t in e)K(n,t,{get:e[t],enumerable:!0})},Me=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ae(e))!ke.call(n,s)&&s!==t&&K(n,s,{get:()=>e[s],enumerable:!(r=Re(e,s))||r.enumerable});return n};var we=n=>Me(K({},"__esModule",{value:!0}),n);var gt={};Ee(gt,{PaymentAPI:()=>z,PciVaultCardCapture:()=>B});module.exports=we(gt);var u=require("@flopay/shared");function Z(n){return typeof n=="string"&&n.trim()?n:void 0}function ee(n){if(typeof n=="string")return n.trim()?n:void 0;if(Array.isArray(n))return n.filter(t=>typeof t=="string"&&t.trim().length>0).join("; ")||void 0}function w(n=12e3){let e=Number.isFinite(n)&&n>=0?n:12e3,t=new AbortController,r=setTimeout(()=>t.abort(),e);return{signal:t.signal,clear:()=>clearTimeout(r)}}function Ie(){return Object.assign(new Error("The operation was aborted."),{name:"AbortError"})}function F(n,e){let t=150*2**n,r=Math.round(t*(.75+Math.random()*.5));return new Promise((s,o)=>{let i,a=()=>e.removeEventListener("abort",c),c=()=>{i!==void 0&&clearTimeout(i),a(),o(Ie())};if(e.aborted){c();return}i=setTimeout(()=>{a(),s()},r),e.addEventListener("abort",c,{once:!0})})}var Pe="flopay_session_display:";var U=new Map;function q(n){return`${Pe}${n}`}function G(){if(typeof window>"u")return null;try{return window.sessionStorage}catch{return null}}function $(n,e,t){if(!n)return;let r=t?.ttlMs??36e5,s={data:e,expiresAt:Date.now()+r},o=G();if(o)try{o.setItem(q(n),JSON.stringify(s));return}catch{}U.set(n,s)}function te(n){if(!n)return null;let e=G();if(e)try{let r=e.getItem(q(n));if(r){let s=JSON.parse(r);if(s&&typeof s.expiresAt=="number"&&s.expiresAt>Date.now())return s.data;e.removeItem(q(n))}}catch{}let t=U.get(n);if(t){if(t.expiresAt>Date.now())return t.data;U.delete(n)}return null}function re(n){if(!n)return;U.delete(n);let e=G();if(e)try{e.removeItem(q(n))}catch{}}var T=require("@flopay/shared"),De="/v1/sdk-telemetry/events",Y=16,Oe=64,xe=1500,ne=1e3,Fe=64,Ue="00000000-0000-4000-8000-000000000000",qe={technical_error:8,lifecycle:32,expected_outcome:32,performance:24};function I(){try{return globalThis.crypto.randomUUID()}catch{let n=new Uint8Array(16);try{globalThis.crypto.getRandomValues(n)}catch{for(let t=0;t<n.length;t+=1)n[t]=Math.floor(Math.random()*256)}n[6]=(n[6]??0)&15|64,n[8]=(n[8]??0)&63|128;let e=[...n].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 Le(n){try{return new TextEncoder().encode(n).byteLength}catch{return n.length}}function Ne(n){return JSON.stringify([n.code,n.failureCategory,n.reason,n.stage,n.provider,n.attempt,n.statusClass,n.requestCategory,n.paymentMethodCategory,n.walletType,n.operationOutcome,n.checkoutMode,n.layout,n.inAppBrowser,n.appFamily,n.popupCapability,n.presentationMode,n.terminalReason])}function _(){return globalThis.performance?.now()??0}var A=class{constructor(e){this.ingestionDisabled=!1;this.queue=[];this.sequence=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(/\/+$/,"")}${De}`,this.sdkPackage=e.sdkPackage??"@flopay/js",this.sdkVersion=e.sdkVersion,this.correlationId=I(),this.merchantEnabled=e.enabled!==!1,this.clock=e.clock??_,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,T.buildTelemetryLogEvent)({...this.checkoutContext,...e,eventId:I(),sequence:this.sequence++}))}error(e){if(this.notify({...e,class:"technical_error"}),!this.canCollect())return;let t=(0,T.buildTelemetryErrorEvent)({...this.checkoutContext,...e,eventId:Ue,sequence:0}),r=Ne(t),s=this.now();this.pruneReportedFailures(s);let o=this.reportedFailures.get(r);if(o!==void 0&&s>=o&&s-o<ne){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(r,s),this.enqueue((0,T.buildTelemetryErrorEvent)({...this.checkoutContext,...e,eventId:I(),sequence:this.sequence++}))}performance(e){this.canCollect()&&this.enqueue((0,T.buildTelemetryPerformanceEvent)({...this.checkoutContext,...e,eventId:I(),sequence:this.sequence++}))}terminal(e){if(this.canCollect()&&(this.enqueue((0,T.buildTelemetryTerminalEvent)({...this.checkoutContext,...e,eventId:I(),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"})}}now(){try{return this.clock()}catch{return _()}}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,r]of this.reportedFailures)(e<r||e-r>=ne)&&this.reportedFailures.delete(t)}rememberReportedFailure(e,t){for(;this.reportedFailures.size>=Fe;){let r=this.reportedFailures.keys().next();if(r.done)break;this.reportedFailures.delete(r.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.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>=Oe||this.eventCounts[e.class]>=qe[e.class])){if(this.eventCounts[e.class]+=1,this.queue.push(e),this.queue.length>=Y){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,Y);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,Y);this.sendBatch(e)}}async sendBatch(e){if(!this.browserTransportAvailable||this.ingestionDisabled)return;let t=(0,T.serializeTelemetryBatch)(e,{correlationId:this.correlationId,sdkPackage:this.sdkPackage,sdkVersion:this.sdkVersion,batchId:I()});if(Le(t)>T.TELEMETRY_MAX_BATCH_BYTES)return;let r=typeof AbortController>"u"?null:new AbortController,s=null;try{let o=fetch(this.endpoint,{method:"POST",headers:{"content-type":"text/plain;charset=UTF-8"},body:t,credentials:"omit",keepalive:!0,referrerPolicy:"no-referrer",signal:r?.signal}).then(async c=>{if(c.status!==202)return null;let l=null;try{l=await c.json()}catch{}return l?.status==="disabled"?"disabled":null}).catch(()=>null),i=new Promise(c=>{s=setTimeout(()=>{r?.abort(),c(null)},xe)});await Promise.race([o,i])==="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)}},se=Symbol.for("@flopay/js.telemetry.reporter-factory.v1"),oe=globalThis;oe[se]===void 0&&Object.defineProperty(oe,se,{configurable:!0,enumerable:!1,writable:!1,value:n=>new A(n)});function Ve(n){return n==="on_session"||n==="off_session"}function ze(n){if(!n||typeof n!="object")return!1;let e=n;return typeof e.paymentMethodType=="string"&&typeof e.reason=="string"}var He="x-flopay-process-result-source",Be="status";function ie(n){return n?.result==="DECLINE"||n?.result==="ERROR"}var je=50,E=new Map;function Ke(n,e){return E.get(n)?.has(e)===!0}function Ge(n,e){let t=E.get(n)??new Set;if(t.add(e),E.delete(n),E.set(n,t),E.size>je){let r=E.keys().next().value;r!==void 0&&E.delete(r)}}function $e(n){let e=n?.threeDSecureActionResultTokenId;if(typeof e=="string"&&e.length>0)return e;if(n?.gateway==="paypal"&&n.type!=="paypal_setup_token"&&typeof n.id=="string"&&n.id.length>0)return n.id}var ae=0,ue=500,L=15e3,ce=15e3,Ye=3e3,We=1e4,Je=1e4;function pe(n){return typeof n=="object"&&n!==null}function P(n,e){return Z(n?.[e])}function le(n,e){return ee(n?.[e])}function Qe(n,e){let t=n?.[e];return typeof t=="number"&&Number.isFinite(t)?t:void 0}function J(n,e){return e?new Promise((t,r)=>{let s=()=>{clearTimeout(o),r(e.reason??Object.assign(new Error("The operation was aborted."),{name:"AbortError"}))},o=setTimeout(()=>{e.removeEventListener("abort",s),t()},n);e.aborted?s():e.addEventListener("abort",s,{once:!0})}):new Promise(t=>setTimeout(t,n))}function W(n){return n instanceof Error&&n.name==="AbortError"}function b(){return new u.FloPayError(u.CHECKOUT_PROCESSING_TIMEOUT_MESSAGE,"api_error",{code:"checkout_processing_timeout"})}async function k(n,e){let t=await n.json().catch(()=>null),r=pe(t?.error)?t.error:null,s=le(t,"message")??le(r,"message")??e,o=P(t,"code")??P(t,"gatewayErrorCode")??P(r,"code")??`http_${n.status}`;return new u.FloPayError(s,"api_error",{code:o,statusCode:n.status})}async function Xe(n){let e=n.status===400?await n.clone().json().catch(()=>null):null;return(0,u.classifyPaymentRejection)(n.status,e)}function de(n){return n===400||n===422}var V=2;async function N(n,e,t=V,r,s){let o;for(let i=0;;i++)try{return s?.(i),await fetch(n,e)}catch(a){if(e?.signal?.aborted||a instanceof Error&&a.name==="AbortError")throw a;if(o=a,i>=t)throw o;try{r?.(i+1)}catch{}await J(150*2**i,e?.signal??void 0)}}var Ze=Symbol.for("@flopay/js.session-create.telemetry.v1");function et(n){return n[Ze]}function tt(n){return"now"in n||"onFirstByte"in n||"onSessionCreateFailure"in n||"onRetry"in n}function he(n){let e=(0,u.isCardHolderNamePlaceholder)(n.firstName,n.lastName);return{userId:n.userId,firstName:e?null:n.firstName??null,lastName:e?null:n.lastName??null,email:n.email,country:n.country??null,gender:n.gender??null,city:n.city??null,state:n.state??null,zip:n.zip??null,addressLine1:n.addressLine1??null,addressLine2:n.addressLine2??null}}function ye(n,e){e.checkoutMetadata!==void 0&&(n.checkoutMetadata=e.checkoutMetadata),e.tagsData&&(n.tagsData=e.tagsData),e.utmMetadata&&e.utmMetadata.length>0&&(n.utmMetadata=e.utmMetadata),e.avsCheck!==void 0&&(n.avsCheck=e.avsCheck),e.checkoutType&&(n.checkoutType=e.checkoutType),e.checkoutLayout&&(n.checkoutLayout=e.checkoutLayout),e.avsConfig&&(n.avsConfig=e.avsConfig)}function rt(n,e){let t={clientId:n.clientId,checkoutVersion:u.SDK_VERSION,successUrl:n.successUrl,cancelUrl:n.cancelUrl,currency:e,checkoutMode:"full",deferDataAttachment:!0};return n.captureMethod==="manual"&&(t.captureMethod=n.captureMethod),n.account.country&&(t.accountData={country:n.account.country}),ye(t,n),t}function me(n,e,t){return{currency:e,products:t.map(r=>(0,u.buildProductPayload)(r,e)),couponCodes:n.couponCodes??[],accountData:he(n.account)}}function nt(n,e,t){return{currency:e,products:t.map(r=>(0,u.buildProductPayload)(r,e)),couponCodes:n.couponCodes??[]}}function st(n){let e={},t=(0,u.isCardHolderNamePlaceholder)(n.firstName,n.lastName);for(let[r,s]of Object.entries(n)){if(t&&r.endsWith("Name")||typeof s!="string")continue;let o=s.trim();o&&(e[r]=o)}return{accountData:e}}var M=class M{constructor(e,t={}){this.baseUrl=e.replace(/\/+$/,"");let r=tt(t);this.telemetryHooks=r?t:void 0,this.directTelemetry=r||t.telemetry===!1?void 0:new A({billingApiUrl:this.baseUrl,sdkVersion:u.SDK_VERSION})}destroy(){this.directTelemetry?.destroy()}reportDirectFailure(e,t,r,s,o="unknown"){let i=(0,u.classifyTelemetryFailure)(e,t);this.directTelemetry?.error({...i,stage:r,requestCategory:s,paymentMethodCategory:o})}reportAccountSnapshotFailure(e,t){let r=(0,u.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED");if(t==="best_effort"&&r.errorCode==="REQUEST_TIMEOUT"){this.directTelemetry?.log({name:"operation.fallback",stage:"processing",requestCategory:"account_snapshot",statusClass:"timeout"});return}this.directTelemetry?.error({...r,stage:"processing",requestCategory:"account_snapshot",paymentMethodCategory:"unknown"})}telemetryTimestamp(){try{return this.telemetryHooks?.now?.()??this.directTelemetry?.now()??_()}catch{return _()}}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,r=!0,s){this.beginDirectTelemetryCheckout(e);let o=this.telemetryTimestamp(),i=o,a=0;this.directTelemetry?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let c={[u.FLO_SDK_VERSION_HEADER]:u.SDK_VERSION};t&&(c["x-checkout-session-token"]=t);try{let l=await N(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}`,{headers:c,signal:s},V,f=>{this.telemetryHooks?.onRetry?.("session_read",f),this.directTelemetry?.log({name:"operation.retry",stage:"session_read",requestCategory:"session_read",attempt:f})},f=>{a=f,i=this.telemetryTimestamp()}),m=Math.max(0,this.telemetryTimestamp()-i);try{this.telemetryHooks?.onFirstByte?.(m,a)}catch{}let d=`${Math.floor(l.status/100)}xx`;if(this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:d,attempt:a}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:m,durationMode:"machine",requestCategory:"session_read",statusClass:d,attempt:a}),!l.ok)throw await k(l,"Failed to get checkout session");let p=await l.json();return this.directTelemetry?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:d}),this.directTelemetry?.performance({stage:"session_complete",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"session_read",statusClass:d}),{...p,data:this.mergeCachedDisplayData(p.data)}}catch(l){throw r&&this.directTelemetry?.error({...(0,u.classifyTelemetryFailure)(l,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"}),l}}cacheSessionDisplayData(e,t,r){$(e,t,r)}clearSessionDisplayData(e){re(e)}async getVaultCapture(e,t){let r=`${this.baseUrl}\0${e}\0${t??""}`,s=M.activeVaultCaptureRequests.get(r);if(s)return s;let o=this.requestVaultCapture(e,t);M.activeVaultCaptureRequests.set(r,o);try{return await o}finally{M.activeVaultCaptureRequests.get(r)===o&&M.activeVaultCaptureRequests.delete(r)}}async requestVaultCapture(e,t){let r=new AbortController,s=setTimeout(()=>r.abort(),Je);this.beginDirectTelemetryCheckout(e);let o=this.telemetryTimestamp();this.directTelemetry?.log({name:"vault.capture.requested",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card"});let i={"Content-Type":"application/json"};t&&(i["x-checkout-session-token"]=t);try{let a=await N(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/vault/capture`,{method:"POST",headers:i,signal:r.signal},V,l=>{this.telemetryHooks?.onRetry?.("vault_capture",l),this.directTelemetry?.log({name:"operation.retry",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card",attempt:l})});if(!a.ok)throw await k(a,"Failed to load the secure card form");let c=await a.json();return this.directTelemetry?.performance({stage:"vault_request",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"2xx"}),this.toVaultBlock(c)}catch(a){let c=r.signal.aborted?new u.FloPayError("Timed out while loading the secure card form. Please try again.","api_error",{code:"vault_capture_timeout"}):a;throw this.reportDirectFailure(c,"VAULT_LOAD_FAILED","vault_request","vault_capture","card"),c}finally{clearTimeout(s)}}async getUnifiedCheckoutSession(e,t){let r=await this.getCheckoutSession(e,t);return this.normalizeCheckoutSessionResponse(r)}async getUnifiedCheckoutSessionForRecovery(e,t,r){let s=await this.fetchCheckoutSession(e,t,!1,r);return this.normalizeCheckoutSessionResponse(s)}normalizeCheckoutSessionResponse(e){let t=this.normalizeRawSession(e.data),r=e.vault;return r&&t.data.session&&(t.data.session.vault=this.toVaultBlock(r)),t}async processPayment(e,t,r){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 u.FloPayError("processPayment requires `nonce` \u2014 pass the value returned from session creation.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let o=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.processing.started",stage:"processing",requestCategory:"process_payment",paymentMethodCategory:s});let{nonce:i,paymentMethodCategory:a,...c}=t,l=$e(t.tokenizedData),m;try{m=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(t.sessionId)}/process`,{method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":i},body:JSON.stringify(c)})}catch(d){if(W(d))throw this.reportDirectFailure(d,"PAYMENT_PROCESSING_FAILED","processing","process_payment",s),d;m=await this.reconcileProcessPayment(t.sessionId,{...r,nonce:i,paymentMethodCategory:s,submittedIntentId:l})}if(!m.ok&&m.status!==202){let d=await Xe(m);return d?this.directTelemetry?.terminal({outcome:d,stage:"processing",requestCategory:"process_payment",statusClass:"4xx",paymentMethodCategory:s}):this.directTelemetry?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",requestCategory:"process_payment",statusClass:(0,u.telemetryStatusClass)(m.status),failureCategory:m.status>=500?"server_error":void 0,paymentMethodCategory:s}),m}try{let d=await this.resolveProcessResponse(m,t.sessionId,{...r,nonce:i,paymentMethodCategory:s,submittedIntentId:l});return this.directTelemetry?.log({name:"payment.processing.completed",stage:"processing",requestCategory:"process_payment",statusClass:(0,u.telemetryStatusClass)(d.status),paymentMethodCategory:s}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"process_payment",statusClass:(0,u.telemetryStatusClass)(d.status),paymentMethodCategory:s}),d}catch(d){throw d instanceof u.FloPayError&&d.code==="checkout_processing_timeout"||this.reportDirectFailure(d,"PAYMENT_PROCESSING_FAILED","processing","process_payment",s),d}}async patchAccountSnapshot(e,t,r,s){this.beginDirectTelemetryCheckout(e);let o=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.state_transition",stage:"processing",requestCategory:"account_snapshot"});let i=s?.timeoutMs??We,a=new AbortController,c=()=>a.abort();s?.signal&&(s.signal.aborted?a.abort():s.signal.addEventListener("abort",c,{once:!0}));let l=setTimeout(()=>a.abort(),i);try{let m;try{m=await N(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/account`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":t},body:JSON.stringify(r),signal:a.signal},V,d=>{this.telemetryHooks?.onRetry?.("account_snapshot",d),this.directTelemetry?.log({name:"operation.retry",stage:"processing",requestCategory:"account_snapshot",attempt:d})})}finally{clearTimeout(l),s?.signal?.removeEventListener("abort",c)}if(!m.ok)throw await k(m,"Failed to persist account snapshot");this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"account_snapshot",statusClass:"2xx"})}catch(m){throw this.reportAccountSnapshotFailure(m,s?.telemetryMode??"blocking"),m}}async createSessionIntent(e,t,r,s){if(!t)throw new u.FloPayError("createSessionIntent requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let o=r,i=o.paymentMethodType,a=typeof i=="string"&&i.trim().toLowerCase()==="card",c=typeof i=="string"&&i.length>0&&!a&&(typeof o.paymentMethodId=="string"||o.paymentMethodId===null),l=o.provider==="stripe"&&(o.paymentMethodCategory==="wallet"||o.paymentMethodCategory==="apm")&&(o.intentKind==="payment"||o.intentKind==="setup"),m=o.provider==="paypal"&&o.paymentMethodCategory==="wallet"&&o.paymentMethodId===null&&(o.paymentMethodType==="paypal"&&o.intentKind==="payment"||o.paymentMethodType===u.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&(o.intentKind==="payment"||o.intentKind==="setup"));if(!c||!l&&!m)throw new u.FloPayError("Only wallet, APM, and PayPal session intents are supported.","validation_error",{code:"InvalidSessionIntentRequest"});let d=o.authorizationAttemptId;if(d!==void 0&&!(0,u.isUuidV4)(d))throw new u.FloPayError("authorizationAttemptId must be a v4 UUID identifying one buyer authorization attempt.","validation_error",{code:"InvalidAuthorizationAttemptId",param:"authorizationAttemptId"});let p=(0,u.isUuidV4)(d)?d:(0,u.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,[u.IDEMPOTENCY_KEY_HEADER]:s?.idempotencyKey||p},C=!1;try{let y=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents`,{method:"POST",headers:h,body:JSON.stringify({...r,authorizationAttemptId:p}),signal:s?.signal});if(!y.ok){C=!0;let j=await k(y,"Failed to create checkout intent"),_e=(0,u.classifyTelemetryFailure)(j,"PAYMENT_PROCESSING_FAILED");throw de(j.statusCode)?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"intent_create",statusClass:"4xx"}):this.directTelemetry?.error({..._e,stage:"processing",requestCategory:"intent_create"}),j}let S=(await y.json()).data;if(!S||typeof S!="object")throw new u.FloPayError("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});let g=S,X=g.paymentMethodType,ve=(g.paymentMethodCategory==="wallet"||g.paymentMethodCategory==="apm")&&typeof X=="string"&&X.trim().toLowerCase()!=="card"&&(typeof g.paymentMethodId=="string"||g.paymentMethodId===null)&&typeof g.providerObjectId=="string",Te=g.provider==="stripe"&&(g.intentKind==="payment"||g.intentKind==="setup")&&typeof g.clientSecret=="string",be=g.provider==="paypal"&&g.paymentMethodCategory==="wallet"&&g.paymentMethodId===null&&(g.paymentMethodType==="paypal"&&g.intentKind==="payment"&&(g.providerObjectType==="order"||g.providerObjectType==="subscription")||g.paymentMethodType===u.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&g.intentKind==="payment"&&g.providerObjectType==="order"||g.paymentMethodType===u.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&g.intentKind==="setup"&&g.providerObjectType==="setup_token")&&g.clientSecret===null,Se=g.provider===r.provider&&g.paymentMethodCategory===r.paymentMethodCategory&&g.paymentMethodType===r.paymentMethodType&&g.paymentMethodId===r.paymentMethodId&&g.intentKind===r.intentKind;if(!ve||!Te&&!be||!Se)throw new u.FloPayError("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});return this.directTelemetry?.log({name:"payment.intent.completed",stage:"processing",requestCategory:"intent_create",statusClass:(0,u.telemetryStatusClass)(y.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-f),durationMode:"machine",requestCategory:"intent_create",statusClass:(0,u.telemetryStatusClass)(y.status)}),g}catch(y){throw C||this.reportDirectFailure(y,"PAYMENT_PROCESSING_FAILED","processing","intent_create"),y}}async reportSessionIntentDecline(e,t,r,s){if(!t)throw new u.FloPayError("reportSessionIntentDecline requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let o=r,i=o.providerDeclineReason,a=o.paymentMethodType,c=o.providerIntentId,l=typeof i=="string"&&/^[a-z0-9][a-z0-9_.:-]{0,63}$/i.test(i)&&!/^(?:pm|pi|seti|tok|src|cus|sess|sk|pk)_/i.test(i),m=typeof a=="string"&&a.length>0&&a.trim().toLowerCase()!=="card"&&l,d=o.provider==="stripe"&&(o.paymentMethodCategory==="wallet"||o.paymentMethodCategory==="apm")&&(c===void 0||typeof c=="string"&&/^pi_[a-z0-9_]{1,252}$/i.test(c)),p=o.provider==="paypal"&&o.paymentMethodCategory==="wallet"&&o.paymentMethodType==="paypal"&&c===void 0;if(!m||!d&&!p)throw new u.FloPayError("Invalid non-card decline classification.","validation_error",{code:"InvalidSessionIntentDeclineRequest"});let f=p?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:i}:{provider:"stripe",paymentMethodCategory:o.paymentMethodCategory,paymentMethodType:o.paymentMethodType,providerDeclineReason:i,...typeof c=="string"?{providerIntentId:c}:{}},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 k(h,"Failed to report checkout decline")}async getPaymentsByEmail(e,t){this.beginDirectTelemetryOperation();let r=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved"});let s=t?.page??1,o=t?.limit??1,i=new URLSearchParams({email:e,page:String(s),limit:String(o),sortField:"createdAt",sortDirection:"DESC"});try{let a=await fetch(`${this.baseUrl}/v1/payments?${i.toString()}`,{method:"GET",signal:t?.signal,keepalive:!0});if(!a.ok)throw new u.FloPayError("Failed to fetch payments","api_error",{statusCode:a.status});let c=await a.json();return this.directTelemetry?.log({name:"operation.recovery.completed",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),this.directTelemetry?.performance({stage:"recovery",durationMs:Math.max(0,this.telemetryTimestamp()-r),durationMode:"machine",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),c}catch(a){throw this.reportDirectFailure(a,"RECOVERY_FAILED","recovery","other","saved"),a}}async createAndFetchSession(e){if((0,u.isDetachedSessionEligible)(e)){let o=e.account.email?.trim();if(o&&!(0,u.isValidEmail)(o))throw new u.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(),r=w(e.timeoutMs??12e3),s={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});try{let o=await this.createAndFetchSessionRequest(e,r.signal,s);return this.adoptDirectTelemetryCheckout(o.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}),o}catch(o){throw this.reportSessionCreateFailure(o,t,s),o}finally{r.clear()}}async createAndFetchSessionRequest(e,t,r){let s=e.products??(0,u.foldIntoProducts)(e.items,e.subscriptions);(0,u.assertCaptureMethodEligible)({captureMethod:e.captureMethod,products:s});let o=(0,u.resolveSessionCurrency)(e.currency,e.items,e.subscriptions,s);if(!o)throw new u.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 i={clientId:e.clientId,checkoutVersion:u.SDK_VERSION,successUrl:e.successUrl,cancelUrl:e.cancelUrl,currency:o,checkoutMode:e.checkoutMode??"full",products:s.map(d=>(0,u.buildProductPayload)(d,o)),accountData:he(e.account),couponCodes:e.couponCodes??[]};e.captureMethod==="manual"&&(i.captureMethod=e.captureMethod),e.tokenizedData&&(i.tokenizedData=e.tokenizedData),ye(i,e);let c=await(await this.postCheckoutSessionCreate(i,e,t,r)).json();if(c.data&&"gateways"in c.data){this.autoCacheDisplayData(c.data.uuid,e);let d=this.mergeCachedDisplayData(c.data),p=this.normalizeRawSession(d);return c.vault&&p.data.session&&(p.data.session.vault=this.toVaultBlock(c.vault)),{...p,autoProcessingError:c.autoProcessingError,autoProcessingAttempted:c.autoProcessingAttempted,autoProcessingPending:c.autoProcessingPending}}let l=c.data?.uuid;if(!l)throw new u.FloPayError("No session ID returned","api_error",{code:"InvalidCheckoutSessionResponse"});return this.autoCacheDisplayData(l,e),this.adoptDirectTelemetryCheckout(l),{...await this.getUnifiedCheckoutSession(l),autoProcessingError:c.autoProcessingError,autoProcessingAttempted:c.autoProcessingAttempted,autoProcessingPending:c.autoProcessingPending}}async postCheckoutSessionCreate(e,t,r,s){let o={"Content-Type":"application/json",[u.FLO_SDK_VERSION_HEADER]:u.SDK_VERSION},i=(0,u.resolveIdempotencyKey)(t.idempotencyKey);i&&(o[u.IDEMPOTENCY_KEY_HEADER]=i),t.checkoutMode==="auto"&&(o[u.FLO_SDK_CAPABILITIES_HEADER]=u.ASYNC_AUTO_CHECKOUT_CAPABILITY);let a,c=!1,l=et(t),m=(p,f,h)=>{c||(c=!0,this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:h,attempt:p}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:Math.max(0,this.telemetryTimestamp()-f),durationMode:"machine",requestCategory:"session_create",statusClass:h,attempt:p}))},d=p=>{try{this.telemetryHooks?.onRetry?.("session_create",p),this.directTelemetry?.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:p})}catch{}};for(let p=0;p<3;p++){s.attempt=p;let f=this.telemetryTimestamp();try{l?.onAttempt?.(p)}catch{}try{a=await fetch(`${this.baseUrl}/v1/checkouts/sessions?expand=true`,{method:"POST",headers:o,body:JSON.stringify(e),signal:r})}catch(y){if(s.statusClass=r.aborted||y instanceof Error&&y.name==="AbortError"?"timeout":"network_error",r.aborted||y instanceof Error&&y.name==="AbortError"||p>=2)throw y;let R=p+1;d(R),await F(p,r);continue}let h=(0,u.telemetryStatusClass)(a.status);if(s.statusClass=h,a.status===204)throw m(p,f,h),new u.FloPayError("Session auto-completed \u2014 payment method already on file","api_error",{code:"session_auto_completed"});if(a.ok){m(p,f,h);break}let C=await k(a,"Failed to create checkout session");if(C.code===u.IDEMPOTENCY_IN_PROGRESS_CODE&&p<2){d(p+1),await F(p,r);continue}throw m(p,f,h),C}if(!a)throw new TypeError("Checkout-session creation exhausted its retry budget.");return a}async createDetachedSession(e){this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp(),r=w(e.timeoutMs??12e3),s={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let o=e.products??(0,u.foldIntoProducts)(e.items,e.subscriptions);try{(0,u.assertCaptureMethodEligible)({captureMethod:e.captureMethod,products:o})}catch(y){throw r.clear(),this.reportSessionCreateFailure(y,t,s),y}let i=(0,u.resolveSessionCurrency)(e.currency,e.items,e.subscriptions,o);if(!i)throw r.clear(),this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),new u.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{me(e,i,o)}catch(y){throw r.clear(),this.reportSessionCreateFailure(y,t,s),y}let a,c;try{if(c=await(await this.postCheckoutSessionCreate(rt(e,i),e,r.signal,s)).json(),!c.data||!("gateways"in c.data))throw new u.FloPayError("The billing API returned no session shell for a detached create. It must support `deferDataAttachment` (TeamFloPay/backend#1099).","api_error",{code:"InvalidCheckoutSessionResponse"});a=this.normalizeRawSession(this.mergeCachedDisplayData(c.data)),c.vault&&a.data.session&&(a.data.session.vault=this.toVaultBlock(c.vault))}catch(y){throw r.clear(),this.reportSessionCreateFailure(y,t,s),y}let l=a.data.session?.id??c.data.uuid??"",m=a.data.session?.clientSecret??c.data.nonce??"";if(!l||!m){r.clear();let y=new u.FloPayError("Checkout session shell was created without a session id or nonce.","api_error",{code:"InvalidCheckoutSessionResponse"});throw this.reportSessionCreateFailure(y,t,s),y}r.clear(),this.adoptDirectTelemetryCheckout(l),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 d=!e.account.email?.trim(),p=w(e.timeoutMs??12e3),f=this.claimCheckoutSession(l,m,d?nt(e,i,o):me(e,i,o),{params:e,startedAt:t,deadline:p,createAttempt:s.attempt}),h=d?void 0:f,C=(y={})=>{if(h!==void 0)return h;let R={...e,account:{...e.account,...y,email:y.email?.trim()||e.account.email?.trim()}};return(0,u.isValidEmail)(R.account.email)?(h=f.then(()=>{let S=this.telemetryTimestamp();return this.claimCheckoutSession(l,m,st(R.account),{params:R,startedAt:S,deadline:w(e.timeoutMs??12e3),createAttempt:0})}),h.catch(()=>{}),h):Promise.reject(new u.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}))};return f.catch(()=>{}),{shell:a,sessionId:l,nonce:m,claimed:f,claim:C}}async claimCheckoutSession(e,t,r,s){let o=s?.startedAt??this.telemetryTimestamp(),i=this.telemetryTimestamp(),a=s?.deadline??w(12e3),c=JSON.stringify(r),l="unknown",m=0;this.directTelemetry?.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"});try{let d;for(m=0;m<3;m++){try{d=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/claim`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":t,[u.FLO_SDK_VERSION_HEADER]:u.SDK_VERSION},body:c,signal:a.signal})}catch(h){let C=a.signal.aborted||h instanceof Error&&h.name==="AbortError";if(l=C?"timeout":"network_error",C||m>=2)throw h;try{this.telemetryHooks?.onRetry?.("session_claim",m+1),this.directTelemetry?.log({name:"operation.retry",stage:"session_claim",requestCategory:"session_claim",attempt:m+1})}catch{}await F(m,a.signal);continue}if(l=(0,u.telemetryStatusClass)(d.status),d.ok)break;throw await k(d,"Failed to attach checkout session data")}if(!d)throw new TypeError("Checkout-session claim exhausted its retry budget.");let p=await d.json();if(!p.data?.gateways)throw new u.FloPayError("The billing API returned no checkout session with gateways after claiming it.","api_error",{code:"InvalidCheckoutSessionResponse"});s?.params&&this.autoCacheDisplayData(p.data.uuid??e,s.params);let f=this.normalizeRawSession(this.mergeCachedDisplayData(p.data));return p.vault&&f.data.session&&(f.data.session.vault=this.toVaultBlock(p.vault)),this.directTelemetry?.log({name:"session.claim.completed",stage:"session_claim",requestCategory:"session_claim",statusClass:l}),this.directTelemetry?.performance({stage:"session_claim",durationMs:Math.max(0,this.telemetryTimestamp()-i),durationMode:"machine",requestCategory:"session_claim",statusClass:l,attempt:m}),this.directTelemetry?.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:l}),this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"session_create",statusClass:l,attempt:s?.createAttempt??m}),f}catch(d){throw this.reportSessionCreateFailure(d,i,{attempt:m,statusClass:l},"session_claim"),d}finally{a.clear()}}reportSessionCreateFailure(e,t,r,s="session_create"){if(!(e instanceof u.FloPayError&&e.code==="session_auto_completed"))try{this.telemetryHooks?.onSessionCreateFailure?.(e)}catch{}let o=(0,u.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:o.statusClass,attempt:r.attempt}),e instanceof u.FloPayError&&e.type==="validation_error"||e instanceof u.FloPayError&&de(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 u.FloPayError&&e.code==="session_auto_completed"||this.directTelemetry?.error({...o,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"})}async waitForCheckoutSessionCompletion(e,t){this.beginDirectTelemetryCheckout(e);let r=this.telemetryTimestamp(),s=t?.paymentMethodCategory??"saved";this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:s});let o=t?.timeoutMs??L,i=Date.now()+o,a=new AbortController,c=!1,l,m=setTimeout(()=>{l=setTimeout(()=>{c=!0,a.abort()},ce)},o),d=()=>a.abort(t?.signal?.reason);t?.signal?.aborted?d():t?.signal?.addEventListener("abort",d,{once:!0});let p=this.clampRetryAfterMs(t?.initialDelayMs??ae),f=0;try{if(t?.statusUrl){let h=await this.waitForCheckoutStatus(e,{initialDelayMs:p,timeoutMs:o,nonce:t.nonce,statusUrl:t.statusUrl,pollAfterAction:t.continueAfterActionRequired,signal:a.signal});if(h){let C=await this.resolveCheckoutSessionStatus(e,h,t.nonce,a.signal,()=>c);return this.reportRecoveryCompleted(r,s),C}}for(;;){let h=i-Date.now();if(h<=0)throw b();if(p>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 J(Math.min(p,h),a.signal),Date.now()>=i)throw b()}let C=await this.getUnifiedCheckoutSessionForRecovery(e,t?.nonce,a.signal),y=C.data.session?.status;if(y==="authorized"||y==="complete"||y==="expired")return this.reportRecoveryCompleted(r,s),C;if(Date.now()>=i)throw b();p=this.clampRetryAfterMs(Math.max(p*2,ue))}}catch(h){let C=c&&W(h)?b():h;throw this.reportDirectFailure(C,"RECOVERY_FAILED","recovery","session_read",s),C}finally{clearTimeout(m),clearTimeout(l),t?.signal?.removeEventListener("abort",d)}}reportRecoveryCompleted(e,t){let r={stage:"recovery",requestCategory:"session_read",paymentMethodCategory:t};this.directTelemetry?.log({name:"operation.recovery.completed",...r}),this.directTelemetry?.performance({...r,durationMs:Math.max(0,this.telemetryTimestamp()-e),durationMode:"machine"})}async resolveCheckoutSessionStatus(e,t,r,s,o){let i=t.latestTransactionAttempt;if(this.rememberReportedFailure(e,t),i?.result==="DECLINE"){let l=i.code===u.STORED_PAYMENT_METHOD_UNSUPPORTED_CODE;throw new u.FloPayError(l?u.STORED_PAYMENT_METHOD_UNSUPPORTED_MESSAGE:"Payment was declined. Please choose another payment method.","api_error",{code:i.code??i.declineReason??"authorization_declined",statusCode:400})}if(i?.result==="ERROR"||t.status==="voided")throw new u.FloPayError("Payment could not be completed. Please try again.","api_error",{code:i?.code??"payment_processing_error",statusCode:500});let a;try{a=await this.getUnifiedCheckoutSessionForRecovery(e,r,s)}catch(l){if(!o?.()||!W(l))throw l;a={providers:[],mode:"tokenize",data:{},raw:t}}let c=a.data.session;return c&&i?.result==="SUCCESS"?{...a,data:{...a.data,session:{...c,status:"complete"}}}:c&&i?.result==="AUTHORIZED"?{...a,data:{...a.data,session:{...c,status:"authorized",paymentId:t.paymentId??void 0,authorizationExpiresAt:t.authorizationExpiresAt??void 0}}}:c&&t.status==="completed"?{...a,data:{...a.data,session:{...c,status:"complete"}}}:c&&t.status==="authorized"?{...a,data:{...a.data,session:{...c,status:"authorized",paymentId:t.paymentId??void 0,authorizationExpiresAt:t.authorizationExpiresAt??void 0}}}:c&&t.status==="expired"?{...a,data:{...a.data,session:{...c,status:"expired"}}}:i?.result!=="ACTION_REQUIRED"?a:i.gateway==="paypal"&&i.providerIntentId?{...a,autoProcessingError:{type:"paypal_direct_required",message:"PayPal authorization required",orderId:i.providerIntentId,checkoutMethod:"paypal"}}:i.nextActionRedirectUrl?{...a,autoProcessingError:{type:"3ds_required",message:"Additional authentication is required.",nextActionRedirectUrl:i.nextActionRedirectUrl}}:a}async waitForCheckoutStatus(e,t){let r=t.timeoutMs??L,s=Date.now()+r,o=this.clampRetryAfterMs(t.initialDelayMs);for(;;){let i=s-Date.now();if(i<=0||o>0&&(await J(Math.min(o,i),t.signal),Date.now()>=s))throw b();let a=s-Date.now();if(a<=0)throw b();let c=new AbortController,l,m=t.signal?new Promise((S,g)=>{l=g}):null,d=()=>{c.abort(t.signal?.reason),l?.(t.signal?.reason??Object.assign(new Error("The operation was aborted."),{name:"AbortError"}))};t.signal?.aborted?d():t.signal?.addEventListener("abort",d,{once:!0});let p,f=t.signal?null:new Promise((S,g)=>{p=setTimeout(()=>{g(b()),c.abort()},a+ce)}),h;try{let S=this.fetchCheckoutStatus(e,t.nonce,t.statusUrl,c.signal);h=await Promise.race([S,f,m].filter(g=>g!==null))}finally{p!==void 0&&clearTimeout(p),t.signal?.removeEventListener("abort",d)}if(!h)return null;let C=ie(h.latestTransactionAttempt)&&!this.isOwnFailedAttempt(e,h,t.submittedIntentId);if(h.status==="completed"||h.status==="authorized"||h.status==="expired"||h.status==="voided")return C?{...h,latestTransactionAttempt:null}:h;let y=h.latestTransactionAttempt?.result,R=t.pollAfterAction===!0&&y==="ACTION_REQUIRED";if(!C&&y!==void 0&&y!=="PENDING"&&!R)return h;o=this.clampRetryAfterMs(Math.max(o*2,ue))}}isOwnFailedAttempt(e,t,r){let s=t.latestTransactionAttempt?.providerIntentId??null;return r!==void 0?s===r:s===null?!0:!Ke(t.uuid||e,s)}rememberReportedFailure(e,t){let r=t.latestTransactionAttempt;!ie(r)||!r.providerIntentId||Ge(t.uuid||e,r.providerIntentId)}async fetchCheckoutStatus(e,t,r,s){let o=`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/status`,i=o;if(r)try{let m=new URL(r,`${this.baseUrl}/`),d=new URL(o);m.origin===d.origin&&(i=m.toString())}catch{}let a={[u.FLO_SDK_VERSION_HEADER]:u.SDK_VERSION};t&&(a["x-checkout-session-token"]=t);let c=await N(i,{headers:a,signal:s});if(c.status===404||c.status===405)return null;if(!c.ok)throw await k(c,"Failed to get checkout session status");let l=await c.json();return pe(l.data)&&"latestTransactionAttempt"in l.data?l.data:null}normalizeRawSession(e){let t=e.gateways??{},r=[],s={session:this.toCheckoutSession(e)},o=t.stripe;if(o?.publishableKey){r.push("stripe");let c=[e.stripeClientSecret,o.stripeClientSecret].find(l=>typeof l=="string"&&l.length>0);s.stripe={clientSecret:c??"",publishableKey:o.publishableKey??void 0,paypalPublishableKey:o.paypalPublishableKey??void 0,environment:o.environment,enabledPaymentMethods:Array.isArray(o.enabledPaymentMethods)?o.enabledPaymentMethods.filter(l=>typeof l=="string"):void 0}}let i=t.paypal;return i?.publishableKey&&(r.push("paypal"),s.paypal={publishableKey:i.publishableKey,environment:i.environment,providerObjectType:i.providerObjectType,approvalPresentation:i.approvalPresentation}),{providers:r,mode:"tokenize",...e.checkoutMetadata===void 0?{}:{checkoutMetadata:e.checkoutMetadata},data:s,raw:{data:e}}}toCheckoutSession(e){let t=e.products??[],r=typeof e.totalAmount=="number"&&Number.isFinite(e.totalAmount),s=t.reduce((l,m)=>l+(m.overrideAmount??m.totalAmount??0),0),o=r?e.totalAmount:s,i=Math.round(o*100),a=e.currency??t[0]?.currency??"USD",c="payment";return e.checkoutMode==="setup"?c="setup":t.some(l=>l.type==="subscription")&&(c="subscription"),{id:e.uuid,clientSecret:e.nonce,mode:c,status:this.toCheckoutSessionStatus(e.status),amount:i,currency:a,captureMethod:e.captureMethod,paymentId:e.paymentId,authorizationExpiresAt:e.authorizationExpiresAt,failureOutcome:(0,u.normalizeCheckoutFailureOutcome)(e.outcome)??(0,u.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}:{},...Ve(e.futureUse)?{futureUse:e.futureUse}:{},...Array.isArray(e.futureUseUnsupported)?{futureUseUnsupported:e.futureUseUnsupported.filter(ze)}:{},buyerIdentified:e.buyerIdentified,providerPaymentMethodId:typeof e.providerPaymentMethodId=="string"?e.providerPaymentMethodId:null,products:t.map(l=>({...l,totalAmount:typeof l.totalAmount=="number"?l.totalAmount:void 0,overrideAmount:typeof l.overrideAmount=="number"?l.overrideAmount:null,currency:typeof l.currency=="string"?l.currency:void 0,metadata:l.metadata??null})),successUrl:e.successUrl,cancelUrl:e.cancelUrl,coupons:e.coupons,subtotalAmount:e.subtotalAmount,discountAmount:e.discountAmount,totalAmount:e.totalAmount,createdAt:e.createdAt,gateways:e.gateways,accountData:e.accountData,tagsData:e.tagsData}}toVaultBlock(e){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}}toCheckoutSessionStatus(e){return e==="completed"?"complete":e==="authorized"?"authorized":e==="expired"?"expired":"open"}async resolveProcessResponse(e,t,r){if(e.status!==202)return e;let s=await e.json().catch(()=>null),o=this.toCheckoutProcessingPending(s,e,t),i=r?.pollTimeoutMs??L,a=Date.now()+i;if(o.statusUrl){let l=await this.waitForCheckoutStatus(o.sessionId,{initialDelayMs:o.retryAfterMs,timeoutMs:i,nonce:r?.nonce,statusUrl:o.statusUrl,submittedIntentId:r?.submittedIntentId});if(l)return this.toProcessResponseFromStatus(l,t,r?.nonce)}let c=await this.waitForCheckoutSessionCompletion(o.sessionId,{initialDelayMs:o.retryAfterMs,timeoutMs:a-Date.now(),nonce:r?.nonce,paymentMethodCategory:r?.paymentMethodCategory});return this.toProcessResponseFromSession(c,t)}async toProcessResponseFromStatus(e,t,r){let s=e.latestTransactionAttempt?.result,o={[He]:Be},i={"Content-Type":"application/json",...o};if(e.status==="completed"||s==="SUCCESS")return new Response(null,{status:204,statusText:"No Content",headers:o});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:i});if(e.status==="expired"){let a=await this.resolveCheckoutSessionStatus(t,e,r);return this.toProcessResponseFromSession(a,t)}if(this.rememberReportedFailure(t,e),s==="DECLINE"){let a=e.latestTransactionAttempt,c=a?.code===u.STORED_PAYMENT_METHOD_UNSUPPORTED_CODE,l=a?.declineReason??void 0;return new Response(JSON.stringify({type:l??"authorization_declined",message:c?u.STORED_PAYMENT_METHOD_UNSUPPORTED_MESSAGE:"Payment was declined. Please choose another payment method.",code:a?.code??l??"authorization_declined",...l?{declineCode:l}:{}}),{status:400,headers:i})}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:i});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:i});if(s==="ERROR"||e.status==="voided")return new Response(JSON.stringify({type:"unknown",code:e.latestTransactionAttempt?.code??"payment_processing_error",message:"Payment could not be completed. Please try again."}),{status:500,headers:i});throw b()}async reconcileProcessPayment(e,t){let r=t?.pollTimeoutMs??L,s=Date.now()+r,o=null;try{o=await this.waitForCheckoutStatus(e,{initialDelayMs:0,timeoutMs:r,nonce:t?.nonce,submittedIntentId:t?.submittedIntentId})}catch(c){if(this.reportDirectFailure(c,"RECOVERY_FAILED","recovery","session_read",t?.paymentMethodCategory??"saved"),c instanceof u.FloPayError&&c.code==="checkout_processing_timeout")throw c}if(o)return this.toProcessResponseFromStatus(o,e,t?.nonce);let i=s-Date.now();if(i<=0)throw b();let a=await this.waitForCheckoutSessionCompletion(e,{initialDelayMs:0,timeoutMs:i,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 r=e.data.session;return new Response(JSON.stringify({status:"authorized",paymentId:r.paymentId,sessionId:r.id||t,authorizationExpiresAt:r.authorizationExpiresAt}),{status:200,headers:{"Content-Type":"application/json"}})}if(e.data.session?.status==="expired"){let r=e.data.session.failureOutcome==="authorization_expired"||e.data.session.captureMethod==="manual";throw new u.FloPayError(r?"Authorization has expired.":"Checkout session has expired.","api_error",{code:r?"authorization_expired":"checkout_session_expired"})}throw b()}toCheckoutProcessingPending(e,t,r){let s=t.headers.get("Retry-After"),o=s===null||s.trim()===""?void 0:Number(s),i=o!==void 0&&Number.isFinite(o)?o*1e3:void 0;return{type:"checkout_processing",sessionId:P(e,"sessionId")??r,retryAfterMs:this.clampRetryAfterMs(Qe(e,"retryAfterMs")??i??ae),statusUrl:P(e,"statusUrl"),sessionUrl:P(e,"sessionUrl")}}clampRetryAfterMs(e){return Math.max(0,Math.min(e,Ye))}autoCacheDisplayData(e,t){if(!e)return;let r=t.products??(0,u.foldIntoProducts)(t.items,t.subscriptions);if(r.length===0&&!t.currency)return;let s=t.products!==void 0,o=(0,u.resolveSessionCurrency)(t.currency,s?void 0:t.items,s?void 0:t.subscriptions,r);$(e,{currency:o??void 0,products:r.map(i=>({code:i.code??i.providerItemId??i.providerPlanId,type:i.type,name:i.name??i.itemName??i.providerItemName??i.subscriptionName??i.providerPlanName??null,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency??o??void 0}))})}mergeCachedDisplayData(e){let t=te(e.uuid),r=new Map,s=i=>i?`code:${i}`:void 0;for(let i of t?.products??[]){let a=s(i.code);a&&r.set(a,i)}let o=(e.products??[]).map(i=>{let a=s(i.code),c=a?r.get(a):void 0;return{...i,name:i.name??c?.name??null,totalAmount:i.totalAmount??c?.totalAmount,overrideAmount:i.overrideAmount??c?.overrideAmount,currency:i.currency??c?.currency}});return{...e,currency:e.currency??t?.currency,products:o}}};M.activeVaultCaptureRequests=new Map;var z=M;var v=require("@flopay/shared");var Q="flopay-vault",ot=3e4,it=v.THREE_DS_CHALLENGE_WINDOW_MS+ot,at="Card authentication timed out.",ge={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 ut(n){return n.class==="lifecycle"?n.name:n.class==="technical_error"?n.code:n.class==="expected_outcome"?n.outcome:"sdk.performance"}function x(n){let e={class:n.class,stage:n.stage};"code"in n&&(e.code=n.code),"provider"in n&&n.provider&&(e.provider=n.provider),"paymentMethodCategory"in n&&n.paymentMethodCategory&&(e.paymentMethodCategory=n.paymentMethodCategory),"outcome"in n&&(e.outcome=n.outcome),"durationMs"in n&&n.durationMs!==void 0&&(e.durationMs=n.durationMs),"durationMode"in n&&n.durationMode&&(e.durationMode=n.durationMode);try{globalThis.Sentry?.addBreadcrumb?.({category:"flopay.telemetry",level:n.class==="technical_error"?"error":"info",message:ut(n),data:e})}catch{}}function H(n,e){return(0,v.buildTelemetryLogEvent)({eventId:"11111111-1111-4111-8111-111111111111",name:n,stage:e,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}var ct=new Set(["authorization_declined","authentication_required","authorization_expired","capture_failed"]);function lt(n){return typeof n=="string"&&ct.has(n)?n:"unknown"}function fe(n,e){return n?{errorCode:"VAULT_SUBMIT_FAILED",stage:"vault_submit",failureCategory:"provider_runtime",reason:lt(e.failureOutcome)}:{errorCode:"VAULT_LOAD_FAILED",stage:"vault_mount",failureCategory:"provider_runtime"}}function Ce(n,e,t="checkout"){return t==="card_setup"?n.type==="decline"?"card_setup_declined":"card_setup_succeeded":n.type==="decline"?"payment_declined":n.outcome==="authorized"||e==="manual"?"payment_authorized":"payment_succeeded"}function dt(n,e,t,r="checkout"){let{type:s}=n;if(s==="complete"||s==="decline")return(0,v.buildTelemetryTerminalEvent)({eventId:"22222222-2222-4222-8222-222222222222",outcome:Ce(n,t,r),sequence:0,provider:"pcivault",paymentMethodCategory:"card"});if(s==="error"){let a=fe(e,n);return(0,v.buildTelemetryErrorEvent)({eventId:"33333333-3333-4333-8333-333333333333",...a,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}let[o,i]=ge[s];return H(o,i)}function mt(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===Q&&(e.type==="ready"||e.type==="submitting"||e.type==="blocked"||e.type==="complete"||e.type==="decline"||e.type==="error"||e.type==="action_required")}function pt(n){if(typeof n!="object"||n===null)return;let e=n,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 ht(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===Q&&e.type==="validation"&&Array.isArray(e.messages)}function yt(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===Q&&e.type==="resize"&&typeof e.height=="number"&&Number.isFinite(e.height)}var B=class{constructor(e={},t){this.provider="pcivault";this.container=null;this.messageHandler=null;this.actionOverlay=null;this.threeDsReturnHandler=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.submissionStarted=!1;this.submissionStartedAt=null;this.listeners=new Map;this.config=e,this.ownsTelemetryReporter=!t&&e.telemetry!==!1,this.telemetryReporter=t?.reporter??(this.ownsTelemetryReporter?new A({billingApiUrl:(0,v.resolveBillingApiUrl)(e.billingApiUrl),sdkVersion:v.SDK_VERSION}):void 0)}async mount(e,t){this.ownsTelemetryReporter&&!this.telemetryReporter&&(this.telemetryReporter=new A({billingApiUrl:(0,v.resolveBillingApiUrl)(this.config.billingApiUrl),sdkVersion:v.SDK_VERSION}));let r=this.telemetryReporter;if(this.config.operation==="card_setup"&&r&&this.setupTelemetryReporter!==r){this.setupTelemetryReporter=r;try{r.beginCheckout({checkoutMode:"setup"})}catch{}}if(this.mountStartedAt=this.telemetryReporter?.now?.()??_(),this.vaultReadyReported=!1,this.submissionStarted=!1,this.submissionStartedAt=null,typeof window>"u"||typeof document>"u")throw this.reportVaultLoadFailure(),new v.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 v.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.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(),x(H("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?.()??_())-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 r=this.listeners.get(e);return r||(r=new Set,this.listeners.set(e,r)),r.add(t),()=>{this.listeners.get(e)?.delete(t)}}unmount(){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 r=Array.from(e.querySelectorAll("script"));for(let s of r){let o=document.createElement("script");for(let i of Array.from(s.attributes))o.setAttribute(i.name,i.value);o.text=s.text,s.replaceWith(o)}}attachMessageListener(){if(this.messageHandler)return;let e=t=>{if(this.expectedOrigin&&t.origin!==this.expectedOrigin)return;let r=t.data;if(yt(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;this.applyHeight(r.height);return}if(ht(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;let c=r.messages.filter(l=>typeof l=="string"&&l.trim()).join(" ");this.emit("validation",{sessionId:this.config.sessionId,message:c||void 0});return}if(!mt(r)||this.messageToken&&r.messageToken!==this.messageToken)return;let s=this.config.sessionId,o=typeof r.sessionId=="string"?r.sessionId:void 0;if(s&&o&&o!==s||(r.type==="complete"||r.type==="decline")&&s&&o!==s)return;let i=pt(r.paymentMethod),a={...r.sessionId??this.config.sessionId?{sessionId:r.sessionId??this.config.sessionId}:{},...r.outcome?{outcome:r.outcome}:{},...r.paymentId?{paymentId:r.paymentId}:{},...r.authorizationExpiresAt?{authorizationExpiresAt:r.authorizationExpiresAt}:{},...r.failureOutcome?{failureOutcome:r.failureOutcome}:{},...r.intentId?{intentId:r.intentId}:{},...r.declineReason?{declineReason:r.declineReason}:{},...r.message?{message:r.message}:{},...i?{paymentMethod:i}:{}};r.type==="submitting"&&(this.submissionStarted=!0,this.submissionStartedAt=this.telemetryReporter?.now?.()??_()),x(dt(r,this.submissionStarted,this.config.captureMethod,this.config.operation)),this.reportOutcome(r),r.type==="ready"&&(this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),this.postSubmitLabel()),r.type==="action_required"&&r.nextActionRedirectUrl&&this.showActionRequiredOverlay(r.nextActionRedirectUrl),(r.type==="complete"||r.type==="decline"||r.type==="error"||r.type==="submitting")&&this.hideActionRequiredOverlay(),r.type!=="action_required"&&this.emit(r.type,a)};this.messageHandler=e,window.addEventListener("message",e)}reportOutcome(e){let t=this.telemetryReporter;if(!t)return;let{type:r}=e;if(r==="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"})),r==="complete"||r==="decline"){t.log({name:"vault.terminal",stage:"completion",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:Ce(e,this.config.captureMethod,this.config.operation),provider:"pcivault",paymentMethodCategory:"card"});return}if(r==="error"){let i=fe(this.submissionStarted,e);t.log({name:"vault.terminal",stage:i.stage,provider:"pcivault",paymentMethodCategory:"card"}),t.error({...i,provider:"pcivault",paymentMethodCategory:"card"});return}if(r==="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 i=this.submissionStartedAt;this.submissionStartedAt=null,i!==null&&t.performance({stage:"three_ds_handoff",durationMs:Math.max(0,t.now()-i),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:"action_required",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"});return}let[s,o]=ge[r];t.log({name:s,stage:o,provider:"pcivault",paymentMethodCategory:"card"})}applyTheme(e){this.theme=e,this.postTheme()}postTheme(){this.theme!==void 0&&this.postToHostedWindow({source:"flopay-vault-host",type:"theme",theme:this.theme},this.directiveTargetOrigin())}setSubmitGate(e){this.submitGateBlocked=e,this.postSubmitGate()}postSubmitGate(){this.postToHostedWindow({source:"flopay-vault-host",type:"gate",blocked:this.submitGateBlocked},this.directiveTargetOrigin())}setCardFieldOrder(e,t){this.cardFieldOrder=e,this.cardAutoFocus=t,this.postCardFieldOrder()}postCardFieldOrder(){this.postToHostedWindow({source:"flopay-vault-host",type:"fieldOrder",order:this.cardFieldOrder,autoFocus:this.cardAutoFocus},this.directiveTargetOrigin())}setSubmitLabel(e){this.submitLabel=e,this.postSubmitLabel()}postSubmitLabel(){let e=this.submitLabel,t=this.config.sessionId,{messageToken:r,expectedOrigin:s}=this;e===void 0||!t||!r||!s||this.postToHostedWindow({source:"flopay-vault-host",type:"submitLabel",sessionId:t,messageToken:r,label:e},s)}hostedWindow(){return this.container?.querySelector("iframe")?.contentWindow??null}postToHostedWindow(e,t){let r=this.hostedWindow();if(r)try{r.postMessage(e,t)}catch{}}directiveTargetOrigin(){return this.expectedOrigin??"*"}emit(e,t){for(let r of this.listeners.get(e)??[])r(t)}showActionRequiredOverlay(e){if(typeof document>"u")return;if(this.actionOverlay){let i=this.actionOverlay.querySelector("iframe");i instanceof HTMLIFrameElement&&i.src!==e&&(i.src=e),this.armActionRequiredTimeout();return}this.actionOverlayPreviousFocus=document.activeElement instanceof HTMLElement?document.activeElement:null;let t=document.createElement("div");t.setAttribute("data-flopay-action-required","1"),t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-label","Card authentication"),t.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 r=document.createElement("iframe");r.setAttribute("title","Card authentication"),r.setAttribute("allow","payment"),r.tabIndex=0,r.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(";"),r.src=e,t.appendChild(r);let s=document.createElement("button");s.type="button",s.setAttribute("aria-label","Close card authentication"),s.textContent="\xD7",s.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(";"),s.addEventListener("click",()=>this.abandonActionRequiredOverlay()),t.appendChild(s),t.addEventListener("click",i=>{i.target===t&&this.abandonActionRequiredOverlay()});let o=i=>{if(i.source!==r.contentWindow)return;let a=i.data;!a||typeof a!="object"||a.source!=="flopay-vault-3ds-return"||(x(H("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",o),this.threeDsReturnHandler=o,document.body.appendChild(t),this.actionOverlay=t,r.focus(),this.armActionRequiredTimeout(),x(H("vault.three_ds.handoff","three_ds_handoff"))}armActionRequiredTimeout(){this.actionOverlayTimer&&clearTimeout(this.actionOverlayTimer),this.actionOverlayTimer=setTimeout(()=>{this.actionOverlayTimer=null,this.actionOverlay&&this.timeOutActionRequiredOverlay()},it)}reportChallengeAbandoned(){x((0,v.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(){this.reportChallengeAbandoned(),this.hideActionRequiredOverlay(),this.emit("error",{...this.config.sessionId?{sessionId:this.config.sessionId}:{},message:at})}abandonActionRequiredOverlay(){this.actionOverlay&&(this.reportChallengeAbandoned(),this.hideActionRequiredOverlay(),this.emit("challenge_dismissed",{...this.config.sessionId?{sessionId:this.config.sessionId}:{}}))}hideActionRequiredOverlay(){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 r=Math.max(0,Math.min(Math.ceil(e),2e3));t.style.height=`${r}px`}};0&&(module.exports={PaymentAPI,PciVaultCardCapture});
@@ -1,2 +1,2 @@
1
- export { C as CardCaptureOperation, P as PaymentAPI, a as PciVaultCardCapture, b as PciVaultCardCaptureConfig } from './card-setup-Bk2dXNak.cjs';
1
+ export { C as CardCaptureOperation, P as PaymentAPI, a as PciVaultCardCapture, b as PciVaultCardCaptureConfig } from './card-setup-CbJ0b8Fm.cjs';
2
2
  import '@flopay/shared';
@@ -1,2 +1,2 @@
1
- export { C as CardCaptureOperation, P as PaymentAPI, a as PciVaultCardCapture, b as PciVaultCardCaptureConfig } from './card-setup-Bk2dXNak.js';
1
+ export { C as CardCaptureOperation, P as PaymentAPI, a as PciVaultCardCapture, b as PciVaultCardCaptureConfig } from './card-setup-CbJ0b8Fm.js';
2
2
  import '@flopay/shared';
@@ -1 +1 @@
1
- import{k as r,m as a}from"./chunk-DZX6SXGU.mjs";export{r as PaymentAPI,a as PciVaultCardCapture};
1
+ import{k as r,m as a}from"./chunk-OZIDFMT7.mjs";export{r as PaymentAPI,a as PciVaultCardCapture};
@@ -0,0 +1 @@
1
+ var He="flopay_session_display:";var U=new Map;function q(n){return`${He}${n}`}function K(){if(typeof window>"u")return null;try{return window.sessionStorage}catch{return null}}function G(n,e,t){if(!n)return;let r=t?.ttlMs??36e5,s={data:e,expiresAt:Date.now()+r},o=K();if(o)try{o.setItem(q(n),JSON.stringify(s));return}catch{}U.set(n,s)}function se(n){if(!n)return null;let e=K();if(e)try{let r=e.getItem(q(n));if(r){let s=JSON.parse(r);if(s&&typeof s.expiresAt=="number"&&s.expiresAt>Date.now())return s.data;e.removeItem(q(n))}}catch{}let t=U.get(n);if(t){if(t.expiresAt>Date.now())return t.data;U.delete(n)}return null}function oe(n){if(!n)return;U.delete(n);let e=K();if(e)try{e.removeItem(q(n))}catch{}}import{ASYNC_AUTO_CHECKOUT_CAPABILITY as nt,assertCaptureMethodEligible as me,buildProductPayload as ee,CHECKOUT_PROCESSING_TIMEOUT_MESSAGE as st,classifyPaymentRejection as ot,classifyTelemetryFailure as x,FLO_SDK_CAPABILITIES_HEADER as it,FLO_SDK_VERSION_HEADER as N,FloPayError as g,foldIntoProducts as Y,IDEMPOTENCY_IN_PROGRESS_CODE as at,IDEMPOTENCY_KEY_HEADER as pe,isCardHolderNamePlaceholder as ke,isDetachedSessionEligible as ut,isUuidV4 as he,isValidEmail as ye,normalizeCheckoutFailureOutcome as ge,PAYPAL_VAULTED_PAYMENT_METHOD_TYPE as W,randomUuidV4 as ct,resolveIdempotencyKey as lt,resolveSessionCurrency as J,SDK_VERSION as k,STORED_PAYMENT_METHOD_UNSUPPORTED_CODE as fe,STORED_PAYMENT_METHOD_UNSUPPORTED_MESSAGE as Ce,telemetryStatusClass as A}from"@flopay/shared";function ie(n){return typeof n=="string"&&n.trim()?n:void 0}function ae(n){if(typeof n=="string")return n.trim()?n:void 0;if(Array.isArray(n))return n.filter(t=>typeof t=="string"&&t.trim().length>0).join("; ")||void 0}function w(n=12e3){let e=Number.isFinite(n)&&n>=0?n:12e3,t=new AbortController,r=setTimeout(()=>t.abort(),e);return{signal:t.signal,clear:()=>clearTimeout(r)}}function Be(){return Object.assign(new Error("The operation was aborted."),{name:"AbortError"})}function L(n,e){let t=150*2**n,r=Math.round(t*(.75+Math.random()*.5));return new Promise((s,o)=>{let i,a=()=>e.removeEventListener("abort",u),u=()=>{i!==void 0&&clearTimeout(i),a(),o(Be())};if(e.aborted){u();return}i=setTimeout(()=>{a(),s()},r),e.addEventListener("abort",u,{once:!0})})}import{buildTelemetryErrorEvent as ue,buildTelemetryLogEvent as je,buildTelemetryPerformanceEvent as Ke,buildTelemetryTerminalEvent as Ge,serializeTelemetryBatch as $e,TELEMETRY_MAX_BATCH_BYTES as Ye}from"@flopay/shared";var We="/v1/sdk-telemetry/events",$=16,Je=64,Qe=1500,ce=1e3,Xe=64,Ze="00000000-0000-4000-8000-000000000000",et={technical_error:8,lifecycle:32,expected_outcome:32,performance:24};function I(){try{return globalThis.crypto.randomUUID()}catch{let n=new Uint8Array(16);try{globalThis.crypto.getRandomValues(n)}catch{for(let t=0;t<n.length;t+=1)n[t]=Math.floor(Math.random()*256)}n[6]=(n[6]??0)&15|64,n[8]=(n[8]??0)&63|128;let e=[...n].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 tt(n){try{return new TextEncoder().encode(n).byteLength}catch{return n.length}}function rt(n){return JSON.stringify([n.code,n.failureCategory,n.reason,n.stage,n.provider,n.attempt,n.statusClass,n.requestCategory,n.paymentMethodCategory,n.walletType,n.operationOutcome,n.checkoutMode,n.layout,n.inAppBrowser,n.appFamily,n.popupCapability,n.presentationMode,n.terminalReason])}function b(){return globalThis.performance?.now()??0}var _=class{constructor(e){this.ingestionDisabled=!1;this.queue=[];this.sequence=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(/\/+$/,"")}${We}`,this.sdkPackage=e.sdkPackage??"@flopay/js",this.sdkVersion=e.sdkVersion,this.correlationId=I(),this.merchantEnabled=e.enabled!==!1,this.clock=e.clock??b,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(je({...this.checkoutContext,...e,eventId:I(),sequence:this.sequence++}))}error(e){if(this.notify({...e,class:"technical_error"}),!this.canCollect())return;let t=ue({...this.checkoutContext,...e,eventId:Ze,sequence:0}),r=rt(t),s=this.now();this.pruneReportedFailures(s);let o=this.reportedFailures.get(r);if(o!==void 0&&s>=o&&s-o<ce){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(r,s),this.enqueue(ue({...this.checkoutContext,...e,eventId:I(),sequence:this.sequence++}))}performance(e){this.canCollect()&&this.enqueue(Ke({...this.checkoutContext,...e,eventId:I(),sequence:this.sequence++}))}terminal(e){if(this.canCollect()&&(this.enqueue(Ge({...this.checkoutContext,...e,eventId:I(),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"})}}now(){try{return this.clock()}catch{return b()}}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,r]of this.reportedFailures)(e<r||e-r>=ce)&&this.reportedFailures.delete(t)}rememberReportedFailure(e,t){for(;this.reportedFailures.size>=Xe;){let r=this.reportedFailures.keys().next();if(r.done)break;this.reportedFailures.delete(r.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.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>=Je||this.eventCounts[e.class]>=et[e.class])){if(this.eventCounts[e.class]+=1,this.queue.push(e),this.queue.length>=$){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,$);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,$);this.sendBatch(e)}}async sendBatch(e){if(!this.browserTransportAvailable||this.ingestionDisabled)return;let t=$e(e,{correlationId:this.correlationId,sdkPackage:this.sdkPackage,sdkVersion:this.sdkVersion,batchId:I()});if(tt(t)>Ye)return;let r=typeof AbortController>"u"?null:new AbortController,s=null;try{let o=fetch(this.endpoint,{method:"POST",headers:{"content-type":"text/plain;charset=UTF-8"},body:t,credentials:"omit",keepalive:!0,referrerPolicy:"no-referrer",signal:r?.signal}).then(async u=>{if(u.status!==202)return null;let c=null;try{c=await u.json()}catch{}return c?.status==="disabled"?"disabled":null}).catch(()=>null),i=new Promise(u=>{s=setTimeout(()=>{r?.abort(),u(null)},Qe)});await Promise.race([o,i])==="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)}},le=Symbol.for("@flopay/js.telemetry.reporter-factory.v1"),de=globalThis;de[le]===void 0&&Object.defineProperty(de,le,{configurable:!0,enumerable:!1,writable:!1,value:n=>new _(n)});function dt(n){return n==="on_session"||n==="off_session"}function mt(n){if(!n||typeof n!="object")return!1;let e=n;return typeof e.paymentMethodType=="string"&&typeof e.reason=="string"}var pt="x-flopay-process-result-source",ht="status";function ve(n){return n?.result==="DECLINE"||n?.result==="ERROR"}var yt=50,E=new Map;function gt(n,e){return E.get(n)?.has(e)===!0}function ft(n,e){let t=E.get(n)??new Set;if(t.add(e),E.delete(n),E.set(n,t),E.size>yt){let r=E.keys().next().value;r!==void 0&&E.delete(r)}}function Ct(n){let e=n?.threeDSecureActionResultTokenId;if(typeof e=="string"&&e.length>0)return e;if(n?.gateway==="paypal"&&n.type!=="paypal_setup_token"&&typeof n.id=="string"&&n.id.length>0)return n.id}var Te=0,be=500,V=15e3,Se=15e3,vt=3e3,Tt=1e4,bt=1e4;function Ee(n){return typeof n=="object"&&n!==null}function P(n,e){return ie(n?.[e])}function _e(n,e){return ae(n?.[e])}function St(n,e){let t=n?.[e];return typeof t=="number"&&Number.isFinite(t)?t:void 0}function X(n,e){return e?new Promise((t,r)=>{let s=()=>{clearTimeout(o),r(e.reason??Object.assign(new Error("The operation was aborted."),{name:"AbortError"}))},o=setTimeout(()=>{e.removeEventListener("abort",s),t()},n);e.aborted?s():e.addEventListener("abort",s,{once:!0})}):new Promise(t=>setTimeout(t,n))}function Q(n){return n instanceof Error&&n.name==="AbortError"}function v(){return new g(st,"api_error",{code:"checkout_processing_timeout"})}async function R(n,e){let t=await n.json().catch(()=>null),r=Ee(t?.error)?t.error:null,s=_e(t,"message")??_e(r,"message")??e,o=P(t,"code")??P(t,"gatewayErrorCode")??P(r,"code")??`http_${n.status}`;return new g(s,"api_error",{code:o,statusCode:n.status})}async function _t(n){let e=n.status===400?await n.clone().json().catch(()=>null):null;return ot(n.status,e)}function Re(n){return n===400||n===422}var H=2;async function z(n,e,t=H,r,s){let o;for(let i=0;;i++)try{return s?.(i),await fetch(n,e)}catch(a){if(e?.signal?.aborted||a instanceof Error&&a.name==="AbortError")throw a;if(o=a,i>=t)throw o;try{r?.(i+1)}catch{}await X(150*2**i,e?.signal??void 0)}}var Rt=Symbol.for("@flopay/js.session-create.telemetry.v1");function At(n){return n[Rt]}function kt(n){return"now"in n||"onFirstByte"in n||"onSessionCreateFailure"in n||"onRetry"in n}function Me(n){let e=ke(n.firstName,n.lastName);return{userId:n.userId,firstName:e?null:n.firstName??null,lastName:e?null:n.lastName??null,email:n.email,country:n.country??null,gender:n.gender??null,city:n.city??null,state:n.state??null,zip:n.zip??null,addressLine1:n.addressLine1??null,addressLine2:n.addressLine2??null}}function we(n,e){e.checkoutMetadata!==void 0&&(n.checkoutMetadata=e.checkoutMetadata),e.tagsData&&(n.tagsData=e.tagsData),e.utmMetadata&&e.utmMetadata.length>0&&(n.utmMetadata=e.utmMetadata),e.avsCheck!==void 0&&(n.avsCheck=e.avsCheck),e.checkoutType&&(n.checkoutType=e.checkoutType),e.checkoutLayout&&(n.checkoutLayout=e.checkoutLayout),e.avsConfig&&(n.avsConfig=e.avsConfig)}function Et(n,e){let t={clientId:n.clientId,checkoutVersion:k,successUrl:n.successUrl,cancelUrl:n.cancelUrl,currency:e,checkoutMode:"full",deferDataAttachment:!0};return n.captureMethod==="manual"&&(t.captureMethod=n.captureMethod),n.account.country&&(t.accountData={country:n.account.country}),we(t,n),t}function Ae(n,e,t){return{currency:e,products:t.map(r=>ee(r,e)),couponCodes:n.couponCodes??[],accountData:Me(n.account)}}function Mt(n,e,t){return{currency:e,products:t.map(r=>ee(r,e)),couponCodes:n.couponCodes??[]}}function wt(n){let e={},t=ke(n.firstName,n.lastName);for(let[r,s]of Object.entries(n)){if(t&&r.endsWith("Name")||typeof s!="string")continue;let o=s.trim();o&&(e[r]=o)}return{accountData:e}}var M=class M{constructor(e,t={}){this.baseUrl=e.replace(/\/+$/,"");let r=kt(t);this.telemetryHooks=r?t:void 0,this.directTelemetry=r||t.telemetry===!1?void 0:new _({billingApiUrl:this.baseUrl,sdkVersion:k})}destroy(){this.directTelemetry?.destroy()}reportDirectFailure(e,t,r,s,o="unknown"){let i=x(e,t);this.directTelemetry?.error({...i,stage:r,requestCategory:s,paymentMethodCategory:o})}reportAccountSnapshotFailure(e,t){let r=x(e,"NETWORK_REQUEST_FAILED");if(t==="best_effort"&&r.errorCode==="REQUEST_TIMEOUT"){this.directTelemetry?.log({name:"operation.fallback",stage:"processing",requestCategory:"account_snapshot",statusClass:"timeout"});return}this.directTelemetry?.error({...r,stage:"processing",requestCategory:"account_snapshot",paymentMethodCategory:"unknown"})}telemetryTimestamp(){try{return this.telemetryHooks?.now?.()??this.directTelemetry?.now()??b()}catch{return b()}}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,r=!0,s){this.beginDirectTelemetryCheckout(e);let o=this.telemetryTimestamp(),i=o,a=0;this.directTelemetry?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let u={[N]:k};t&&(u["x-checkout-session-token"]=t);try{let c=await z(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}`,{headers:u,signal:s},H,f=>{this.telemetryHooks?.onRetry?.("session_read",f),this.directTelemetry?.log({name:"operation.retry",stage:"session_read",requestCategory:"session_read",attempt:f})},f=>{a=f,i=this.telemetryTimestamp()}),d=Math.max(0,this.telemetryTimestamp()-i);try{this.telemetryHooks?.onFirstByte?.(d,a)}catch{}let l=`${Math.floor(c.status/100)}xx`;if(this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:l,attempt:a}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:d,durationMode:"machine",requestCategory:"session_read",statusClass:l,attempt:a}),!c.ok)throw await R(c,"Failed to get checkout session");let m=await c.json();return this.directTelemetry?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:l}),this.directTelemetry?.performance({stage:"session_complete",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"session_read",statusClass:l}),{...m,data:this.mergeCachedDisplayData(m.data)}}catch(c){throw r&&this.directTelemetry?.error({...x(c,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"}),c}}cacheSessionDisplayData(e,t,r){G(e,t,r)}clearSessionDisplayData(e){oe(e)}async getVaultCapture(e,t){let r=`${this.baseUrl}\0${e}\0${t??""}`,s=M.activeVaultCaptureRequests.get(r);if(s)return s;let o=this.requestVaultCapture(e,t);M.activeVaultCaptureRequests.set(r,o);try{return await o}finally{M.activeVaultCaptureRequests.get(r)===o&&M.activeVaultCaptureRequests.delete(r)}}async requestVaultCapture(e,t){let r=new AbortController,s=setTimeout(()=>r.abort(),bt);this.beginDirectTelemetryCheckout(e);let o=this.telemetryTimestamp();this.directTelemetry?.log({name:"vault.capture.requested",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card"});let i={"Content-Type":"application/json"};t&&(i["x-checkout-session-token"]=t);try{let a=await z(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/vault/capture`,{method:"POST",headers:i,signal:r.signal},H,c=>{this.telemetryHooks?.onRetry?.("vault_capture",c),this.directTelemetry?.log({name:"operation.retry",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card",attempt:c})});if(!a.ok)throw await R(a,"Failed to load the secure card form");let u=await a.json();return this.directTelemetry?.performance({stage:"vault_request",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"2xx"}),this.toVaultBlock(u)}catch(a){let u=r.signal.aborted?new g("Timed out while loading the secure card form. Please try again.","api_error",{code:"vault_capture_timeout"}):a;throw this.reportDirectFailure(u,"VAULT_LOAD_FAILED","vault_request","vault_capture","card"),u}finally{clearTimeout(s)}}async getUnifiedCheckoutSession(e,t){let r=await this.getCheckoutSession(e,t);return this.normalizeCheckoutSessionResponse(r)}async getUnifiedCheckoutSessionForRecovery(e,t,r){let s=await this.fetchCheckoutSession(e,t,!1,r);return this.normalizeCheckoutSessionResponse(s)}normalizeCheckoutSessionResponse(e){let t=this.normalizeRawSession(e.data),r=e.vault;return r&&t.data.session&&(t.data.session.vault=this.toVaultBlock(r)),t}async processPayment(e,t,r){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 g("processPayment requires `nonce` \u2014 pass the value returned from session creation.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let o=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.processing.started",stage:"processing",requestCategory:"process_payment",paymentMethodCategory:s});let{nonce:i,paymentMethodCategory:a,...u}=t,c=Ct(t.tokenizedData),d;try{d=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(t.sessionId)}/process`,{method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":i},body:JSON.stringify(u)})}catch(l){if(Q(l))throw this.reportDirectFailure(l,"PAYMENT_PROCESSING_FAILED","processing","process_payment",s),l;d=await this.reconcileProcessPayment(t.sessionId,{...r,nonce:i,paymentMethodCategory:s,submittedIntentId:c})}if(!d.ok&&d.status!==202){let l=await _t(d);return l?this.directTelemetry?.terminal({outcome:l,stage:"processing",requestCategory:"process_payment",statusClass:"4xx",paymentMethodCategory:s}):this.directTelemetry?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",requestCategory:"process_payment",statusClass:A(d.status),failureCategory:d.status>=500?"server_error":void 0,paymentMethodCategory:s}),d}try{let l=await this.resolveProcessResponse(d,t.sessionId,{...r,nonce:i,paymentMethodCategory:s,submittedIntentId:c});return this.directTelemetry?.log({name:"payment.processing.completed",stage:"processing",requestCategory:"process_payment",statusClass:A(l.status),paymentMethodCategory:s}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"process_payment",statusClass:A(l.status),paymentMethodCategory:s}),l}catch(l){throw l instanceof g&&l.code==="checkout_processing_timeout"||this.reportDirectFailure(l,"PAYMENT_PROCESSING_FAILED","processing","process_payment",s),l}}async patchAccountSnapshot(e,t,r,s){this.beginDirectTelemetryCheckout(e);let o=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.state_transition",stage:"processing",requestCategory:"account_snapshot"});let i=s?.timeoutMs??Tt,a=new AbortController,u=()=>a.abort();s?.signal&&(s.signal.aborted?a.abort():s.signal.addEventListener("abort",u,{once:!0}));let c=setTimeout(()=>a.abort(),i);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(r),signal:a.signal},H,l=>{this.telemetryHooks?.onRetry?.("account_snapshot",l),this.directTelemetry?.log({name:"operation.retry",stage:"processing",requestCategory:"account_snapshot",attempt:l})})}finally{clearTimeout(c),s?.signal?.removeEventListener("abort",u)}if(!d.ok)throw await R(d,"Failed to persist account snapshot");this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"account_snapshot",statusClass:"2xx"})}catch(d){throw this.reportAccountSnapshotFailure(d,s?.telemetryMode??"blocking"),d}}async createSessionIntent(e,t,r,s){if(!t)throw new g("createSessionIntent requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let o=r,i=o.paymentMethodType,a=typeof i=="string"&&i.trim().toLowerCase()==="card",u=typeof i=="string"&&i.length>0&&!a&&(typeof o.paymentMethodId=="string"||o.paymentMethodId===null),c=o.provider==="stripe"&&(o.paymentMethodCategory==="wallet"||o.paymentMethodCategory==="apm")&&(o.intentKind==="payment"||o.intentKind==="setup"),d=o.provider==="paypal"&&o.paymentMethodCategory==="wallet"&&o.paymentMethodId===null&&(o.paymentMethodType==="paypal"&&o.intentKind==="payment"||o.paymentMethodType===W&&(o.intentKind==="payment"||o.intentKind==="setup"));if(!u||!c&&!d)throw new g("Only wallet, APM, and PayPal session intents are supported.","validation_error",{code:"InvalidSessionIntentRequest"});let l=o.authorizationAttemptId;if(l!==void 0&&!he(l))throw new g("authorizationAttemptId must be a v4 UUID identifying one buyer authorization attempt.","validation_error",{code:"InvalidAuthorizationAttemptId",param:"authorizationAttemptId"});let m=he(l)?l:ct();this.beginDirectTelemetryCheckout(e);let f=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.intent.started",stage:"processing",requestCategory:"intent_create"});let p={"Content-Type":"application/json","x-checkout-session-token":t,[pe]:s?.idempotencyKey||m},C=!1;try{let h=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents`,{method:"POST",headers:p,body:JSON.stringify({...r,authorizationAttemptId:m}),signal:s?.signal});if(!h.ok){C=!0;let j=await R(h,"Failed to create checkout intent"),ze=x(j,"PAYMENT_PROCESSING_FAILED");throw Re(j.statusCode)?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"intent_create",statusClass:"4xx"}):this.directTelemetry?.error({...ze,stage:"processing",requestCategory:"intent_create"}),j}let T=(await h.json()).data;if(!T||typeof T!="object")throw new g("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});let y=T,ne=y.paymentMethodType,qe=(y.paymentMethodCategory==="wallet"||y.paymentMethodCategory==="apm")&&typeof ne=="string"&&ne.trim().toLowerCase()!=="card"&&(typeof y.paymentMethodId=="string"||y.paymentMethodId===null)&&typeof y.providerObjectId=="string",Le=y.provider==="stripe"&&(y.intentKind==="payment"||y.intentKind==="setup")&&typeof y.clientSecret=="string",Ne=y.provider==="paypal"&&y.paymentMethodCategory==="wallet"&&y.paymentMethodId===null&&(y.paymentMethodType==="paypal"&&y.intentKind==="payment"&&(y.providerObjectType==="order"||y.providerObjectType==="subscription")||y.paymentMethodType===W&&y.intentKind==="payment"&&y.providerObjectType==="order"||y.paymentMethodType===W&&y.intentKind==="setup"&&y.providerObjectType==="setup_token")&&y.clientSecret===null,Ve=y.provider===r.provider&&y.paymentMethodCategory===r.paymentMethodCategory&&y.paymentMethodType===r.paymentMethodType&&y.paymentMethodId===r.paymentMethodId&&y.intentKind===r.intentKind;if(!qe||!Le&&!Ne||!Ve)throw new g("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});return this.directTelemetry?.log({name:"payment.intent.completed",stage:"processing",requestCategory:"intent_create",statusClass:A(h.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-f),durationMode:"machine",requestCategory:"intent_create",statusClass:A(h.status)}),y}catch(h){throw C||this.reportDirectFailure(h,"PAYMENT_PROCESSING_FAILED","processing","intent_create"),h}}async reportSessionIntentDecline(e,t,r,s){if(!t)throw new g("reportSessionIntentDecline requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let o=r,i=o.providerDeclineReason,a=o.paymentMethodType,u=o.providerIntentId,c=typeof i=="string"&&/^[a-z0-9][a-z0-9_.:-]{0,63}$/i.test(i)&&!/^(?:pm|pi|seti|tok|src|cus|sess|sk|pk)_/i.test(i),d=typeof a=="string"&&a.length>0&&a.trim().toLowerCase()!=="card"&&c,l=o.provider==="stripe"&&(o.paymentMethodCategory==="wallet"||o.paymentMethodCategory==="apm")&&(u===void 0||typeof u=="string"&&/^pi_[a-z0-9_]{1,252}$/i.test(u)),m=o.provider==="paypal"&&o.paymentMethodCategory==="wallet"&&o.paymentMethodType==="paypal"&&u===void 0;if(!d||!l&&!m)throw new g("Invalid non-card decline classification.","validation_error",{code:"InvalidSessionIntentDeclineRequest"});let f=m?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:i}:{provider:"stripe",paymentMethodCategory:o.paymentMethodCategory,paymentMethodType:o.paymentMethodType,providerDeclineReason:i,...typeof u=="string"?{providerIntentId:u}:{}},p=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents/decline`,{method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":t},body:JSON.stringify(f),signal:s?.signal});if(!p.ok)throw await R(p,"Failed to report checkout decline")}async getPaymentsByEmail(e,t){this.beginDirectTelemetryOperation();let r=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved"});let s=t?.page??1,o=t?.limit??1,i=new URLSearchParams({email:e,page:String(s),limit:String(o),sortField:"createdAt",sortDirection:"DESC"});try{let a=await fetch(`${this.baseUrl}/v1/payments?${i.toString()}`,{method:"GET",signal:t?.signal,keepalive:!0});if(!a.ok)throw new g("Failed to fetch payments","api_error",{statusCode:a.status});let u=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()-r),durationMode:"machine",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),u}catch(a){throw this.reportDirectFailure(a,"RECOVERY_FAILED","recovery","other","saved"),a}}async createAndFetchSession(e){if(ut(e)){let o=e.account.email?.trim();if(o&&!ye(o))throw new g("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(),r=w(e.timeoutMs??12e3),s={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});try{let o=await this.createAndFetchSessionRequest(e,r.signal,s);return this.adoptDirectTelemetryCheckout(o.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}),o}catch(o){throw this.reportSessionCreateFailure(o,t,s),o}finally{r.clear()}}async createAndFetchSessionRequest(e,t,r){let s=e.products??Y(e.items,e.subscriptions);me({captureMethod:e.captureMethod,products:s});let o=J(e.currency,e.items,e.subscriptions,s);if(!o)throw new g("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 i={clientId:e.clientId,checkoutVersion:k,successUrl:e.successUrl,cancelUrl:e.cancelUrl,currency:o,checkoutMode:e.checkoutMode??"full",products:s.map(l=>ee(l,o)),accountData:Me(e.account),couponCodes:e.couponCodes??[]};e.captureMethod==="manual"&&(i.captureMethod=e.captureMethod),e.tokenizedData&&(i.tokenizedData=e.tokenizedData),we(i,e);let u=await(await this.postCheckoutSessionCreate(i,e,t,r)).json();if(u.data&&"gateways"in u.data){this.autoCacheDisplayData(u.data.uuid,e);let l=this.mergeCachedDisplayData(u.data),m=this.normalizeRawSession(l);return u.vault&&m.data.session&&(m.data.session.vault=this.toVaultBlock(u.vault)),{...m,autoProcessingError:u.autoProcessingError,autoProcessingAttempted:u.autoProcessingAttempted,autoProcessingPending:u.autoProcessingPending}}let c=u.data?.uuid;if(!c)throw new g("No session ID returned","api_error",{code:"InvalidCheckoutSessionResponse"});return this.autoCacheDisplayData(c,e),this.adoptDirectTelemetryCheckout(c),{...await this.getUnifiedCheckoutSession(c),autoProcessingError:u.autoProcessingError,autoProcessingAttempted:u.autoProcessingAttempted,autoProcessingPending:u.autoProcessingPending}}async postCheckoutSessionCreate(e,t,r,s){let o={"Content-Type":"application/json",[N]:k},i=lt(t.idempotencyKey);i&&(o[pe]=i),t.checkoutMode==="auto"&&(o[it]=nt);let a,u=!1,c=At(t),d=(m,f,p)=>{u||(u=!0,this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:p,attempt:m}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:Math.max(0,this.telemetryTimestamp()-f),durationMode:"machine",requestCategory:"session_create",statusClass:p,attempt:m}))},l=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{c?.onAttempt?.(m)}catch{}try{a=await fetch(`${this.baseUrl}/v1/checkouts/sessions?expand=true`,{method:"POST",headers:o,body:JSON.stringify(e),signal:r})}catch(h){if(s.statusClass=r.aborted||h instanceof Error&&h.name==="AbortError"?"timeout":"network_error",r.aborted||h instanceof Error&&h.name==="AbortError"||m>=2)throw h;let S=m+1;l(S),await L(m,r);continue}let p=A(a.status);if(s.statusClass=p,a.status===204)throw d(m,f,p),new g("Session auto-completed \u2014 payment method already on file","api_error",{code:"session_auto_completed"});if(a.ok){d(m,f,p);break}let C=await R(a,"Failed to create checkout session");if(C.code===at&&m<2){l(m+1),await L(m,r);continue}throw d(m,f,p),C}if(!a)throw new TypeError("Checkout-session creation exhausted its retry budget.");return a}async createDetachedSession(e){this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp(),r=w(e.timeoutMs??12e3),s={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let o=e.products??Y(e.items,e.subscriptions);try{me({captureMethod:e.captureMethod,products:o})}catch(h){throw r.clear(),this.reportSessionCreateFailure(h,t,s),h}let i=J(e.currency,e.items,e.subscriptions,o);if(!i)throw r.clear(),this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),new g("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{Ae(e,i,o)}catch(h){throw r.clear(),this.reportSessionCreateFailure(h,t,s),h}let a,u;try{if(u=await(await this.postCheckoutSessionCreate(Et(e,i),e,r.signal,s)).json(),!u.data||!("gateways"in u.data))throw new g("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(u.data)),u.vault&&a.data.session&&(a.data.session.vault=this.toVaultBlock(u.vault))}catch(h){throw r.clear(),this.reportSessionCreateFailure(h,t,s),h}let c=a.data.session?.id??u.data.uuid??"",d=a.data.session?.clientSecret??u.data.nonce??"";if(!c||!d){r.clear();let h=new g("Checkout session shell was created without a session id or nonce.","api_error",{code:"InvalidCheckoutSessionResponse"});throw this.reportSessionCreateFailure(h,t,s),h}r.clear(),this.adoptDirectTelemetryCheckout(c),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 l=!e.account.email?.trim(),m=w(e.timeoutMs??12e3),f=this.claimCheckoutSession(c,d,l?Mt(e,i,o):Ae(e,i,o),{params:e,startedAt:t,deadline:m,createAttempt:s.attempt}),p=l?void 0:f,C=(h={})=>{if(p!==void 0)return p;let S={...e,account:{...e.account,...h,email:h.email?.trim()||e.account.email?.trim()}};return ye(S.account.email)?(p=f.then(()=>{let T=this.telemetryTimestamp();return this.claimCheckoutSession(c,d,wt(S.account),{params:S,startedAt:T,deadline:w(e.timeoutMs??12e3),createAttempt:0})}),p.catch(()=>{}),p):Promise.reject(new g("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}))};return f.catch(()=>{}),{shell:a,sessionId:c,nonce:d,claimed:f,claim:C}}async claimCheckoutSession(e,t,r,s){let o=s?.startedAt??this.telemetryTimestamp(),i=this.telemetryTimestamp(),a=s?.deadline??w(12e3),u=JSON.stringify(r),c="unknown",d=0;this.directTelemetry?.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"});try{let l;for(d=0;d<3;d++){try{l=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/claim`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":t,[N]:k},body:u,signal:a.signal})}catch(p){let C=a.signal.aborted||p instanceof Error&&p.name==="AbortError";if(c=C?"timeout":"network_error",C||d>=2)throw p;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 L(d,a.signal);continue}if(c=A(l.status),l.ok)break;throw await R(l,"Failed to attach checkout session data")}if(!l)throw new TypeError("Checkout-session claim exhausted its retry budget.");let m=await l.json();if(!m.data?.gateways)throw new g("The billing API returned no checkout session with gateways after claiming it.","api_error",{code:"InvalidCheckoutSessionResponse"});s?.params&&this.autoCacheDisplayData(m.data.uuid??e,s.params);let f=this.normalizeRawSession(this.mergeCachedDisplayData(m.data));return m.vault&&f.data.session&&(f.data.session.vault=this.toVaultBlock(m.vault)),this.directTelemetry?.log({name:"session.claim.completed",stage:"session_claim",requestCategory:"session_claim",statusClass:c}),this.directTelemetry?.performance({stage:"session_claim",durationMs:Math.max(0,this.telemetryTimestamp()-i),durationMode:"machine",requestCategory:"session_claim",statusClass:c,attempt:d}),this.directTelemetry?.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:c}),this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"session_create",statusClass:c,attempt:s?.createAttempt??d}),f}catch(l){throw this.reportSessionCreateFailure(l,i,{attempt:d,statusClass:c},"session_claim"),l}finally{a.clear()}}reportSessionCreateFailure(e,t,r,s="session_create"){if(!(e instanceof g&&e.code==="session_auto_completed"))try{this.telemetryHooks?.onSessionCreateFailure?.(e)}catch{}let o=x(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:o.statusClass,attempt:r.attempt}),e instanceof g&&e.type==="validation_error"||e instanceof g&&Re(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 g&&e.code==="session_auto_completed"||this.directTelemetry?.error({...o,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"})}async waitForCheckoutSessionCompletion(e,t){this.beginDirectTelemetryCheckout(e);let r=this.telemetryTimestamp(),s=t?.paymentMethodCategory??"saved";this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:s});let o=t?.timeoutMs??V,i=Date.now()+o,a=new AbortController,u=!1,c,d=setTimeout(()=>{c=setTimeout(()=>{u=!0,a.abort()},Se)},o),l=()=>a.abort(t?.signal?.reason);t?.signal?.aborted?l():t?.signal?.addEventListener("abort",l,{once:!0});let m=this.clampRetryAfterMs(t?.initialDelayMs??Te),f=0;try{if(t?.statusUrl){let p=await this.waitForCheckoutStatus(e,{initialDelayMs:m,timeoutMs:o,nonce:t.nonce,statusUrl:t.statusUrl,pollAfterAction:t.continueAfterActionRequired,signal:a.signal});if(p){let C=await this.resolveCheckoutSessionStatus(e,p,t.nonce,a.signal,()=>u);return this.reportRecoveryCompleted(r,s),C}}for(;;){let p=i-Date.now();if(p<=0)throw v();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 X(Math.min(m,p),a.signal),Date.now()>=i)throw v()}let C=await this.getUnifiedCheckoutSessionForRecovery(e,t?.nonce,a.signal),h=C.data.session?.status;if(h==="authorized"||h==="complete"||h==="expired")return this.reportRecoveryCompleted(r,s),C;if(Date.now()>=i)throw v();m=this.clampRetryAfterMs(Math.max(m*2,be))}}catch(p){let C=u&&Q(p)?v():p;throw this.reportDirectFailure(C,"RECOVERY_FAILED","recovery","session_read",s),C}finally{clearTimeout(d),clearTimeout(c),t?.signal?.removeEventListener("abort",l)}}reportRecoveryCompleted(e,t){let r={stage:"recovery",requestCategory:"session_read",paymentMethodCategory:t};this.directTelemetry?.log({name:"operation.recovery.completed",...r}),this.directTelemetry?.performance({...r,durationMs:Math.max(0,this.telemetryTimestamp()-e),durationMode:"machine"})}async resolveCheckoutSessionStatus(e,t,r,s,o){let i=t.latestTransactionAttempt;if(this.rememberReportedFailure(e,t),i?.result==="DECLINE"){let c=i.code===fe;throw new g(c?Ce:"Payment was declined. Please choose another payment method.","api_error",{code:i.code??i.declineReason??"authorization_declined",statusCode:400})}if(i?.result==="ERROR"||t.status==="voided")throw new g("Payment could not be completed. Please try again.","api_error",{code:i?.code??"payment_processing_error",statusCode:500});let a;try{a=await this.getUnifiedCheckoutSessionForRecovery(e,r,s)}catch(c){if(!o?.()||!Q(c))throw c;a={providers:[],mode:"tokenize",data:{},raw:t}}let u=a.data.session;return u&&i?.result==="SUCCESS"?{...a,data:{...a.data,session:{...u,status:"complete"}}}:u&&i?.result==="AUTHORIZED"?{...a,data:{...a.data,session:{...u,status:"authorized",paymentId:t.paymentId??void 0,authorizationExpiresAt:t.authorizationExpiresAt??void 0}}}:u&&t.status==="completed"?{...a,data:{...a.data,session:{...u,status:"complete"}}}:u&&t.status==="authorized"?{...a,data:{...a.data,session:{...u,status:"authorized",paymentId:t.paymentId??void 0,authorizationExpiresAt:t.authorizationExpiresAt??void 0}}}:u&&t.status==="expired"?{...a,data:{...a.data,session:{...u,status:"expired"}}}:i?.result!=="ACTION_REQUIRED"?a:i.gateway==="paypal"&&i.providerIntentId?{...a,autoProcessingError:{type:"paypal_direct_required",message:"PayPal authorization required",orderId:i.providerIntentId,checkoutMethod:"paypal"}}:i.nextActionRedirectUrl?{...a,autoProcessingError:{type:"3ds_required",message:"Additional authentication is required.",nextActionRedirectUrl:i.nextActionRedirectUrl}}:a}async waitForCheckoutStatus(e,t){let r=t.timeoutMs??V,s=Date.now()+r,o=this.clampRetryAfterMs(t.initialDelayMs);for(;;){let i=s-Date.now();if(i<=0||o>0&&(await X(Math.min(o,i),t.signal),Date.now()>=s))throw v();let a=s-Date.now();if(a<=0)throw v();let u=new AbortController,c,d=t.signal?new Promise((T,y)=>{c=y}):null,l=()=>{u.abort(t.signal?.reason),c?.(t.signal?.reason??Object.assign(new Error("The operation was aborted."),{name:"AbortError"}))};t.signal?.aborted?l():t.signal?.addEventListener("abort",l,{once:!0});let m,f=t.signal?null:new Promise((T,y)=>{m=setTimeout(()=>{y(v()),u.abort()},a+Se)}),p;try{let T=this.fetchCheckoutStatus(e,t.nonce,t.statusUrl,u.signal);p=await Promise.race([T,f,d].filter(y=>y!==null))}finally{m!==void 0&&clearTimeout(m),t.signal?.removeEventListener("abort",l)}if(!p)return null;let C=ve(p.latestTransactionAttempt)&&!this.isOwnFailedAttempt(e,p,t.submittedIntentId);if(p.status==="completed"||p.status==="authorized"||p.status==="expired"||p.status==="voided")return C?{...p,latestTransactionAttempt:null}:p;let h=p.latestTransactionAttempt?.result,S=t.pollAfterAction===!0&&h==="ACTION_REQUIRED";if(!C&&h!==void 0&&h!=="PENDING"&&!S)return p;o=this.clampRetryAfterMs(Math.max(o*2,be))}}isOwnFailedAttempt(e,t,r){let s=t.latestTransactionAttempt?.providerIntentId??null;return r!==void 0?s===r:s===null?!0:!gt(t.uuid||e,s)}rememberReportedFailure(e,t){let r=t.latestTransactionAttempt;!ve(r)||!r.providerIntentId||ft(t.uuid||e,r.providerIntentId)}async fetchCheckoutStatus(e,t,r,s){let o=`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/status`,i=o;if(r)try{let d=new URL(r,`${this.baseUrl}/`),l=new URL(o);d.origin===l.origin&&(i=d.toString())}catch{}let a={[N]:k};t&&(a["x-checkout-session-token"]=t);let u=await z(i,{headers:a,signal:s});if(u.status===404||u.status===405)return null;if(!u.ok)throw await R(u,"Failed to get checkout session status");let c=await u.json();return Ee(c.data)&&"latestTransactionAttempt"in c.data?c.data:null}normalizeRawSession(e){let t=e.gateways??{},r=[],s={session:this.toCheckoutSession(e)},o=t.stripe;if(o?.publishableKey){r.push("stripe");let u=[e.stripeClientSecret,o.stripeClientSecret].find(c=>typeof c=="string"&&c.length>0);s.stripe={clientSecret:u??"",publishableKey:o.publishableKey??void 0,paypalPublishableKey:o.paypalPublishableKey??void 0,environment:o.environment,enabledPaymentMethods:Array.isArray(o.enabledPaymentMethods)?o.enabledPaymentMethods.filter(c=>typeof c=="string"):void 0}}let i=t.paypal;return i?.publishableKey&&(r.push("paypal"),s.paypal={publishableKey:i.publishableKey,environment:i.environment,providerObjectType:i.providerObjectType,approvalPresentation:i.approvalPresentation}),{providers:r,mode:"tokenize",...e.checkoutMetadata===void 0?{}:{checkoutMetadata:e.checkoutMetadata},data:s,raw:{data:e}}}toCheckoutSession(e){let t=e.products??[],r=typeof e.totalAmount=="number"&&Number.isFinite(e.totalAmount),s=t.reduce((c,d)=>c+(d.overrideAmount??d.totalAmount??0),0),o=r?e.totalAmount:s,i=Math.round(o*100),a=e.currency??t[0]?.currency??"USD",u="payment";return e.checkoutMode==="setup"?u="setup":t.some(c=>c.type==="subscription")&&(u="subscription"),{id:e.uuid,clientSecret:e.nonce,mode:u,status:this.toCheckoutSessionStatus(e.status),amount:i,currency:a,captureMethod:e.captureMethod,paymentId:e.paymentId,authorizationExpiresAt:e.authorizationExpiresAt,failureOutcome:ge(e.outcome)??ge(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}:{},...dt(e.futureUse)?{futureUse:e.futureUse}:{},...Array.isArray(e.futureUseUnsupported)?{futureUseUnsupported:e.futureUseUnsupported.filter(mt)}:{},buyerIdentified:e.buyerIdentified,providerPaymentMethodId:typeof e.providerPaymentMethodId=="string"?e.providerPaymentMethodId:null,products:t.map(c=>({...c,totalAmount:typeof c.totalAmount=="number"?c.totalAmount:void 0,overrideAmount:typeof c.overrideAmount=="number"?c.overrideAmount:null,currency:typeof c.currency=="string"?c.currency:void 0,metadata:c.metadata??null})),successUrl:e.successUrl,cancelUrl:e.cancelUrl,coupons:e.coupons,subtotalAmount:e.subtotalAmount,discountAmount:e.discountAmount,totalAmount:e.totalAmount,createdAt:e.createdAt,gateways:e.gateways,accountData:e.accountData,tagsData:e.tagsData}}toVaultBlock(e){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}}toCheckoutSessionStatus(e){return e==="completed"?"complete":e==="authorized"?"authorized":e==="expired"?"expired":"open"}async resolveProcessResponse(e,t,r){if(e.status!==202)return e;let s=await e.json().catch(()=>null),o=this.toCheckoutProcessingPending(s,e,t),i=r?.pollTimeoutMs??V,a=Date.now()+i;if(o.statusUrl){let c=await this.waitForCheckoutStatus(o.sessionId,{initialDelayMs:o.retryAfterMs,timeoutMs:i,nonce:r?.nonce,statusUrl:o.statusUrl,submittedIntentId:r?.submittedIntentId});if(c)return this.toProcessResponseFromStatus(c,t,r?.nonce)}let u=await this.waitForCheckoutSessionCompletion(o.sessionId,{initialDelayMs:o.retryAfterMs,timeoutMs:a-Date.now(),nonce:r?.nonce,paymentMethodCategory:r?.paymentMethodCategory});return this.toProcessResponseFromSession(u,t)}async toProcessResponseFromStatus(e,t,r){let s=e.latestTransactionAttempt?.result,o={[pt]:ht},i={"Content-Type":"application/json",...o};if(e.status==="completed"||s==="SUCCESS")return new Response(null,{status:204,statusText:"No Content",headers:o});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:i});if(e.status==="expired"){let a=await this.resolveCheckoutSessionStatus(t,e,r);return this.toProcessResponseFromSession(a,t)}if(this.rememberReportedFailure(t,e),s==="DECLINE"){let a=e.latestTransactionAttempt,u=a?.code===fe,c=a?.declineReason??void 0;return new Response(JSON.stringify({type:c??"authorization_declined",message:u?Ce:"Payment was declined. Please choose another payment method.",code:a?.code??c??"authorization_declined",...c?{declineCode:c}:{}}),{status:400,headers:i})}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:i});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:i});if(s==="ERROR"||e.status==="voided")return new Response(JSON.stringify({type:"unknown",code:e.latestTransactionAttempt?.code??"payment_processing_error",message:"Payment could not be completed. Please try again."}),{status:500,headers:i});throw v()}async reconcileProcessPayment(e,t){let r=t?.pollTimeoutMs??V,s=Date.now()+r,o=null;try{o=await this.waitForCheckoutStatus(e,{initialDelayMs:0,timeoutMs:r,nonce:t?.nonce,submittedIntentId:t?.submittedIntentId})}catch(u){if(this.reportDirectFailure(u,"RECOVERY_FAILED","recovery","session_read",t?.paymentMethodCategory??"saved"),u instanceof g&&u.code==="checkout_processing_timeout")throw u}if(o)return this.toProcessResponseFromStatus(o,e,t?.nonce);let i=s-Date.now();if(i<=0)throw v();let a=await this.waitForCheckoutSessionCompletion(e,{initialDelayMs:0,timeoutMs:i,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 r=e.data.session;return new Response(JSON.stringify({status:"authorized",paymentId:r.paymentId,sessionId:r.id||t,authorizationExpiresAt:r.authorizationExpiresAt}),{status:200,headers:{"Content-Type":"application/json"}})}if(e.data.session?.status==="expired"){let r=e.data.session.failureOutcome==="authorization_expired"||e.data.session.captureMethod==="manual";throw new g(r?"Authorization has expired.":"Checkout session has expired.","api_error",{code:r?"authorization_expired":"checkout_session_expired"})}throw v()}toCheckoutProcessingPending(e,t,r){let s=t.headers.get("Retry-After"),o=s===null||s.trim()===""?void 0:Number(s),i=o!==void 0&&Number.isFinite(o)?o*1e3:void 0;return{type:"checkout_processing",sessionId:P(e,"sessionId")??r,retryAfterMs:this.clampRetryAfterMs(St(e,"retryAfterMs")??i??Te),statusUrl:P(e,"statusUrl"),sessionUrl:P(e,"sessionUrl")}}clampRetryAfterMs(e){return Math.max(0,Math.min(e,vt))}autoCacheDisplayData(e,t){if(!e)return;let r=t.products??Y(t.items,t.subscriptions);if(r.length===0&&!t.currency)return;let s=t.products!==void 0,o=J(t.currency,s?void 0:t.items,s?void 0:t.subscriptions,r);G(e,{currency:o??void 0,products:r.map(i=>({code:i.code??i.providerItemId??i.providerPlanId,type:i.type,name:i.name??i.itemName??i.providerItemName??i.subscriptionName??i.providerPlanName??null,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency??o??void 0}))})}mergeCachedDisplayData(e){let t=se(e.uuid),r=new Map,s=i=>i?`code:${i}`:void 0;for(let i of t?.products??[]){let a=s(i.code);a&&r.set(a,i)}let o=(e.products??[]).map(i=>{let a=s(i.code),u=a?r.get(a):void 0;return{...i,name:i.name??u?.name??null,totalAmount:i.totalAmount??u?.totalAmount,overrideAmount:i.overrideAmount??u?.overrideAmount,currency:i.currency??u?.currency}});return{...e,currency:e.currency??t?.currency,products:o}}};M.activeVaultCaptureRequests=new Map;var Z=M;function er(n,e){let t=Z;return new t(n,e)}import{buildTelemetryErrorEvent as It,buildTelemetryLogEvent as Pt,buildTelemetryTerminalEvent as Oe,FloPayError as Ie,resolveBillingApiUrl as Pe,SDK_VERSION as De,THREE_DS_CHALLENGE_WINDOW_MS as Dt}from"@flopay/shared";var re="flopay-vault",Ot=3e4,xt=Dt+Ot,Ft="Card authentication timed out.",xe={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 Ut(n){return n.class==="lifecycle"?n.name:n.class==="technical_error"?n.code:n.class==="expected_outcome"?n.outcome:"sdk.performance"}function F(n){let e={class:n.class,stage:n.stage};"code"in n&&(e.code=n.code),"provider"in n&&n.provider&&(e.provider=n.provider),"paymentMethodCategory"in n&&n.paymentMethodCategory&&(e.paymentMethodCategory=n.paymentMethodCategory),"outcome"in n&&(e.outcome=n.outcome),"durationMs"in n&&n.durationMs!==void 0&&(e.durationMs=n.durationMs),"durationMode"in n&&n.durationMode&&(e.durationMode=n.durationMode);try{globalThis.Sentry?.addBreadcrumb?.({category:"flopay.telemetry",level:n.class==="technical_error"?"error":"info",message:Ut(n),data:e})}catch{}}function B(n,e){return Pt({eventId:"11111111-1111-4111-8111-111111111111",name:n,stage:e,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}var qt=new Set(["authorization_declined","authentication_required","authorization_expired","capture_failed"]);function Lt(n){return typeof n=="string"&&qt.has(n)?n:"unknown"}function Fe(n,e){return n?{errorCode:"VAULT_SUBMIT_FAILED",stage:"vault_submit",failureCategory:"provider_runtime",reason:Lt(e.failureOutcome)}:{errorCode:"VAULT_LOAD_FAILED",stage:"vault_mount",failureCategory:"provider_runtime"}}function Ue(n,e,t="checkout"){return t==="card_setup"?n.type==="decline"?"card_setup_declined":"card_setup_succeeded":n.type==="decline"?"payment_declined":n.outcome==="authorized"||e==="manual"?"payment_authorized":"payment_succeeded"}function Nt(n,e,t,r="checkout"){let{type:s}=n;if(s==="complete"||s==="decline")return Oe({eventId:"22222222-2222-4222-8222-222222222222",outcome:Ue(n,t,r),sequence:0,provider:"pcivault",paymentMethodCategory:"card"});if(s==="error"){let a=Fe(e,n);return It({eventId:"33333333-3333-4333-8333-333333333333",...a,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}let[o,i]=xe[s];return B(o,i)}function Vt(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===re&&(e.type==="ready"||e.type==="submitting"||e.type==="blocked"||e.type==="complete"||e.type==="decline"||e.type==="error"||e.type==="action_required")}function zt(n){if(typeof n!="object"||n===null)return;let e=n,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 Ht(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===re&&e.type==="validation"&&Array.isArray(e.messages)}function Bt(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===re&&e.type==="resize"&&typeof e.height=="number"&&Number.isFinite(e.height)}var te=class{constructor(e={},t){this.provider="pcivault";this.container=null;this.messageHandler=null;this.actionOverlay=null;this.threeDsReturnHandler=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.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 _({billingApiUrl:Pe(e.billingApiUrl),sdkVersion:De}):void 0)}async mount(e,t){this.ownsTelemetryReporter&&!this.telemetryReporter&&(this.telemetryReporter=new _({billingApiUrl:Pe(this.config.billingApiUrl),sdkVersion:De}));let r=this.telemetryReporter;if(this.config.operation==="card_setup"&&r&&this.setupTelemetryReporter!==r){this.setupTelemetryReporter=r;try{r.beginCheckout({checkoutMode:"setup"})}catch{}}if(this.mountStartedAt=this.telemetryReporter?.now?.()??b(),this.vaultReadyReported=!1,this.submissionStarted=!1,this.submissionStartedAt=null,typeof window>"u"||typeof document>"u")throw this.reportVaultLoadFailure(),new Ie("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 Ie("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.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(),F(B("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?.()??b())-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 r=this.listeners.get(e);return r||(r=new Set,this.listeners.set(e,r)),r.add(t),()=>{this.listeners.get(e)?.delete(t)}}unmount(){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 r=Array.from(e.querySelectorAll("script"));for(let s of r){let o=document.createElement("script");for(let i of Array.from(s.attributes))o.setAttribute(i.name,i.value);o.text=s.text,s.replaceWith(o)}}attachMessageListener(){if(this.messageHandler)return;let e=t=>{if(this.expectedOrigin&&t.origin!==this.expectedOrigin)return;let r=t.data;if(Bt(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;this.applyHeight(r.height);return}if(Ht(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;let u=r.messages.filter(c=>typeof c=="string"&&c.trim()).join(" ");this.emit("validation",{sessionId:this.config.sessionId,message:u||void 0});return}if(!Vt(r)||this.messageToken&&r.messageToken!==this.messageToken)return;let s=this.config.sessionId,o=typeof r.sessionId=="string"?r.sessionId:void 0;if(s&&o&&o!==s||(r.type==="complete"||r.type==="decline")&&s&&o!==s)return;let i=zt(r.paymentMethod),a={...r.sessionId??this.config.sessionId?{sessionId:r.sessionId??this.config.sessionId}:{},...r.outcome?{outcome:r.outcome}:{},...r.paymentId?{paymentId:r.paymentId}:{},...r.authorizationExpiresAt?{authorizationExpiresAt:r.authorizationExpiresAt}:{},...r.failureOutcome?{failureOutcome:r.failureOutcome}:{},...r.intentId?{intentId:r.intentId}:{},...r.declineReason?{declineReason:r.declineReason}:{},...r.message?{message:r.message}:{},...i?{paymentMethod:i}:{}};r.type==="submitting"&&(this.submissionStarted=!0,this.submissionStartedAt=this.telemetryReporter?.now?.()??b()),F(Nt(r,this.submissionStarted,this.config.captureMethod,this.config.operation)),this.reportOutcome(r),r.type==="ready"&&(this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),this.postSubmitLabel()),r.type==="action_required"&&r.nextActionRedirectUrl&&this.showActionRequiredOverlay(r.nextActionRedirectUrl),(r.type==="complete"||r.type==="decline"||r.type==="error"||r.type==="submitting")&&this.hideActionRequiredOverlay(),r.type!=="action_required"&&this.emit(r.type,a)};this.messageHandler=e,window.addEventListener("message",e)}reportOutcome(e){let t=this.telemetryReporter;if(!t)return;let{type:r}=e;if(r==="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"})),r==="complete"||r==="decline"){t.log({name:"vault.terminal",stage:"completion",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:Ue(e,this.config.captureMethod,this.config.operation),provider:"pcivault",paymentMethodCategory:"card"});return}if(r==="error"){let i=Fe(this.submissionStarted,e);t.log({name:"vault.terminal",stage:i.stage,provider:"pcivault",paymentMethodCategory:"card"}),t.error({...i,provider:"pcivault",paymentMethodCategory:"card"});return}if(r==="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 i=this.submissionStartedAt;this.submissionStartedAt=null,i!==null&&t.performance({stage:"three_ds_handoff",durationMs:Math.max(0,t.now()-i),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:"action_required",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"});return}let[s,o]=xe[r];t.log({name:s,stage:o,provider:"pcivault",paymentMethodCategory:"card"})}applyTheme(e){this.theme=e,this.postTheme()}postTheme(){this.theme!==void 0&&this.postToHostedWindow({source:"flopay-vault-host",type:"theme",theme:this.theme},this.directiveTargetOrigin())}setSubmitGate(e){this.submitGateBlocked=e,this.postSubmitGate()}postSubmitGate(){this.postToHostedWindow({source:"flopay-vault-host",type:"gate",blocked:this.submitGateBlocked},this.directiveTargetOrigin())}setCardFieldOrder(e,t){this.cardFieldOrder=e,this.cardAutoFocus=t,this.postCardFieldOrder()}postCardFieldOrder(){this.postToHostedWindow({source:"flopay-vault-host",type:"fieldOrder",order:this.cardFieldOrder,autoFocus:this.cardAutoFocus},this.directiveTargetOrigin())}setSubmitLabel(e){this.submitLabel=e,this.postSubmitLabel()}postSubmitLabel(){let e=this.submitLabel,t=this.config.sessionId,{messageToken:r,expectedOrigin:s}=this;e===void 0||!t||!r||!s||this.postToHostedWindow({source:"flopay-vault-host",type:"submitLabel",sessionId:t,messageToken:r,label:e},s)}hostedWindow(){return this.container?.querySelector("iframe")?.contentWindow??null}postToHostedWindow(e,t){let r=this.hostedWindow();if(r)try{r.postMessage(e,t)}catch{}}directiveTargetOrigin(){return this.expectedOrigin??"*"}emit(e,t){for(let r of this.listeners.get(e)??[])r(t)}showActionRequiredOverlay(e){if(typeof document>"u")return;if(this.actionOverlay){let i=this.actionOverlay.querySelector("iframe");i instanceof HTMLIFrameElement&&i.src!==e&&(i.src=e),this.armActionRequiredTimeout();return}this.actionOverlayPreviousFocus=document.activeElement instanceof HTMLElement?document.activeElement:null;let t=document.createElement("div");t.setAttribute("data-flopay-action-required","1"),t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-label","Card authentication"),t.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 r=document.createElement("iframe");r.setAttribute("title","Card authentication"),r.setAttribute("allow","payment"),r.tabIndex=0,r.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(";"),r.src=e,t.appendChild(r);let s=document.createElement("button");s.type="button",s.setAttribute("aria-label","Close card authentication"),s.textContent="\xD7",s.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(";"),s.addEventListener("click",()=>this.abandonActionRequiredOverlay()),t.appendChild(s),t.addEventListener("click",i=>{i.target===t&&this.abandonActionRequiredOverlay()});let o=i=>{if(i.source!==r.contentWindow)return;let a=i.data;!a||typeof a!="object"||a.source!=="flopay-vault-3ds-return"||(F(B("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",o),this.threeDsReturnHandler=o,document.body.appendChild(t),this.actionOverlay=t,r.focus(),this.armActionRequiredTimeout(),F(B("vault.three_ds.handoff","three_ds_handoff"))}armActionRequiredTimeout(){this.actionOverlayTimer&&clearTimeout(this.actionOverlayTimer),this.actionOverlayTimer=setTimeout(()=>{this.actionOverlayTimer=null,this.actionOverlay&&this.timeOutActionRequiredOverlay()},xt)}reportChallengeAbandoned(){F(Oe({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(){this.reportChallengeAbandoned(),this.hideActionRequiredOverlay(),this.emit("error",{...this.config.sessionId?{sessionId:this.config.sessionId}:{},message:Ft})}abandonActionRequiredOverlay(){this.actionOverlay&&(this.reportChallengeAbandoned(),this.hideActionRequiredOverlay(),this.emit("challenge_dismissed",{...this.config.sessionId?{sessionId:this.config.sessionId}:{}}))}hideActionRequiredOverlay(){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 r=Math.max(0,Math.min(Math.ceil(e),2e3));t.style.height=`${r}px`}};function sr(n,e){let t=te;return new t(n,{reporter:e})}export{ie as a,ae as b,w as c,L as d,G as e,se as f,oe as g,b as h,_ as i,Rt as j,Z as k,er as l,te as m,sr as n};