@flopay/js 1.4.20 → 1.4.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +9 -3
- package/dist/index.d.ts +9 -3
- package/dist/index.mjs +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -410,6 +410,15 @@ card fields, its own submit button, card tokenization, the PaymentIntent (create
|
|
|
410
410
|
on the card path** and PAN / CVC never enter the SDK runtime. The SDK's only job
|
|
411
411
|
is to inject the widget HTML and relay its terminal `postMessage` outcome.
|
|
412
412
|
|
|
413
|
+
For a merchant-server-created no-charge setup session, `@flopay/react` uses
|
|
414
|
+
the same adapter with `operation: 'card_setup'`. A valid terminal `complete`
|
|
415
|
+
message may include `paymentMethod`, a reconstructed display-only object with
|
|
416
|
+
FloPay id, brand, last four, expiry, and status. Unknown or malformed nested
|
|
417
|
+
fields are dropped. During a mixed backend rollout the field may be absent; the
|
|
418
|
+
result stays bound to the setup session and the SDK never invents an id. Setup
|
|
419
|
+
terminal telemetry uses `card_setup_succeeded` / `card_setup_declined`, not
|
|
420
|
+
payment-success outcomes.
|
|
421
|
+
|
|
413
422
|
```ts
|
|
414
423
|
// 1. Obtain the vault capture block — use an embedded block when supplied, or
|
|
415
424
|
// fetch it through the explicit recovery route for a session whose Stripe
|
|
@@ -453,7 +462,7 @@ mount (including buyer time on a payment-method picker) is excluded. Duplicate
|
|
|
453
462
|
`CardCaptureAdapter` methods: `mount(container, { html, messageToken?, expectedOrigin? })`,
|
|
454
463
|
`on(event, handler)` (`'ready' | 'complete' | 'decline' | 'error'`), `unmount()`.
|
|
455
464
|
Outcome events arrive via a `window.postMessage` from the widget shaped
|
|
456
|
-
`{ source: 'flopay-vault', type, sessionId, messageToken?, intentId?, declineReason?, message? }`.
|
|
465
|
+
`{ source: 'flopay-vault', type, sessionId, messageToken?, intentId?, declineReason?, message?, paymentMethod? }`.
|
|
457
466
|
The widget is injected **same-window**, so `source` alone is forgeable: the
|
|
458
467
|
adapter rejects terminal `complete` / `decline` outcomes that are not bound to
|
|
459
468
|
the mounted `sessionId`, that mismatch the mounted `messageToken` (when one was
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var ge=Object.defineProperty;var lt=Object.getOwnPropertyDescriptor;var ct=Object.getOwnPropertyNames;var dt=Object.prototype.hasOwnProperty;var ut=(n,e)=>{for(var t in e)ge(n,t,{get:e[t],enumerable:!0})},pt=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ct(e))!dt.call(n,o)&&o!==t&&ge(n,o,{get:()=>e[o],enumerable:!(r=lt(e,o))||r.enumerable});return n};var mt=n=>pt(ge({},"__esModule",{value:!0}),n);var Gt={};ut(Gt,{FloPay:()=>X,FloPayElements:()=>H,PaymentAPI:()=>I,PciVaultCardCapture:()=>L,SESSION_CREATE_TELEMETRY:()=>_e,StripeAdapter:()=>K,cacheSessionDisplayData:()=>F,clearSessionDisplayData:()=>ce,createCheckoutSession:()=>tt,createCheckoutSessionWithRetries:()=>st,dropThirdPartyOnlyError:()=>it.dropThirdPartyOnlyError,getSessionDisplayData:()=>le,loadFloPay:()=>Xe,toStripeAppearance:()=>ze,toStripeAppearanceTheme:()=>J});module.exports=mt(Gt);var E=require("@flopay/shared");var Ve=require("@stripe/stripe-js"),f=require("@flopay/shared");var d=require("@flopay/shared");function x(n){return typeof n=="string"&&n.trim()?n:void 0}function Pe(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}var yt="flopay_session_display:";var ie=new Map;function ae(n){return`${yt}${n}`}function fe(){if(typeof window>"u")return null;try{return window.sessionStorage}catch{return null}}function F(n,e,t){if(!n)return;let r=t?.ttlMs??36e5,o={data:e,expiresAt:Date.now()+r},s=fe();if(s)try{s.setItem(ae(n),JSON.stringify(o));return}catch{}ie.set(n,o)}function le(n){if(!n)return null;let e=fe();if(e)try{let r=e.getItem(ae(n));if(r){let o=JSON.parse(r);if(o&&typeof o.expiresAt=="number"&&o.expiresAt>Date.now())return o.data;e.removeItem(ae(n))}}catch{}let t=ie.get(n);if(t){if(t.expiresAt>Date.now())return t.data;ie.delete(n)}return null}function ce(n){if(!n)return;ie.delete(n);let e=fe();if(e)try{e.removeItem(ae(n))}catch{}}var S=require("@flopay/shared"),ht="/v1/sdk-telemetry/events",Ce=16,gt=64,ft=1500,Ee=1e3,Ct=64,vt="00000000-0000-4000-8000-000000000000",Tt={technical_error:8,lifecycle:32,expected_outcome:32,performance:24};function z(){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]&15|64,n[8]=n[8]&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 _t(n){try{return new TextEncoder().encode(n).byteLength}catch{return n.length}}function wt(n){return JSON.stringify([n.code,n.failureCategory,n.stage,n.provider,n.attempt,n.statusClass,n.requestCategory,n.paymentMethodCategory,n.checkoutMode,n.layout])}function M(){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.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(/\/+$/,"")}${ht}`,this.sdkPackage=e.sdkPackage??"@flopay/js",this.sdkVersion=e.sdkVersion,this.correlationId=z(),this.merchantEnabled=e.enabled!==!1,this.clock=e.clock??M,this.browserTransportAvailable=typeof window<"u"&&typeof document<"u",this.browserTransportAvailable&&(window.addEventListener("pagehide",this.pageExitHandler),document.addEventListener("visibilitychange",this.visibilityHandler))}log(e){this.canCollect()&&this.enqueue((0,S.buildTelemetryLogEvent)({...this.checkoutContext,...e,eventId:z(),sequence:this.sequence++}))}error(e){if(!this.canCollect())return;let t=(0,S.buildTelemetryErrorEvent)({...this.checkoutContext,...e,eventId:vt,sequence:0}),r=wt(t),o=this.now();this.pruneReportedFailures(o);let s=this.reportedFailures.get(r);if(s!==void 0&&o>=s&&o-s<Ee){this.log({name:"operation.deduplicated",stage:e.stage,provider:e.provider,paymentMethodCategory:e.paymentMethodCategory,attempt:e.attempt});return}this.rememberReportedFailure(r,o),this.enqueue((0,S.buildTelemetryErrorEvent)({...this.checkoutContext,...e,eventId:z(),sequence:this.sequence++}))}performance(e){this.canCollect()&&this.enqueue((0,S.buildTelemetryPerformanceEvent)({...this.checkoutContext,...e,eventId:z(),sequence:this.sequence++}))}terminal(e){if(this.canCollect()&&(this.enqueue((0,S.buildTelemetryTerminalEvent)({...this.checkoutContext,...e,eventId:z(),sequence:this.sequence++})),e.outcome!=="action_required"&&this.checkoutStartedAt!==null)){let t=this.checkoutStartedAt;this.checkoutStartedAt=null,this.performance({stage:"total_journey",durationMs:Math.max(0,this.now()-t),durationMode:"total",provider:e.provider,paymentMethodCategory:e.paymentMethodCategory})}}now(){try{return this.clock()}catch{return M()}}pruneReportedFailures(e){for(let[t,r]of this.reportedFailures)(e<r||e-r>=Ee)&&this.reportedFailures.delete(t)}rememberReportedFailure(e,t){for(;this.reportedFailures.size>=Ct;){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>=gt||this.eventCounts[e.class]>=Tt[e.class])){if(this.eventCounts[e.class]+=1,this.queue.push(e),this.queue.length>=Ce){this.flush();return}this.scheduleFlush()}}canCollect(){return this.browserTransportAvailable&&this.merchantEnabled&&!this.ingestionDisabled&&!this.destroyed}async flush(){if(this.flushInFlight)return this.flushInFlight;if(!this.browserTransportAvailable||this.destroyed||this.ingestionDisabled||this.queue.length===0)return;this.clearFlushTimer();let e=this.queue.splice(0,Ce);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())}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,Ce);this.sendBatch(e)}}async sendBatch(e){if(!this.browserTransportAvailable||this.ingestionDisabled)return;let t=(0,S.serializeTelemetryBatch)(e,{correlationId:this.correlationId,sdkPackage:this.sdkPackage,sdkVersion:this.sdkVersion,batchId:z()});if(_t(t)>S.TELEMETRY_MAX_BATCH_BYTES)return;let r=typeof AbortController>"u"?null:new AbortController,o=null;try{let s=fetch(this.endpoint,{method:"POST",headers:{"content-type":"text/plain;charset=UTF-8"},body:t,credentials:"omit",keepalive:!0,referrerPolicy:"no-referrer",signal:r?.signal}).then(async a=>a.status!==202?null:(await a.json().catch(()=>null))?.status==="disabled"?"disabled":null).catch(()=>null),i=new Promise(a=>{o=setTimeout(()=>{r?.abort(),a(null)},ft)});await Promise.race([s,i])==="disabled"&&this.disableFromIngestion()}catch{}finally{o&&clearTimeout(o)}}disableFromIngestion(){this.ingestionDisabled=!0,this.queue.splice(0),this.reportedFailures.clear(),this.clearFlushTimer()}scheduleFlush(){this.flushTimer||this.destroyed||this.ingestionDisabled||(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush()},0))}clearFlushTimer(){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null)}},Re=Symbol.for("@flopay/js.telemetry.reporter-factory.v1"),Ae=globalThis;Ae[Re]===void 0&&Object.defineProperty(Ae,Re,{configurable:!0,enumerable:!1,writable:!1,value:n=>new _(n)});function O(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 St(){return Object.assign(new Error("The operation was aborted."),{name:"AbortError"})}function B(n,e){let t=150*2**n,r=Math.round(t*(.75+Math.random()*.5));return new Promise((o,s)=>{let i,l=()=>e.removeEventListener("abort",a),a=()=>{i!==void 0&&clearTimeout(i),l(),s(St())};if(e.aborted){a();return}i=setTimeout(()=>{l(),o()},r),e.addEventListener("abort",a,{once:!0})})}var Ie=1e3,bt=500,Mt=15e3,kt=3e3,Pt=1e4,Et=1e4;function Rt(n){return typeof n=="object"&&n!==null}function j(n,e){return x(n?.[e])}function De(n,e){return Pe(n?.[e])}function At(n,e){let t=n?.[e];return typeof t=="number"&&Number.isFinite(t)?t:void 0}function Fe(n){return new Promise(e=>setTimeout(e,n))}function de(){return new d.FloPayError("Checkout is still processing. Please try again shortly.","api_error",{code:"checkout_processing_timeout"})}async function q(n,e){let t=await n.json().catch(()=>null),r=Rt(t?.error)?t.error:null,o=De(t,"message")??De(r,"message")??e,s=j(t,"code")??j(t,"gatewayErrorCode")??j(r,"code")??`http_${n.status}`;return new d.FloPayError(o,"api_error",{code:s,statusCode:n.status})}async function It(n){let e=n.status===400?await n.clone().json().catch(()=>null):null;return(0,d.classifyPaymentRejection)(n.status,e)}function xe(n){return n===400||n===422}var ue=2;async function Te(n,e,t=ue,r){let o;for(let s=0;;s++)try{return await fetch(n,e)}catch(i){if(e?.signal?.aborted||i instanceof Error&&i.name==="AbortError")throw i;if(o=i,s>=t)throw o;try{r?.(s+1)}catch{}await Fe(150*2**s)}}var _e=Symbol.for("@flopay/js.session-create.telemetry.v1");function Dt(n){return n[_e]}function xt(n){return"now"in n||"onFirstByte"in n||"onSessionCreateFailure"in n||"onRetry"in n}function Oe(n){return{userId:n.userId,firstName:n.firstName??null,lastName: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 qe(n,e){e.tagsData&&(n.tagsData=e.tagsData),e.utmMetadata?.length&&(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 Ft(n,e){let t={clientId:n.clientId,checkoutVersion:d.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}),qe(t,n),t}function Ot(n,e,t){return{currency:e,products:t.map(r=>(0,d.buildProductPayload)(r,e)),couponCodes:n.couponCodes??[],accountData:Oe(n.account)}}var U=class U{constructor(e,t={}){this.baseUrl=e.replace(/\/+$/,"");let r=xt(t);this.telemetryHooks=r?t:void 0,this.directTelemetry=r||t.telemetry===!1?void 0:new _({billingApiUrl:this.baseUrl,sdkVersion:d.SDK_VERSION})}destroy(){this.directTelemetry?.destroy()}reportDirectFailure(e,t,r,o,s="unknown"){let i=(0,d.classifyTelemetryFailure)(e,t);this.directTelemetry?.error({...i,stage:r,requestCategory:o,paymentMethodCategory:s})}reportAccountSnapshotFailure(e,t){let r=(0,d.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()??M()}catch{return M()}}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){this.beginDirectTelemetryCheckout(e);let r=this.telemetryTimestamp();this.directTelemetry?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let o={[d.FLO_SDK_VERSION_HEADER]:d.SDK_VERSION};t&&(o["x-checkout-session-token"]=t);try{let s=await Te(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}`,{headers:o},ue,c=>{this.telemetryHooks?.onRetry?.("session_read",c),this.directTelemetry?.log({name:"operation.retry",stage:"session_read",requestCategory:"session_read",attempt:c})}),i=Math.max(0,this.telemetryTimestamp()-r);try{this.telemetryHooks?.onFirstByte?.(i)}catch{}let l=`${Math.floor(s.status/100)}xx`;if(this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:l}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:i,durationMode:"machine",requestCategory:"session_read",statusClass:l}),!s.ok)throw await q(s,"Failed to get checkout session");let a=await s.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()-r),durationMode:"machine",requestCategory:"session_read",statusClass:l}),{...a,data:this.mergeCachedDisplayData(a.data)}}catch(s){throw this.directTelemetry?.error({...(0,d.classifyTelemetryFailure)(s,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"}),s}}cacheSessionDisplayData(e,t,r){F(e,t,r)}clearSessionDisplayData(e){ce(e)}async getVaultCapture(e,t){let r=`${this.baseUrl}\0${e}\0${t??""}`,o=U.activeVaultCaptureRequests.get(r);if(o)return o;let s=this.requestVaultCapture(e,t);U.activeVaultCaptureRequests.set(r,s);try{return await s}finally{U.activeVaultCaptureRequests.get(r)===s&&U.activeVaultCaptureRequests.delete(r)}}async requestVaultCapture(e,t){let r=new AbortController,o=setTimeout(()=>r.abort(),Et);this.beginDirectTelemetryCheckout(e);let s=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 l=await Te(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/vault/capture`,{method:"POST",headers:i,signal:r.signal},ue,c=>{this.telemetryHooks?.onRetry?.("vault_capture",c),this.directTelemetry?.log({name:"operation.retry",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card",attempt:c})});if(!l.ok)throw await q(l,"Failed to load the secure card form");let a=await l.json();return this.directTelemetry?.performance({stage:"vault_request",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"2xx"}),this.toVaultBlock(a)}catch(l){let a=r.signal.aborted?new d.FloPayError("Timed out while loading the secure card form. Please try again.","api_error",{code:"vault_capture_timeout"}):l;throw this.reportDirectFailure(a,"VAULT_LOAD_FAILED","vault_request","vault_capture","card"),a}finally{clearTimeout(o)}}async getUnifiedCheckoutSession(e,t){let r=await this.getCheckoutSession(e,t),o=this.normalizeRawSession(r.data),s=r.vault;return s&&o.data.session&&(o.data.session.vault=this.toVaultBlock(s)),o}async processPayment(e,t,r){if(this.beginDirectTelemetryCheckout(t.sessionId),!t.nonce)throw this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"process_payment"}),new d.FloPayError("processPayment requires `nonce` \u2014 pass the value returned from session creation.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let o=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.processing.started",stage:"processing",requestCategory:"process_payment"});let{nonce:s,...i}=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":s},body:JSON.stringify(i)})}catch(a){throw this.reportDirectFailure(a,"PAYMENT_PROCESSING_FAILED","processing","process_payment"),a}if(!l.ok&&l.status!==202){let a=await It(l);return a?this.directTelemetry?.terminal({outcome:a,stage:"processing",requestCategory:"process_payment",statusClass:"4xx"}):this.directTelemetry?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",requestCategory:"process_payment",statusClass:(0,d.telemetryStatusClass)(l.status),failureCategory:l.status>=500?"server_error":void 0}),l}try{let a=await this.resolveProcessResponse(l,t.sessionId,{...r,nonce:s});return this.directTelemetry?.log({name:"payment.processing.completed",stage:"processing",requestCategory:"process_payment",statusClass:(0,d.telemetryStatusClass)(a.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"process_payment",statusClass:(0,d.telemetryStatusClass)(a.status)}),a}catch(a){throw a instanceof d.FloPayError&&a.code==="checkout_processing_timeout"||this.reportDirectFailure(a,"PAYMENT_PROCESSING_FAILED","processing","process_payment"),a}}async patchAccountSnapshot(e,t,r,o){this.beginDirectTelemetryCheckout(e);let s=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.state_transition",stage:"processing",requestCategory:"account_snapshot"});let i=o?.timeoutMs??Pt,l=new AbortController,a=()=>l.abort();o?.signal&&(o.signal.aborted?l.abort():o.signal.addEventListener("abort",a,{once:!0}));let c=setTimeout(()=>l.abort(),i);try{let u;try{u=await Te(`${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:l.signal},ue,y=>{this.telemetryHooks?.onRetry?.("account_snapshot",y),this.directTelemetry?.log({name:"operation.retry",stage:"processing",requestCategory:"account_snapshot",attempt:y})})}finally{clearTimeout(c),o?.signal?.removeEventListener("abort",a)}if(!u.ok)throw await q(u,"Failed to persist account snapshot");this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"account_snapshot",statusClass:"2xx"})}catch(u){throw this.reportAccountSnapshotFailure(u,o?.telemetryMode??"blocking"),u}}async createSessionIntent(e,t,r,o){if(!t)throw new d.FloPayError("createSessionIntent requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let s=r,i=s.paymentMethodType,l=typeof i=="string"&&i.trim().toLowerCase()==="card",a=typeof i=="string"&&i.length>0&&!l&&(typeof s.paymentMethodId=="string"||s.paymentMethodId===null),c=s.provider==="stripe"&&(s.paymentMethodCategory==="wallet"||s.paymentMethodCategory==="apm")&&(s.intentKind==="payment"||s.intentKind==="setup"),u=s.provider==="paypal"&&s.paymentMethodCategory==="wallet"&&s.paymentMethodType==="paypal"&&s.paymentMethodId===null&&s.intentKind==="payment";if(!a||!c&&!u)throw new d.FloPayError("Only wallet, APM, and PayPal session intents are supported.","validation_error",{code:"InvalidSessionIntentRequest"});let y=s.authorizationAttemptId;if(y!==void 0&&!(0,d.isUuidV4)(y))throw new d.FloPayError("authorizationAttemptId must be a v4 UUID identifying one buyer authorization attempt.","validation_error",{code:"InvalidAuthorizationAttemptId",param:"authorizationAttemptId"});let p=(0,d.isUuidV4)(y)?y:(0,d.randomUuidV4)();this.beginDirectTelemetryCheckout(e);let m=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.intent.started",stage:"processing",requestCategory:"intent_create"});let k={"Content-Type":"application/json","x-checkout-session-token":t,[d.IDEMPOTENCY_KEY_HEADER]:o?.idempotencyKey||p},w=!1;try{let b=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents`,{method:"POST",headers:k,body:JSON.stringify({...r,authorizationAttemptId:p}),signal:o?.signal});if(!b.ok){w=!0;let W=await q(b,"Failed to create checkout intent"),te=(0,d.classifyTelemetryFailure)(W,"PAYMENT_PROCESSING_FAILED");throw xe(W.statusCode)?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"intent_create",statusClass:"4xx"}):this.directTelemetry?.error({...te,stage:"processing",requestCategory:"intent_create"}),W}let Y=(await b.json()).data;if(!Y||typeof Y!="object")throw new d.FloPayError("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});let g=Y,Z=g.paymentMethodType,ee=(g.paymentMethodCategory==="wallet"||g.paymentMethodCategory==="apm")&&typeof Z=="string"&&Z.trim().toLowerCase()!=="card"&&(typeof g.paymentMethodId=="string"||g.paymentMethodId===null)&&typeof g.providerObjectId=="string",D=g.provider==="stripe"&&(g.intentKind==="payment"||g.intentKind==="setup")&&typeof g.clientSecret=="string",R=g.provider==="paypal"&&g.paymentMethodCategory==="wallet"&&g.paymentMethodType==="paypal"&&g.paymentMethodId===null&&g.intentKind==="payment"&&(g.providerObjectType==="order"||g.providerObjectType==="subscription")&&g.clientSecret===null,N=g.provider===r.provider&&g.paymentMethodCategory===r.paymentMethodCategory&&g.paymentMethodType===r.paymentMethodType&&g.paymentMethodId===r.paymentMethodId&&g.intentKind===r.intentKind;if(!ee||!D&&!R||!N)throw new d.FloPayError("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});return this.directTelemetry?.log({name:"payment.intent.completed",stage:"processing",requestCategory:"intent_create",statusClass:(0,d.telemetryStatusClass)(b.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-m),durationMode:"machine",requestCategory:"intent_create",statusClass:(0,d.telemetryStatusClass)(b.status)}),g}catch(b){throw w||this.reportDirectFailure(b,"PAYMENT_PROCESSING_FAILED","processing","intent_create"),b}}async reportSessionIntentDecline(e,t,r,o){if(!t)throw new d.FloPayError("reportSessionIntentDecline requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let s=r,i=s.providerDeclineReason,l=s.paymentMethodType,a=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),c=typeof l=="string"&&l.length>0&&l.trim().toLowerCase()!=="card"&&a,u=s.provider==="stripe"&&(s.paymentMethodCategory==="wallet"||s.paymentMethodCategory==="apm"),y=s.provider==="paypal"&&s.paymentMethodCategory==="wallet"&&s.paymentMethodType==="paypal";if(!c||!u&&!y)throw new d.FloPayError("Invalid non-card decline classification.","validation_error",{code:"InvalidSessionIntentDeclineRequest"});let p=y?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:i}:{provider:"stripe",paymentMethodCategory:s.paymentMethodCategory,paymentMethodType:s.paymentMethodType,providerDeclineReason:i},m=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents/decline`,{method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":t},body:JSON.stringify(p),signal:o?.signal});if(!m.ok)throw await q(m,"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 o=t?.page??1,s=t?.limit??1,i=new URLSearchParams({email:e,page:String(o),limit:String(s),sortField:"createdAt",sortDirection:"DESC"});try{let l=await fetch(`${this.baseUrl}/v1/payments?${i.toString()}`,{method:"GET",signal:t?.signal,keepalive:!0});if(!l.ok)throw new d.FloPayError("Failed to fetch payments","api_error",{statusCode:l.status});let a=await l.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"}),a}catch(l){throw this.reportDirectFailure(l,"RECOVERY_FAILED","recovery","other","saved"),l}}async createAndFetchSession(e){if((0,d.isDetachedSessionEligible)(e))return(await this.createDetachedSession(e)).claimed;this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp(),r=O(e.timeoutMs??12e3),o={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});try{let s=await this.createAndFetchSessionRequest(e,t,r.signal,o);return this.adoptDirectTelemetryCheckout(s.data.session?.id),this.directTelemetry?.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:o.statusClass}),this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:"session_create",statusClass:o.statusClass,attempt:o.attempt}),s}catch(s){throw this.reportSessionCreateFailure(s,t,o),s}finally{r.clear()}}async createAndFetchSessionRequest(e,t,r,o){let s=e.products??(0,d.foldIntoProducts)(e.items,e.subscriptions);(0,d.assertCaptureMethodEligible)({captureMethod:e.captureMethod,products:s});let i=(0,d.resolveSessionCurrency)(e.currency,e.items,e.subscriptions,s);if(!i)throw new d.FloPayError("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});let l={clientId:e.clientId,checkoutVersion:d.SDK_VERSION,successUrl:e.successUrl,cancelUrl:e.cancelUrl,currency:i,checkoutMode:e.checkoutMode??"full",products:s.map(p=>(0,d.buildProductPayload)(p,i)),accountData:Oe(e.account),couponCodes:e.couponCodes??[]};e.captureMethod==="manual"&&(l.captureMethod=e.captureMethod),e.tokenizedData&&(l.tokenizedData=e.tokenizedData),qe(l,e);let c=await(await this.postCheckoutSessionCreate(l,e,t,r,o)).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 u=c.data?.uuid;if(!u)throw new d.FloPayError("No session ID returned","api_error",{code:"InvalidCheckoutSessionResponse"});return this.autoCacheDisplayData(u,e),this.adoptDirectTelemetryCheckout(u),{...await this.getUnifiedCheckoutSession(u),autoProcessingError:c.autoProcessingError,autoProcessingAttempted:c.autoProcessingAttempted,autoProcessingPending:c.autoProcessingPending}}async postCheckoutSessionCreate(e,t,r,o,s){let i={"Content-Type":"application/json",[d.FLO_SDK_VERSION_HEADER]:d.SDK_VERSION},l=(0,d.resolveIdempotencyKey)(t.idempotencyKey);l&&(i[d.IDEMPOTENCY_KEY_HEADER]=l);let a,c=!1,u=Dt(t),y=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;try{u?.onAttempt?.(p)}catch{}try{a=await fetch(`${this.baseUrl}/v1/checkouts/sessions?expand=true`,{method:"POST",headers:i,body:JSON.stringify(e),signal:o})}catch(w){if(s.statusClass=o.aborted||w instanceof Error&&w.name==="AbortError"?"timeout":"network_error",o.aborted||w instanceof Error&&w.name==="AbortError"||p>=2)throw w;let b=p+1;y(b),await B(p,o);continue}let m=(0,d.telemetryStatusClass)(a.status);if(s.statusClass=m,c||(c=!0,this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:m,attempt:p}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:Math.max(0,this.telemetryTimestamp()-r),durationMode:"machine",requestCategory:"session_create",statusClass:m,attempt:p})),a.status===204)throw new d.FloPayError("Session auto-completed \u2014 payment method already on file","api_error",{code:"session_auto_completed"});if(a.ok)break;let k=await q(a,"Failed to create checkout session");if(k.code===d.IDEMPOTENCY_IN_PROGRESS_CODE&&p<2){y(p+1),await B(p,o);continue}throw k}if(!a)throw new TypeError("Checkout-session creation exhausted its retry budget.");return a}async createDetachedSession(e){this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp(),r=O(e.timeoutMs??12e3),o={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let s=e.products??(0,d.foldIntoProducts)(e.items,e.subscriptions);try{(0,d.assertCaptureMethodEligible)({captureMethod:e.captureMethod,products:s})}catch(m){throw r.clear(),this.reportSessionCreateFailure(m,t,o),m}let i=(0,d.resolveSessionCurrency)(e.currency,e.items,e.subscriptions,s);if(!i)throw r.clear(),this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),new d.FloPayError("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});let l;try{l=Ot(e,i,s)}catch(m){throw r.clear(),this.reportSessionCreateFailure(m,t,o),m}let a,c;try{if(c=await(await this.postCheckoutSessionCreate(Ft(e,i),e,t,r.signal,o)).json(),!c.data||!("gateways"in c.data))throw new d.FloPayError("The billing API returned no session shell for a detached create. It must support `deferDataAttachment` (TeamFloPay/backend#1099).","api_error",{code:"InvalidCheckoutSessionResponse"});a=this.normalizeRawSession(this.mergeCachedDisplayData(c.data)),c.vault&&a.data.session&&(a.data.session.vault=this.toVaultBlock(c.vault))}catch(m){throw r.clear(),this.reportSessionCreateFailure(m,t,o),m}let u=a.data.session?.id??c.data.uuid??"",y=a.data.session?.clientSecret??c.data.nonce??"";if(!u||!y){r.clear();let m=new d.FloPayError("Checkout session shell was created without a session id or nonce.","api_error",{code:"InvalidCheckoutSessionResponse"});throw this.reportSessionCreateFailure(m,t,o),m}this.adoptDirectTelemetryCheckout(u),this.directTelemetry?.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",statusClass:o.statusClass,paymentMethodCategory:"card"}),this.directTelemetry?.performance({stage:"session_shell",durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:"session_create",statusClass:o.statusClass,attempt:o.attempt,paymentMethodCategory:"card"});let p=this.claimCheckoutSession(u,y,l,{params:e,startedAt:t,deadline:r,createAttempt:o.attempt});return p.catch(()=>{}),{shell:a,sessionId:u,nonce:y,claimed:p}}async claimCheckoutSession(e,t,r,o){let s=o?.startedAt??this.telemetryTimestamp(),i=this.telemetryTimestamp(),l=o?.deadline??O(12e3),a=JSON.stringify(r),c="unknown",u=0;this.directTelemetry?.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"});try{let y;for(u=0;u<3;u++){try{y=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/claim`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":t,[d.FLO_SDK_VERSION_HEADER]:d.SDK_VERSION},body:a,signal:l.signal})}catch(k){let w=l.signal.aborted||k instanceof Error&&k.name==="AbortError";if(c=w?"timeout":"network_error",w||u>=2)throw k;try{this.telemetryHooks?.onRetry?.("session_claim",u+1),this.directTelemetry?.log({name:"operation.retry",stage:"session_claim",requestCategory:"session_claim",attempt:u+1})}catch{}await B(u,l.signal);continue}if(c=(0,d.telemetryStatusClass)(y.status),y.ok)break;throw await q(y,"Failed to attach checkout session data")}if(!y)throw new TypeError("Checkout-session claim exhausted its retry budget.");let p=await y.json();if(!p.data||!p.data.gateways)throw new d.FloPayError("The billing API returned no checkout session with gateways after claiming it.","api_error",{code:"InvalidCheckoutSessionResponse"});o?.params&&this.autoCacheDisplayData(p.data.uuid??e,o.params);let m=this.normalizeRawSession(this.mergeCachedDisplayData(p.data));return p.vault&&m.data.session&&(m.data.session.vault=this.toVaultBlock(p.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:u}),this.directTelemetry?.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:c}),this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"session_create",statusClass:c,attempt:o?.createAttempt??u}),m}catch(y){throw this.reportSessionCreateFailure(y,s,{attempt:u,statusClass:c},"session_claim"),y}finally{l.clear()}}reportSessionCreateFailure(e,t,r,o="session_create"){if(!(e instanceof d.FloPayError&&e.code==="session_auto_completed"))try{this.telemetryHooks?.onSessionCreateFailure?.(e)}catch{}let s=(0,d.classifyTelemetryFailure)(e,"CHECKOUT_SESSION_CREATE_FAILED");if(this.directTelemetry?.performance({stage:o,durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:o==="session_claim"?"session_claim":"session_create",statusClass:s.statusClass,attempt:r.attempt}),e instanceof d.FloPayError&&e.type==="validation_error"||e instanceof d.FloPayError&&xe(e.statusCode)){this.directTelemetry?.terminal({outcome:"validation_rejected",stage:o,requestCategory:o==="session_claim"?"session_claim":"session_create",...e.type==="validation_error"?{}:{statusClass:"4xx"}});return}e instanceof d.FloPayError&&e.code==="session_auto_completed"||this.directTelemetry?.error({...s,stage:o,requestCategory:o==="session_claim"?"session_claim":"session_create"})}async waitForCheckoutSessionCompletion(e,t){this.beginDirectTelemetryCheckout(e);let r=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:"saved"});let o=t?.timeoutMs??Mt,s=Date.now()+o,i=this.clampRetryAfterMs(t?.initialDelayMs??Ie),l=0;try{for(;;){let a=s-Date.now();if(a<=0)throw de();if(i>0){try{l+=1,this.telemetryHooks?.onRetry?.("session_read",l),this.directTelemetry?.log({name:"operation.retry",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:"saved",attempt:l})}catch{}if(await Fe(Math.min(i,a)),Date.now()>=s)throw de()}let c=await this.getUnifiedCheckoutSession(e,t?.nonce),u=c.data.session?.status;if(u==="authorized"||u==="complete"||u==="expired")return this.directTelemetry?.log({name:"operation.recovery.completed",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:"saved"}),this.directTelemetry?.performance({stage:"recovery",durationMs:Math.max(0,this.telemetryTimestamp()-r),durationMode:"machine",requestCategory:"session_read",paymentMethodCategory:"saved"}),c;if(Date.now()>=s)throw de();i=this.clampRetryAfterMs(Math.max(i*2,bt))}}catch(a){throw a instanceof d.FloPayError&&a.code==="checkout_processing_timeout"&&this.reportDirectFailure(a,"RECOVERY_FAILED","recovery","session_read","saved"),a}}normalizeRawSession(e){let t=e.gateways??{},r=[],o={session:this.toCheckoutSession(e)},s=t.stripe;if(s?.publishableKey){r.push("stripe");let a=[e.stripeClientSecret,s.stripeClientSecret].find(c=>typeof c=="string"&&c.length>0);o.stripe={clientSecret:a??"",publishableKey:s.publishableKey??void 0,paypalPublishableKey:s.paypalPublishableKey??void 0,environment:s.environment,enabledPaymentMethods:Array.isArray(s.enabledPaymentMethods)?s.enabledPaymentMethods.filter(c=>typeof c=="string"):void 0}}let i=t.paypal;return i?.publishableKey&&(r.push("paypal"),o.paypal={publishableKey:i.publishableKey,environment:i.environment}),{providers:r,mode:"tokenize",data:o,raw:{data:e}}}toCheckoutSession(e){let t=e.products??[],r=typeof e.totalAmount=="number"&&Number.isFinite(e.totalAmount),o=t.reduce((c,u)=>c+(u.overrideAmount??u.totalAmount??0),0),s=r?e.totalAmount:o,i=Math.round(s*100),l=e.currency??t[0]?.currency??"USD",a=t.some(c=>c.type==="subscription")?"subscription":"payment";return{id:e.uuid,clientSecret:e.nonce,mode:a,status:this.toCheckoutSessionStatus(e.status),amount:i,currency:l,captureMethod:e.captureMethod,paymentId:e.paymentId,authorizationExpiresAt:e.authorizationExpiresAt,failureOutcome:(0,d.normalizeCheckoutFailureOutcome)(e.outcome)??(0,d.normalizeCheckoutFailureOutcome)(e.failureReason)??(e.status==="expired"&&e.captureMethod==="manual"?"authorization_expired":void 0),customer:{id:e.accountData.userId,email:e.accountData.email,firstName:e.accountData.firstName,lastName:e.accountData.lastName,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},metadata:{},checkoutMode:e.checkoutMode,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 o=await e.json().catch(()=>null),s=this.toCheckoutProcessingPending(o,e,t),i=await this.waitForCheckoutSessionCompletion(s.sessionId,{initialDelayMs:s.retryAfterMs,timeoutMs:r?.pollTimeoutMs,nonce:r?.nonce});if(i.data.session?.status==="complete")return new Response(null,{status:204,statusText:"No Content"});if(i.data.session?.status==="authorized"){let l=i.data.session;return new Response(JSON.stringify({status:"authorized",paymentId:l.paymentId,sessionId:l.id||t,authorizationExpiresAt:l.authorizationExpiresAt}),{status:200,headers:{"Content-Type":"application/json"}})}if(i.data.session?.status==="expired"){let l=i.data.session.failureOutcome==="authorization_expired"||i.data.session.captureMethod==="manual";throw new d.FloPayError(l?"Authorization has expired.":"Checkout session has expired.","api_error",{code:l?"authorization_expired":"checkout_session_expired"})}throw de()}toCheckoutProcessingPending(e,t,r){let o=t.headers.get("Retry-After"),s=o===null||o.trim()===""?void 0:Number(o),i=s!==void 0&&Number.isFinite(s)?s*1e3:void 0;return{type:"checkout_processing",sessionId:j(e,"sessionId")??r,retryAfterMs:this.clampRetryAfterMs(At(e,"retryAfterMs")??i??Ie),statusUrl:j(e,"statusUrl"),sessionUrl:j(e,"sessionUrl")}}clampRetryAfterMs(e){return Math.max(0,Math.min(e,kt))}autoCacheDisplayData(e,t){if(!e)return;let r=t.products??(0,d.foldIntoProducts)(t.items,t.subscriptions);if(r.length===0&&!t.currency)return;let o=t.products!==void 0,s=(0,d.resolveSessionCurrency)(t.currency,o?void 0:t.items,o?void 0:t.subscriptions,r);F(e,{currency:s??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??s??void 0}))})}mergeCachedDisplayData(e){let t=le(e.uuid),r=new Map,o=i=>i?`code:${i}`:void 0;for(let i of t?.products??[]){let l=o(i.code);l&&r.set(l,i)}let s=(e.products??[]).map(i=>{let l=o(i.code),a=l?r.get(l):void 0;return{...i,name:i.name??a?.name??null,totalAmount:i.totalAmount??a?.totalAmount,overrideAmount:i.overrideAmount??a?.overrideAmount,currency:i.currency??a?.currency}});return{...e,currency:e.currency??t?.currency,products:s}}};U.activeVaultCaptureRequests=new Map;var I=U;function Ue(n,e){let t=I;return new t(n,e)}function Le(n){return{payment:"payment",address:"address"}[n]}function J(n){switch(n){case"night":return"night";case"flat":return"flat";default:return"stripe"}}function ze(n){return{...n,theme:J(n.theme)}}function we(n){return n?JSON.stringify(n.map(e=>e.trim().toLowerCase())):null}function Ne(n){let e=n;return{mount(t){e.mount(t)},unmount(){e.unmount()},update(t){e.update(t)},on(t,r){e.on?.(t,r)},off(t,r){e.off?.(t,r)},destroy(){e.destroy()}}}function qt(n){return{billing_details:{...n.email?{email:n.email}:{},...n.name?{name:n.name}:{},...n.address?{address:{...n.address.country?{country:n.address.country}:{},...n.address.postal_code?{postal_code:n.address.postal_code}:{},...n.address.city?{city:n.address.city}:{},...n.address.line1?{line1:n.address.line1}:{},...n.address.line2?{line2:n.address.line2}:{},...n.address.state?{state:n.address.state}:{}}}:{}}}}var K=class{constructor(){this.name="stripe";this.stripe=null;this.elements=null;this.appliedAppearanceKey=null;this.appliedPaymentMethodTypesKey=null;this.appliedClientSecret=null;this.verifiedClientSecret=null;this.verifiedPaymentMethodTypesKey=null}async initialize(e){if(typeof window>"u")return;let t=await(0,Ve.loadStripe)(e.publishableKey,{locale:e.locale??"auto"});if(!t)throw new f.FloPayError("Failed to initialize Stripe. Check your publishable key.","authentication_error");this.stripe=t}getElements(e){if(!this.stripe)throw new f.FloPayError("StripeAdapter not initialized. Call initialize() first.","api_error");let t=e?.appearance?{theme:J(e.appearance.theme),variables:e.appearance.variables,rules:e.appearance.rules}:void 0,r=t?JSON.stringify(t):null,o=we(e?.paymentMethodTypes),s=e?.clientSecret??null;if(this.elements&&o&&(o!==this.appliedPaymentMethodTypesKey||s!==this.appliedClientSecret)&&(this.elements=null,this.appliedAppearanceKey=null,this.appliedPaymentMethodTypesKey=null,this.appliedClientSecret=null,this.verifiedClientSecret=null,this.verifiedPaymentMethodTypesKey=null),this.elements)r!==this.appliedAppearanceKey&&(this.elements.update({appearance:t??{}}),this.appliedAppearanceKey=r);else{let i,l=e?.amount??0,a=(e?.currency??"usd").toLowerCase(),c=e?.paymentMethodCreation??"manual";e?.clientSecret?i={clientSecret:e.clientSecret}:l>0?(i={mode:"payment",amount:l,currency:a,paymentMethodCreation:c},e?.setupFutureUsage&&(i.setupFutureUsage=e.setupFutureUsage)):i={mode:"setup",currency:a,paymentMethodCreation:c},!e?.clientSecret&&e?.paymentMethodTypes&&(i.paymentMethodTypes=e.paymentMethodTypes),t&&(i.appearance=t),this.elements=this.stripe.elements(i),this.appliedAppearanceKey=r,this.appliedPaymentMethodTypesKey=o,this.appliedClientSecret=s,this.verifiedClientSecret=null,this.verifiedPaymentMethodTypesKey=null}return this.elements}async assertClientSecretPaymentMethods(e,t){if(!this.stripe)throw new f.FloPayError("StripeAdapter not initialized. Call initialize() first.","api_error");let r,o=!1;if((0,f.isSetupIntentClientSecret)(e)){let{setupIntent:a,error:c}=await this.stripe.retrieveSetupIntent(e);r=a,o=!!c}else{let{paymentIntent:a,error:c}=await this.stripe.retrievePaymentIntent(e);r=a,o=!!c}let s=r?.payment_method_types;if(o||!Array.isArray(s))throw new f.FloPayError("Unable to verify the payment methods configured for this client secret.","api_error",{param:"clientSecret"});let i=new Set(t.map(a=>a.toLowerCase()));if(s.some(a=>typeof a!="string"||!i.has(a.trim().toLowerCase()))||s.length===0)throw new f.FloPayError("The client-secret intent must enable only declared non-card payment methods.","validation_error",{param:"clientSecret"})}async createElement(e,t){let r=t;if(e==="payment"){let a=t.paymentMethodTypes?.map(c=>c.trim()).filter(c=>c&&c.toLowerCase()!=="card");if(!a?.length)throw new f.FloPayError("At least one supported non-card payment method is required.","validation_error",{param:"paymentMethodTypes"});if(r={...t,paymentMethodTypes:a},r.clientSecret){let c=we(a);this.elements&&this.appliedClientSecret===r.clientSecret&&this.appliedPaymentMethodTypesKey===c&&this.verifiedClientSecret===r.clientSecret&&this.verifiedPaymentMethodTypesKey===c||await this.assertClientSecretPaymentMethods(r.clientSecret,a)}}let o=this.getElements(r);e==="payment"&&r.clientSecret&&(this.verifiedClientSecret=r.clientSecret,this.verifiedPaymentMethodTypesKey=we(r.paymentMethodTypes));let s=Le(e),i={};r.layout&&(i.layout=r.layout),r.defaultValues&&(i.defaultValues=r.defaultValues),r.readOnly&&(i.readOnly=r.readOnly),r.mode&&(i.mode=r.mode);let l=o.create(s,i);return Ne(l)}getElement(e){if(!this.elements)return null;let t=Le(e),r=this.elements.getElement(t);return r?Ne(r):null}async submitElements(){if(!this.stripe||!this.elements)return{error:new f.FloPayError("Stripe not initialized","api_error")};let{error:e}=await this.elements.submit();return e?{error:new f.FloPayError(e.message??"Validation failed","validation_error")}:{}}async confirmPayment(e){if(!this.stripe||!this.elements)throw new f.FloPayError("StripeAdapter not initialized or no elements created.","api_error");let t=e.billingDetails,r=t?qt(t):void 0,{error:o,paymentIntent:s}=await this.stripe.confirmPayment({elements:this.elements,clientSecret:e.clientSecret,confirmParams:{return_url:e.returnUrl??window.location.href,...r?{payment_method_data:r}:{}},redirect:"if_required"});return o?{status:"failed",error:new f.FloPayError(o.message??"Payment failed","api_error",{code:o.code,declineCode:o.decline_code})}:s?{status:{succeeded:"succeeded",processing:"processing",requires_action:"requires_action",requires_payment_method:"failed",canceled:"failed"}[s.status]??"failed",paymentIntentId:s.id,paymentMethodId:this.extractPaymentMethodId(s.payment_method)}:{status:"failed",error:new f.FloPayError("No payment intent returned","api_error")}}extractPaymentMethodId(e){if(typeof e=="string"&&e.startsWith("pm_"))return e;if(e&&typeof e=="object"&&typeof e.id=="string")return e.id}async confirmPayPalPayment(e){if(!this.stripe)return{status:"failed",error:new f.FloPayError("Stripe not initialized","api_error")};let t=e.billingApiUrl.replace(/\/+$/,"");if(this.elements){let{error:s}=await this.elements.submit();if(s)return{status:"failed",error:new f.FloPayError(s.message??"PayPal payment failed","validation_error",{code:s.code})}}let r;try{let s=await new I(t).createSessionIntent(e.sessionId,e.nonce??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"});if(s.provider!=="stripe")throw new f.FloPayError("Invalid provider returned for PayPal intent","api_error");r=s.clientSecret}catch(s){return{status:"failed",error:s instanceof f.FloPayError?s:new f.FloPayError("Failed to create PayPal payment intent","api_error")}}let{error:o}=await this.stripe.confirmPayment({clientSecret:r,elements:this.elements??void 0,confirmParams:{return_url:e.returnUrl}});if(o){if(e.nonce)try{await new I(t).reportSessionIntentDecline(e.sessionId,e.nonce,{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:o.code??"provider_declined"})}catch{}return{status:"failed",error:new f.FloPayError(o.message??"PayPal payment failed","api_error",{code:o.code})}}return{status:"processing"}}async resumePayPalPayment(){if(!this.stripe||typeof window>"u")return null;let e=new URLSearchParams(window.location.search),t=e.get("payment_intent"),r=e.get("payment_intent_client_secret"),o=e.get("redirect_status");if(!t||!r)return null;if(o==="failed")return{status:"failed",error:new f.FloPayError("PayPal payment was declined. Please try again.","api_error")};let{paymentIntent:s,error:i}=await this.stripe.retrievePaymentIntent(r);if(i)return{status:"failed",error:new f.FloPayError(i.message??"Failed to retrieve PayPal payment","api_error")};if(s&&(0,f.isMoneySettledOutcome)(s.status)){let l=typeof s.payment_method=="string"?s.payment_method:s.payment_method?.id,a=new URL(window.location.href);return a.searchParams.delete("payment_intent"),a.searchParams.delete("payment_intent_client_secret"),a.searchParams.delete("redirect_status"),window.history.replaceState({},"",a.toString()),{status:s.status,paymentIntentId:s.id,paymentMethodId:l}}return{status:"failed",error:new f.FloPayError("PayPal payment was not completed. Please try again.","api_error")}}getRawProvider(){return this.stripe}createPayPalElements(e){if(!this.stripe)return null;let t={mode:"payment",amount:e.amount??0,currency:(e.currency??"usd").toLowerCase(),captureMethod:"manual"};return e.setupFutureUsage&&(t.setupFutureUsage=e.setupFutureUsage),e.appearance&&(t.appearance={theme:J(e.appearance.theme),variables:e.appearance.variables,rules:e.appearance.rules}),this.stripe.elements(t)}destroy(){this.elements=null,this.appliedAppearanceKey=null,this.appliedPaymentMethodTypesKey=null,this.appliedClientSecret=null,this.verifiedClientSecret=null,this.verifiedPaymentMethodTypesKey=null,this.stripe=null}};var C=require("@flopay/shared");var Be=require("@flopay/shared"),H=class{constructor(e,t){this.elementMap=new Map;this.provider=e,this.baseOptions=t??{}}async create(e,t){let r={...this.baseOptions,...t};if(e==="payment"){let l=r.paymentMethodTypes?.map(a=>a.trim()).filter(a=>a&&a.toLowerCase()!=="card");if(!l?.length)throw new Be.FloPayError("At least one supported non-card payment method is required.","validation_error",{param:"paymentMethodTypes"});r.paymentMethodTypes=l}let o=this.provider.getElement(e);if(o)return this.elementMap.set(e,o),o;let s=this.elementMap.get(e);s&&s.destroy();let i=await this.provider.createElement(e,r);return this.elementMap.set(e,i),i}getElement(e){return this.elementMap.get(e)??null}async submit(){return{}}destroy(){for(let e of this.elementMap.values())e.destroy();this.elementMap.clear()}};var T=require("@flopay/shared");var Se="flopay-vault",je={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 Q(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:n.class==="lifecycle"?n.name:n.class==="technical_error"?n.code:n.class==="expected_outcome"?n.outcome:"sdk.performance",data:e})}catch{}}function pe(n,e){return(0,T.buildTelemetryLogEvent)({eventId:"11111111-1111-4111-8111-111111111111",name:n,stage:e,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}function Ke(n){return n?{errorCode:"VAULT_SUBMIT_FAILED",stage:"vault_submit",failureCategory:"provider_runtime"}:{errorCode:"VAULT_LOAD_FAILED",stage:"vault_mount",failureCategory:"provider_runtime"}}function He(n,e){return n.type==="decline"?"payment_declined":n.outcome==="authorized"||e==="manual"?"payment_authorized":"payment_succeeded"}function Ut(n,e,t){let{type:r}=n;if(r==="complete"||r==="decline")return(0,T.buildTelemetryTerminalEvent)({eventId:"22222222-2222-4222-8222-222222222222",outcome:He(n,t),sequence:0,provider:"pcivault",paymentMethodCategory:"card"});if(r==="error"){let i=Ke(e);return(0,T.buildTelemetryErrorEvent)({eventId:"33333333-3333-4333-8333-333333333333",...i,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}let[o,s]=je[r];return pe(o,s)}function Lt(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===Se&&(e.type==="ready"||e.type==="submitting"||e.type==="blocked"||e.type==="complete"||e.type==="decline"||e.type==="error"||e.type==="action_required")}function Nt(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===Se&&e.type==="validation"&&Array.isArray(e.messages)}function Vt(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===Se&&e.type==="resize"&&typeof e.height=="number"&&Number.isFinite(e.height)}var L=class{constructor(e={},t){this.provider="pcivault";this.container=null;this.messageHandler=null;this.actionOverlay=null;this.threeDsReturnHandler=null;this.messageToken=null;this.expectedOrigin=null;this.theme=null;this.submitGateBlocked=!1;this.cardFieldOrder=null;this.cardAutoFocus=!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:(0,T.resolveBillingApiUrl)(),sdkVersion:T.SDK_VERSION}):void 0)}async mount(e,t){if(this.ownsTelemetryReporter&&!this.telemetryReporter&&(this.telemetryReporter=new _({billingApiUrl:(0,T.resolveBillingApiUrl)(),sdkVersion:T.SDK_VERSION})),this.mountStartedAt=this.telemetryReporter?.now?.()??M(),this.vaultReadyReported=!1,this.submissionStarted=!1,this.submissionStartedAt=null,typeof window>"u"||typeof document>"u")throw this.reportVaultLoadFailure(),new T.FloPayError("The vault card form is only available in the browser.","api_error",{code:"card_capture_no_window"});if(!t?.html||!t.html.trim())throw this.reportVaultLoadFailure(),new T.FloPayError("No vault capture widget HTML was provided to mount the secure card form.","api_error",{code:"card_capture_no_widget_html"});this.container=e,this.messageToken=t.messageToken??null,this.expectedOrigin=t.expectedOrigin??this.config.expectedOrigin??null,this.theme=t.theme??null;try{this.attachMessageListener(),this.injectWidget(e,t.html)}catch(r){throw this.reportVaultLoadFailure(),r}this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),Q(pe("vault.widget.mounted","vault_mount")),this.telemetryReporter?.log({name:"vault.widget.mounted",stage:"vault_mount",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 o of r){let s=document.createElement("script");for(let i of Array.from(o.attributes))s.setAttribute(i.name,i.value);s.text=o.text,o.replaceWith(s)}}attachMessageListener(){if(this.messageHandler)return;let e=t=>{if(this.expectedOrigin&&t.origin!==this.expectedOrigin)return;let r=t.data;if(Vt(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;this.applyHeight(r.height);return}if(Nt(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;let l=r.messages.filter(a=>typeof a=="string"&&a.trim()).join(" ");this.emit("validation",{sessionId:this.config.sessionId,message:l||void 0});return}if(!Lt(r)||this.messageToken&&r.messageToken!==this.messageToken)return;let o=this.config.sessionId,s=typeof r.sessionId=="string"?r.sessionId:void 0;if(o&&s&&s!==o||(r.type==="complete"||r.type==="decline")&&o&&s!==o)return;let i={...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}:{}};r.type==="submitting"&&(this.submissionStarted=!0,this.submissionStartedAt=this.telemetryReporter?.now?.()??M()),Q(Ut(r,this.submissionStarted,this.config.captureMethod)),this.reportOutcome(r),r.type==="ready"&&(this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder()),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,i)};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"})),r==="complete"||r==="decline"){t.log({name:"vault.terminal",stage:"completion",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:He(e,this.config.captureMethod),provider:"pcivault",paymentMethodCategory:"card"});return}if(r==="error"){let i=Ke(this.submissionStarted);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[o,s]=je[r];t.log({name:o,stage:s,provider:"pcivault",paymentMethodCategory:"card"})}applyTheme(e){this.theme=e,this.postTheme()}postTheme(){if(!this.theme||!this.container)return;let t=this.container.querySelector("iframe")?.contentWindow;if(t)try{t.postMessage({source:"flopay-vault-host",type:"theme",theme:this.theme},"*")}catch{}}setSubmitGate(e){this.submitGateBlocked=e,this.postSubmitGate()}postSubmitGate(){if(!this.container)return;let t=this.container.querySelector("iframe")?.contentWindow;if(t)try{t.postMessage({source:"flopay-vault-host",type:"gate",blocked:this.submitGateBlocked},"*")}catch{}}setCardFieldOrder(e,t){this.cardFieldOrder=e,this.cardAutoFocus=t,this.postCardFieldOrder()}postCardFieldOrder(){if(!this.container)return;let t=this.container.querySelector("iframe")?.contentWindow;if(t)try{t.postMessage({source:"flopay-vault-host",type:"fieldOrder",order:this.cardFieldOrder,autoFocus:this.cardAutoFocus},"*")}catch{}}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);return}let t=document.createElement("div");t.setAttribute("data-flopay-action-required","1"),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.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 o=document.createElement("button");o.type="button",o.setAttribute("aria-label","Close card authentication"),o.textContent="\xD7",o.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(";"),o.addEventListener("click",()=>this.abandonActionRequiredOverlay()),t.appendChild(o),t.addEventListener("click",i=>{i.target===t&&this.abandonActionRequiredOverlay()});let s=i=>{if(i.source!==r.contentWindow)return;let l=i.data;if(!l||typeof l!="object")return;let a=l;a.source==="flopay-vault-3ds-return"&&(Q(pe("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(),this.postActionCompleted(a.status))};window.addEventListener("message",s),this.threeDsReturnHandler=s,document.body.appendChild(t),this.actionOverlay=t,Q(pe("vault.three_ds.handoff","three_ds_handoff"))}postActionCompleted(e){if(!this.container)return;let r=this.container.querySelector("iframe")?.contentWindow;if(r)try{r.postMessage({source:"flopay-vault-host",type:"action_completed",status:typeof e=="string"?e:"unknown"},"*")}catch{}}abandonActionRequiredOverlay(){if(!this.actionOverlay)return;let e=(0,T.buildTelemetryTerminalEvent)({eventId:"77777777-7777-4777-8777-777777777777",outcome:"customer_abandoned",stage:"three_ds_handoff",sequence:0,provider:"pcivault",paymentMethodCategory:"card"});Q(e),this.telemetryReporter?.terminal({outcome:"customer_abandoned",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"}),this.hideActionRequiredOverlay(),this.postActionCompleted("abandoned")}hideActionRequiredOverlay(){this.threeDsReturnHandler&&(window.removeEventListener("message",this.threeDsReturnHandler),this.threeDsReturnHandler=null),this.actionOverlay&&(this.actionOverlay.parentNode?.removeChild(this.actionOverlay),this.actionOverlay=null)}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 $e(n,e){let t=L;return new t(n,{reporter:e})}var Ge=Symbol.for("@flopay/js.telemetry.bridge.v1");function Ye(n,e,t){let r=()=>e?.now()??t();Object.defineProperty(n,Ge,{configurable:!1,enumerable:!1,writable:!1,value:{error:s=>e?.error(s),log:s=>e?.log(s),performance:s=>e?.performance(s),terminal:s=>e?.terminal(s),now:r,elapsed:s=>Math.max(0,r()-s),setCheckoutContext:s=>e?.setCheckoutContext(s),beginCheckout:(s={})=>e?.beginCheckout(s)??r(),disable:()=>e?.disable()}})}function We(n){return n[Ge]}function $(n){if(!n)return!1;let e=n.code?.toLowerCase()??"";return!!n.declineCode||e.includes("declin")}function zt(n){return n==="stripe"||n==="paypal"||n==="pcivault"?n:"other"}var X=class{constructor(e,t,r){this.currentElements=null;this.provider=e,this.config=t,this.telemetryReporter=r??new _({billingApiUrl:(0,C.resolveBillingApiUrl)(t.billingApiUrl),sdkVersion:C.SDK_VERSION,enabled:t.telemetry!==!1}),Ye(this,this.telemetryReporter,M)}now(){return this.telemetryReporter?.now?.()??M()}elements(e){return this.currentElements&&this.currentElements.destroy(),this.currentElements=new H(this.provider,{appearance:this.config.appearance,...e}),this.currentElements}async submitElements(){return this.provider.submitElements()}cardCapture(e){return this.telemetryReporter?.log({name:"vault.capture.requested",stage:"vault_request",provider:"pcivault",paymentMethodCategory:"card"}),this.telemetryReporter?$e({sessionId:e?.sessionId,captureMethod:e?.captureMethod},this.telemetryReporter):new L({sessionId:e?.sessionId,captureMethod:e?.captureMethod,telemetry:!1})}async confirmPayPalPayment(e){let t=this.now();this.telemetryReporter?.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),this.telemetryReporter?.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});try{let r=await this.provider.confirmPayPalPayment(e);return this.telemetryReporter?.performance({stage:"processing",durationMs:this.now()-t,durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),r.error||this.telemetryReporter?.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),r.status==="requires_action"?(this.telemetryReporter?.log({name:"provider.redirect.started",stage:"redirect",provider:"paypal",paymentMethodCategory:"paypal"}),this.telemetryReporter?.terminal({outcome:"action_required",stage:"redirect",provider:"paypal",paymentMethodCategory:"paypal"})):r.status==="succeeded"?this.telemetryReporter?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}):r.status!=="processing"&&($(r.error)?this.telemetryReporter?.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):r.error?.type==="validation_error"?this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal"}):r.error&&this.telemetryReporter?.error({errorCode:"PAYMENT_PROCESSING_FAILED",failureCategory:"provider_runtime",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"})),r}catch(r){if(this.telemetryReporter?.performance({stage:"processing",durationMs:this.now()-t,durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),r instanceof C.FloPayError&&$(r))this.telemetryReporter?.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"});else if(r instanceof C.FloPayError&&r.type==="validation_error")this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal"});else{let o=(0,C.classifyTelemetryFailure)(r,"PAYMENT_PROCESSING_FAILED","unknown");this.telemetryReporter?.error({...o,failureCategory:o.failureCategory??"provider_runtime",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"})}throw r}}async resumePayPalPayment(){let e=this.now();try{let t=await this.provider.resumePayPalPayment();return t===null?null:(this.telemetryReporter?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),this.telemetryReporter?.performance({stage:"redirect_resume",durationMs:this.now()-e,durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),t.status==="succeeded"?this.telemetryReporter?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}):$(t.error)?this.telemetryReporter?.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):t.error?.type==="validation_error"?this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal"}):t.error&&this.telemetryReporter?.error({errorCode:"REDIRECT_RESUME_FAILED",failureCategory:"provider_runtime",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),t)}catch(t){if(this.telemetryReporter?.performance({stage:"redirect_resume",durationMs:this.now()-e,durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),t instanceof C.FloPayError&&$(t))this.telemetryReporter?.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"});else if(t instanceof C.FloPayError&&t.type==="validation_error")this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal"});else{let r=(0,C.classifyTelemetryFailure)(t,"REDIRECT_RESUME_FAILED","unknown");this.telemetryReporter?.error({...r,failureCategory:r.failureCategory??"provider_runtime",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"})}throw t}}async confirmPayment(e){if(e.paymentMethodCategory!=="wallet"&&e.paymentMethodCategory!=="apm"||!e.paymentMethodType?.trim()||e.paymentMethodType.trim().toLowerCase()==="card")throw new C.FloPayError("A supported non-card payment method is required.","validation_error",{param:"paymentMethodType"});let t=this.now(),r=zt(this.provider.name);this.telemetryReporter?.log({name:"payment.processing.started",stage:"processing",provider:r,paymentMethodCategory:e.paymentMethodCategory});try{let o=await this.provider.confirmPayment(e),s=this.now()-t;return this.telemetryReporter?.performance({stage:"processing",durationMs:s,durationMode:"machine",provider:r,paymentMethodCategory:e.paymentMethodCategory}),o.status==="succeeded"?this.telemetryReporter?.terminal({outcome:"payment_succeeded",provider:r,paymentMethodCategory:e.paymentMethodCategory}):$(o.error)?this.telemetryReporter?.terminal({outcome:"payment_declined",provider:r,paymentMethodCategory:e.paymentMethodCategory}):o.error?.type==="validation_error"?this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:r,paymentMethodCategory:e.paymentMethodCategory}):o.status==="requires_action"?this.telemetryReporter?.terminal({outcome:"action_required",stage:"three_ds_handoff",provider:r,paymentMethodCategory:e.paymentMethodCategory}):o.status==="failed"&&o.error&&this.telemetryReporter?.error({errorCode:"PAYMENT_PROCESSING_FAILED",failureCategory:"provider_runtime",stage:"processing",provider:r,paymentMethodCategory:e.paymentMethodCategory}),o.status==="succeeded"||o.status==="failed"?this.telemetryReporter?.log({name:"payment.processing.completed",stage:"processing",provider:r,paymentMethodCategory:e.paymentMethodCategory}):this.telemetryReporter?.log({name:"operation.state_transition",stage:o.status==="requires_action"?"three_ds_handoff":"processing",provider:r,paymentMethodCategory:e.paymentMethodCategory}),o}catch(o){throw this.telemetryReporter?.performance({stage:"processing",durationMs:this.now()-t,durationMode:"machine",provider:r,paymentMethodCategory:e.paymentMethodCategory}),o instanceof C.FloPayError&&$(o)?this.telemetryReporter?.terminal({outcome:"payment_declined",provider:r,paymentMethodCategory:e.paymentMethodCategory}):o instanceof C.FloPayError&&o.type==="validation_error"?this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:r,paymentMethodCategory:e.paymentMethodCategory}):this.telemetryReporter?.error({errorCode:"PAYMENT_PROCESSING_FAILED",failureCategory:"provider_runtime",stage:"processing",provider:r,paymentMethodCategory:e.paymentMethodCategory}),o}}async retrieveSession(e,t){if(!e)throw new C.FloPayError("sessionId is required to retrieve a session.","validation_error",{param:"sessionId"});let r=await this.retrieveUnifiedSession(e,t);if(!r.data.session)throw new C.FloPayError("Session not found","api_error");return r.data.session}async retrieveUnifiedSession(e,t){if(!e)throw new C.FloPayError("sessionId is required.","validation_error",{param:"sessionId"});let r=(0,C.resolveBillingApiUrl)(t??this.config.billingApiUrl),o=this.now();this.telemetryReporter?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let s,i=Ue(r,{now:()=>this.telemetryReporter?.now()??M(),onFirstByte:l=>{s=l},onRetry:(l,a)=>{this.telemetryReporter?.log({name:"operation.retry",stage:l==="session_read"?"session_read":"processing",requestCategory:l,attempt:a})}});try{let l=await i.getUnifiedCheckoutSession(e);return s!==void 0&&(this.telemetryReporter?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:"2xx"}),this.telemetryReporter?.performance({stage:"session_first_byte",durationMs:s,durationMode:"machine",requestCategory:"session_read",statusClass:"2xx"})),this.telemetryReporter?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:"2xx"}),this.telemetryReporter?.log({name:"checkout.data.ready",stage:"checkout_data_ready"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-o,durationMode:"machine",requestCategory:"session_read",statusClass:"2xx"}),l}catch(l){let a=(0,C.classifyTelemetryFailure)(l,l instanceof C.FloPayError&&l.code==="checkout_processing_timeout"?"REQUEST_TIMEOUT":"NETWORK_REQUEST_FAILED");throw this.telemetryReporter?.error({...a,stage:"session_read",provider:"flo",paymentMethodCategory:"unknown"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-o,durationMode:"machine",requestCategory:"session_read",statusClass:a.statusClass}),l}}getRawProvider(){return this.provider.getRawProvider()}destroy(){this.telemetryReporter?.log({name:"checkout.unmount",stage:"unmount"}),this.telemetryReporter?.destroy(),this.currentElements?.destroy(),this.currentElements=null,this.provider.destroy()}};function Je(n,e,t){let r=X;return new r(n,e,t)}var Qe=new Map;function be(n){return Array.isArray(n)?n.map(be):n&&typeof n=="object"?Object.fromEntries(Object.entries(n).filter(([,e])=>e!==void 0).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,be(t)])):n}function Bt(n,e){return JSON.stringify([n,(0,E.resolveBillingApiUrl)(e?.billingApiUrl),e?.telemetry!==!1,e?.locale??"auto",e?.apiVersion??null,be(e?.appearance??null)])}var me=new Map;async function Xe(n,e){if(!n){let l=new _({billingApiUrl:(0,E.resolveBillingApiUrl)(e?.billingApiUrl),sdkVersion:E.SDK_VERSION,enabled:e?.telemetry!==!1});throw l.error({errorCode:"CONFIGURATION_INVALID",stage:"sdk_initialize",paymentMethodCategory:"unknown"}),l.flush().catch(()=>{}).finally(()=>l.destroy()),new E.FloPayError("A publishable key is required to initialize FloPay.","validation_error",{param:"publishableKey"})}let t=Bt(n,e),r=Qe.get(t);if(r)return e?.telemetry!==!1&&We(r)?.log({name:"sdk.cache.hit",stage:"sdk_initialize"}),r;let o=me.get(t);if(o)return o;let s={...e,publishableKey:n},i=(async()=>{let l=new _({billingApiUrl:(0,E.resolveBillingApiUrl)(s.billingApiUrl),sdkVersion:E.SDK_VERSION,enabled:s.telemetry!==!1}),a=l.now();l.log({name:"sdk.initialize.started",stage:"sdk_initialize"}),l.log({name:"sdk.cache.miss",stage:"sdk_initialize"}),l.log({name:"provider.load.started",stage:"provider_load",provider:"stripe"});let c=new K,u=l.now();try{await c.initialize(s)}catch(m){throw l.error({errorCode:"SDK_INITIALIZATION_FAILED",failureCategory:"provider_runtime",stage:"sdk_initialize",provider:"stripe",paymentMethodCategory:"unknown"}),l.destroy(),m}let y=l.now();l.log({name:"provider.ready",stage:"provider_ready",provider:"stripe"}),l.log({name:"provider.availability.checked",stage:"provider_ready",provider:"stripe"}),l.log({name:"sdk.initialize.ready",stage:"sdk_initialize"}),l.performance({stage:"sdk_initialize",durationMs:y-a,durationMode:"machine",provider:"stripe"}),l.performance({stage:"provider_ready",durationMs:y-u,durationMode:"machine",provider:"stripe"});let p=Je(c,s,l);return Qe.set(t,p),p})();me.set(t,i);try{return await i}finally{me.get(t)===i&&me.delete(t)}}var h=require("@flopay/shared");var Me=5,Ze=new WeakSet;function jt(n){(typeof n=="object"&&n!==null||typeof n=="function")&&Ze.add(n)}function Kt(n){return(typeof n=="object"&&n!==null||typeof n=="function")&&Ze.has(n)}function Ht(n,e){let t=e?.error,r=x(e?.code)??x(t?.code)??`http_${n}`,o=x(e?.message)??x(t?.message)??$t(r,n);return new h.FloPayError(o,"api_error",{code:r,statusCode:n})}function $t(n,e){switch(n){case"CouponLimitExceeded":return`Too many coupon codes \u2014 a checkout session accepts at most ${Me}.`;case"CouponCurrencyUnsupported":return"One of the applied coupons has no price configured for the cart currency.";default:return`Failed to create checkout session (HTTP ${e}).`}}async function et(n,e,t){let{billingApiUrl:r,checkoutBaseUrl:o,items:s=[],subscriptions:i=[],products:l,account:a,successUrl:c,cancelUrl:u,checkoutMode:y="confirm",captureMethod:p,couponCodes:m=[],tagsData:k,redirectParams:w={},setCookie:b=!0,clientId:ke,currency:Y,utmMetadata:g,idempotencyKey:Z}=n,ee=(0,h.resolveIdempotencyKey)(Z);if(m.length>Me)throw new h.FloPayError(`Too many coupon codes \u2014 a checkout session accepts at most ${Me}.`,"validation_error",{code:"CouponLimitExceeded",param:"couponCodes"});let D=l??(0,h.foldIntoProducts)(s,i);(0,h.assertCaptureMethodEligible)({captureMethod:p,products:D});let R=(0,h.resolveSessionCurrency)(Y,s,i,D);if(!R)throw new h.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 N={clientId:ke,checkoutVersion:h.SDK_VERSION,successUrl:c,cancelUrl:u,currency:R,checkoutMode:y,products:D.map(A=>(0,h.buildProductPayload)(A,R)),accountData:{userId:a.userId,firstName:a.firstName??null,lastName:a.lastName??null,email:a.email,country:a.country??null,gender:a.gender??null,city:a.city??null,state:a.state??null,zip:a.zip??null,addressLine1:a.addressLine1??null,addressLine2:a.addressLine2??null},couponCodes:m};p==="manual"&&(N.captureMethod=p),k&&(N.tagsData=k),g?.length&&(N.utmMetadata=g);let W=`${r.replace(/\/+$/,"")}/v1/checkouts/sessions`,te={"Content-Type":"application/json"};ee&&(te[h.IDEMPOTENCY_KEY_HEADER]=ee);let V,re,at={method:"POST",headers:te,body:JSON.stringify(N),signal:e},ne;try{ne=await fetch(W,at)}catch(A){throw jt(A),A}try{t?.(ne.status)}catch{}V=ne.status;try{re=await ne.json()}catch{}if(V>=400)throw Ht(V,re);if(V===201){let A=re?.data?.uuid,he=re?.data?.nonce;if(!A)throw new Error("Checkout session created but no UUID was returned by the billing API");if(!he)throw new h.FloPayError("Checkout session created but no `nonce` was returned by the billing API. Upgrade the billing service to TeamFloPay/backend#640 or later.","api_error",{code:"MissingCheckoutSessionToken"});(D.length||R)&&F(A,{currency:R,products:D.map(v=>({code:v.code??v.providerItemId??v.providerPlanId,type:v.type,name:v.name??v.itemName??v.providerItemName??v.subscriptionName??v.providerPlanName??null,totalAmount:v.totalAmount,overrideAmount:v.overrideAmount,currency:v.currency??R}))});let oe=new URL(`${o.replace(/\/+$/,"")}/secure`);oe.searchParams.set("id",A);for(let[v,se]of Object.entries(w))oe.searchParams.set(v,se);if(b&&typeof window<"u"&&typeof document<"u"){let v=JSON.stringify({origin_url:u}),se=window.location.hostname.split(".").slice(-2).join(".");document.cookie=`checkout_data=${encodeURIComponent(v)}; domain=.${se}; path=/; max-age=3600; SameSite=Lax; Secure;`,document.cookie=`flopay_checkout_token=${encodeURIComponent(he)}; domain=.${se}; path=/; max-age=3600; SameSite=Lax; Secure;`}return typeof window<"u"&&(window.location.href=oe.toString()),{status:201,redirectUrl:oe.toString(),nonce:he}}return V===204?(typeof window<"u"&&(window.location.href=c),{status:204}):{status:V}}async function tt(n){let e=nt(n),t=rt(e),r=O(n.timeoutMs);try{let o=await et(n,r.signal,t);return ot(e,o),o}catch(o){throw ye(e,o),o}finally{r.clear(),G(e.reporter)}}function rt(n){let e=!1;return t=>{if(e)return;e=!0;let r=(0,h.telemetryStatusClass)(t);n.reporter.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:r,attempt:n.attempt}),n.reporter.performance({stage:"session_first_byte",durationMs:n.reporter.now()-n.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:r,attempt:n.attempt})}}function nt(n){let e=new _({billingApiUrl:n.billingApiUrl,sdkVersion:h.SDK_VERSION,enabled:n.telemetry!==!1}),t=e.now();return e.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"}),{reporter:e,startedAt:t,attempt:0}}function ot(n,e){let t=(0,h.telemetryStatusClass)(e.status);n.reporter.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:t}),n.reporter.performance({stage:"session_create",durationMs:n.reporter.now()-n.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:t,attempt:n.attempt})}function ye(n,e){let{reporter:t}=n,r=(0,h.classifyTelemetryFailure)(e,"CHECKOUT_SESSION_CREATE_FAILED");if(t.performance({stage:"session_create",durationMs:t.now()-n.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:r.statusClass,attempt:n.attempt}),e instanceof h.FloPayError&&e.type==="validation_error"){t.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"});return}if(r.statusClass==="4xx"){t.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create",statusClass:"4xx"});return}t.error({...r,stage:"session_create",requestCategory:"session_create"})}function G(n){n.flush().catch(()=>{}).finally(()=>n.destroy())}async function st(n){let{maxRetries:e=2,...t}=n,r=nt(n),o=rt(r);if(!Number.isFinite(e)||!Number.isInteger(e)||e<0||e>=3)throw r.reporter.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),G(r.reporter),new Error(`Number of retries must be an integer between 0 and ${2}`);let s={...t,idempotencyKey:(0,h.resolveIdempotencyKey)(t.idempotencyKey)},i=O(t.timeoutMs),l;for(let a=0;a<=e;a++){r.attempt=a;try{let c=await et(s,i.signal,o);return ot(r,c),i.clear(),G(r.reporter),c}catch(c){l=c;let u=c instanceof Error&&c.name==="AbortError",y=Kt(c),p=c instanceof h.FloPayError&&c.code===h.IDEMPOTENCY_IN_PROGRESS_CODE;if((u||y||p)&&!i.signal.aborted&&a<e){r.reporter.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:a+1});try{await B(a,i.signal)}catch(m){throw ye(r,m),i.clear(),G(r.reporter),m}continue}throw ye(r,c),i.clear(),G(r.reporter),c}}throw ye(r,l),i.clear(),G(r.reporter),l??new Error("Unknown error during checkout session creation")}var it=require("@flopay/shared");0&&(module.exports={FloPay,FloPayElements,PaymentAPI,PciVaultCardCapture,SESSION_CREATE_TELEMETRY,StripeAdapter,cacheSessionDisplayData,clearSessionDisplayData,createCheckoutSession,createCheckoutSessionWithRetries,dropThirdPartyOnlyError,getSessionDisplayData,loadFloPay,toStripeAppearance,toStripeAppearanceTheme});
|
|
1
|
+
"use strict";var ge=Object.defineProperty;var lt=Object.getOwnPropertyDescriptor;var ct=Object.getOwnPropertyNames;var dt=Object.prototype.hasOwnProperty;var ut=(n,e)=>{for(var t in e)ge(n,t,{get:e[t],enumerable:!0})},pt=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ct(e))!dt.call(n,o)&&o!==t&&ge(n,o,{get:()=>e[o],enumerable:!(r=lt(e,o))||r.enumerable});return n};var mt=n=>pt(ge({},"__esModule",{value:!0}),n);var Yt={};ut(Yt,{FloPay:()=>X,FloPayElements:()=>H,PaymentAPI:()=>I,PciVaultCardCapture:()=>L,SESSION_CREATE_TELEMETRY:()=>_e,StripeAdapter:()=>K,cacheSessionDisplayData:()=>F,clearSessionDisplayData:()=>ce,createCheckoutSession:()=>tt,createCheckoutSessionWithRetries:()=>st,dropThirdPartyOnlyError:()=>it.dropThirdPartyOnlyError,getSessionDisplayData:()=>le,loadFloPay:()=>Xe,toStripeAppearance:()=>ze,toStripeAppearanceTheme:()=>J});module.exports=mt(Yt);var E=require("@flopay/shared");var Ve=require("@stripe/stripe-js"),f=require("@flopay/shared");var d=require("@flopay/shared");function D(n){return typeof n=="string"&&n.trim()?n:void 0}function Pe(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}var yt="flopay_session_display:";var ie=new Map;function ae(n){return`${yt}${n}`}function fe(){if(typeof window>"u")return null;try{return window.sessionStorage}catch{return null}}function F(n,e,t){if(!n)return;let r=t?.ttlMs??36e5,o={data:e,expiresAt:Date.now()+r},s=fe();if(s)try{s.setItem(ae(n),JSON.stringify(o));return}catch{}ie.set(n,o)}function le(n){if(!n)return null;let e=fe();if(e)try{let r=e.getItem(ae(n));if(r){let o=JSON.parse(r);if(o&&typeof o.expiresAt=="number"&&o.expiresAt>Date.now())return o.data;e.removeItem(ae(n))}}catch{}let t=ie.get(n);if(t){if(t.expiresAt>Date.now())return t.data;ie.delete(n)}return null}function ce(n){if(!n)return;ie.delete(n);let e=fe();if(e)try{e.removeItem(ae(n))}catch{}}var S=require("@flopay/shared"),ht="/v1/sdk-telemetry/events",Ce=16,gt=64,ft=1500,Ee=1e3,Ct=64,vt="00000000-0000-4000-8000-000000000000",Tt={technical_error:8,lifecycle:32,expected_outcome:32,performance:24};function z(){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]&15|64,n[8]=n[8]&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 _t(n){try{return new TextEncoder().encode(n).byteLength}catch{return n.length}}function wt(n){return JSON.stringify([n.code,n.failureCategory,n.stage,n.provider,n.attempt,n.statusClass,n.requestCategory,n.paymentMethodCategory,n.checkoutMode,n.layout])}function M(){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.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(/\/+$/,"")}${ht}`,this.sdkPackage=e.sdkPackage??"@flopay/js",this.sdkVersion=e.sdkVersion,this.correlationId=z(),this.merchantEnabled=e.enabled!==!1,this.clock=e.clock??M,this.browserTransportAvailable=typeof window<"u"&&typeof document<"u",this.browserTransportAvailable&&(window.addEventListener("pagehide",this.pageExitHandler),document.addEventListener("visibilitychange",this.visibilityHandler))}log(e){this.canCollect()&&this.enqueue((0,S.buildTelemetryLogEvent)({...this.checkoutContext,...e,eventId:z(),sequence:this.sequence++}))}error(e){if(!this.canCollect())return;let t=(0,S.buildTelemetryErrorEvent)({...this.checkoutContext,...e,eventId:vt,sequence:0}),r=wt(t),o=this.now();this.pruneReportedFailures(o);let s=this.reportedFailures.get(r);if(s!==void 0&&o>=s&&o-s<Ee){this.log({name:"operation.deduplicated",stage:e.stage,provider:e.provider,paymentMethodCategory:e.paymentMethodCategory,attempt:e.attempt});return}this.rememberReportedFailure(r,o),this.enqueue((0,S.buildTelemetryErrorEvent)({...this.checkoutContext,...e,eventId:z(),sequence:this.sequence++}))}performance(e){this.canCollect()&&this.enqueue((0,S.buildTelemetryPerformanceEvent)({...this.checkoutContext,...e,eventId:z(),sequence:this.sequence++}))}terminal(e){if(this.canCollect()&&(this.enqueue((0,S.buildTelemetryTerminalEvent)({...this.checkoutContext,...e,eventId:z(),sequence:this.sequence++})),e.outcome!=="action_required"&&this.checkoutStartedAt!==null)){let t=this.checkoutStartedAt;this.checkoutStartedAt=null,this.performance({stage:"total_journey",durationMs:Math.max(0,this.now()-t),durationMode:"total",provider:e.provider,paymentMethodCategory:e.paymentMethodCategory})}}now(){try{return this.clock()}catch{return M()}}pruneReportedFailures(e){for(let[t,r]of this.reportedFailures)(e<r||e-r>=Ee)&&this.reportedFailures.delete(t)}rememberReportedFailure(e,t){for(;this.reportedFailures.size>=Ct;){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>=gt||this.eventCounts[e.class]>=Tt[e.class])){if(this.eventCounts[e.class]+=1,this.queue.push(e),this.queue.length>=Ce){this.flush();return}this.scheduleFlush()}}canCollect(){return this.browserTransportAvailable&&this.merchantEnabled&&!this.ingestionDisabled&&!this.destroyed}async flush(){if(this.flushInFlight)return this.flushInFlight;if(!this.browserTransportAvailable||this.destroyed||this.ingestionDisabled||this.queue.length===0)return;this.clearFlushTimer();let e=this.queue.splice(0,Ce);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())}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,Ce);this.sendBatch(e)}}async sendBatch(e){if(!this.browserTransportAvailable||this.ingestionDisabled)return;let t=(0,S.serializeTelemetryBatch)(e,{correlationId:this.correlationId,sdkPackage:this.sdkPackage,sdkVersion:this.sdkVersion,batchId:z()});if(_t(t)>S.TELEMETRY_MAX_BATCH_BYTES)return;let r=typeof AbortController>"u"?null:new AbortController,o=null;try{let s=fetch(this.endpoint,{method:"POST",headers:{"content-type":"text/plain;charset=UTF-8"},body:t,credentials:"omit",keepalive:!0,referrerPolicy:"no-referrer",signal:r?.signal}).then(async l=>l.status!==202?null:(await l.json().catch(()=>null))?.status==="disabled"?"disabled":null).catch(()=>null),i=new Promise(l=>{o=setTimeout(()=>{r?.abort(),l(null)},ft)});await Promise.race([s,i])==="disabled"&&this.disableFromIngestion()}catch{}finally{o&&clearTimeout(o)}}disableFromIngestion(){this.ingestionDisabled=!0,this.queue.splice(0),this.reportedFailures.clear(),this.clearFlushTimer()}scheduleFlush(){this.flushTimer||this.destroyed||this.ingestionDisabled||(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush()},0))}clearFlushTimer(){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null)}},Re=Symbol.for("@flopay/js.telemetry.reporter-factory.v1"),Ae=globalThis;Ae[Re]===void 0&&Object.defineProperty(Ae,Re,{configurable:!0,enumerable:!1,writable:!1,value:n=>new _(n)});function O(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 St(){return Object.assign(new Error("The operation was aborted."),{name:"AbortError"})}function B(n,e){let t=150*2**n,r=Math.round(t*(.75+Math.random()*.5));return new Promise((o,s)=>{let i,a=()=>e.removeEventListener("abort",l),l=()=>{i!==void 0&&clearTimeout(i),a(),s(St())};if(e.aborted){l();return}i=setTimeout(()=>{a(),o()},r),e.addEventListener("abort",l,{once:!0})})}var Ie=1e3,bt=500,Mt=15e3,kt=3e3,Pt=1e4,Et=1e4;function Rt(n){return typeof n=="object"&&n!==null}function j(n,e){return D(n?.[e])}function xe(n,e){return Pe(n?.[e])}function At(n,e){let t=n?.[e];return typeof t=="number"&&Number.isFinite(t)?t:void 0}function Fe(n){return new Promise(e=>setTimeout(e,n))}function de(){return new d.FloPayError("Checkout is still processing. Please try again shortly.","api_error",{code:"checkout_processing_timeout"})}async function q(n,e){let t=await n.json().catch(()=>null),r=Rt(t?.error)?t.error:null,o=xe(t,"message")??xe(r,"message")??e,s=j(t,"code")??j(t,"gatewayErrorCode")??j(r,"code")??`http_${n.status}`;return new d.FloPayError(o,"api_error",{code:s,statusCode:n.status})}async function It(n){let e=n.status===400?await n.clone().json().catch(()=>null):null;return(0,d.classifyPaymentRejection)(n.status,e)}function De(n){return n===400||n===422}var ue=2;async function Te(n,e,t=ue,r){let o;for(let s=0;;s++)try{return await fetch(n,e)}catch(i){if(e?.signal?.aborted||i instanceof Error&&i.name==="AbortError")throw i;if(o=i,s>=t)throw o;try{r?.(s+1)}catch{}await Fe(150*2**s)}}var _e=Symbol.for("@flopay/js.session-create.telemetry.v1");function xt(n){return n[_e]}function Dt(n){return"now"in n||"onFirstByte"in n||"onSessionCreateFailure"in n||"onRetry"in n}function Oe(n){return{userId:n.userId,firstName:n.firstName??null,lastName: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 qe(n,e){e.tagsData&&(n.tagsData=e.tagsData),e.utmMetadata?.length&&(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 Ft(n,e){let t={clientId:n.clientId,checkoutVersion:d.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}),qe(t,n),t}function Ot(n,e,t){return{currency:e,products:t.map(r=>(0,d.buildProductPayload)(r,e)),couponCodes:n.couponCodes??[],accountData:Oe(n.account)}}var U=class U{constructor(e,t={}){this.baseUrl=e.replace(/\/+$/,"");let r=Dt(t);this.telemetryHooks=r?t:void 0,this.directTelemetry=r||t.telemetry===!1?void 0:new _({billingApiUrl:this.baseUrl,sdkVersion:d.SDK_VERSION})}destroy(){this.directTelemetry?.destroy()}reportDirectFailure(e,t,r,o,s="unknown"){let i=(0,d.classifyTelemetryFailure)(e,t);this.directTelemetry?.error({...i,stage:r,requestCategory:o,paymentMethodCategory:s})}reportAccountSnapshotFailure(e,t){let r=(0,d.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()??M()}catch{return M()}}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){this.beginDirectTelemetryCheckout(e);let r=this.telemetryTimestamp();this.directTelemetry?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let o={[d.FLO_SDK_VERSION_HEADER]:d.SDK_VERSION};t&&(o["x-checkout-session-token"]=t);try{let s=await Te(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}`,{headers:o},ue,c=>{this.telemetryHooks?.onRetry?.("session_read",c),this.directTelemetry?.log({name:"operation.retry",stage:"session_read",requestCategory:"session_read",attempt:c})}),i=Math.max(0,this.telemetryTimestamp()-r);try{this.telemetryHooks?.onFirstByte?.(i)}catch{}let a=`${Math.floor(s.status/100)}xx`;if(this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:a}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:i,durationMode:"machine",requestCategory:"session_read",statusClass:a}),!s.ok)throw await q(s,"Failed to get checkout session");let l=await s.json();return this.directTelemetry?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:a}),this.directTelemetry?.performance({stage:"session_complete",durationMs:Math.max(0,this.telemetryTimestamp()-r),durationMode:"machine",requestCategory:"session_read",statusClass:a}),{...l,data:this.mergeCachedDisplayData(l.data)}}catch(s){throw this.directTelemetry?.error({...(0,d.classifyTelemetryFailure)(s,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"}),s}}cacheSessionDisplayData(e,t,r){F(e,t,r)}clearSessionDisplayData(e){ce(e)}async getVaultCapture(e,t){let r=`${this.baseUrl}\0${e}\0${t??""}`,o=U.activeVaultCaptureRequests.get(r);if(o)return o;let s=this.requestVaultCapture(e,t);U.activeVaultCaptureRequests.set(r,s);try{return await s}finally{U.activeVaultCaptureRequests.get(r)===s&&U.activeVaultCaptureRequests.delete(r)}}async requestVaultCapture(e,t){let r=new AbortController,o=setTimeout(()=>r.abort(),Et);this.beginDirectTelemetryCheckout(e);let s=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 Te(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/vault/capture`,{method:"POST",headers:i,signal:r.signal},ue,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 q(a,"Failed to load the secure card form");let l=await a.json();return this.directTelemetry?.performance({stage:"vault_request",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"2xx"}),this.toVaultBlock(l)}catch(a){let l=r.signal.aborted?new d.FloPayError("Timed out while loading the secure card form. Please try again.","api_error",{code:"vault_capture_timeout"}):a;throw this.reportDirectFailure(l,"VAULT_LOAD_FAILED","vault_request","vault_capture","card"),l}finally{clearTimeout(o)}}async getUnifiedCheckoutSession(e,t){let r=await this.getCheckoutSession(e,t),o=this.normalizeRawSession(r.data),s=r.vault;return s&&o.data.session&&(o.data.session.vault=this.toVaultBlock(s)),o}async processPayment(e,t,r){if(this.beginDirectTelemetryCheckout(t.sessionId),!t.nonce)throw this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"process_payment"}),new d.FloPayError("processPayment requires `nonce` \u2014 pass the value returned from session creation.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let o=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.processing.started",stage:"processing",requestCategory:"process_payment"});let{nonce:s,...i}=t,a;try{a=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(t.sessionId)}/process`,{method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":s},body:JSON.stringify(i)})}catch(l){throw this.reportDirectFailure(l,"PAYMENT_PROCESSING_FAILED","processing","process_payment"),l}if(!a.ok&&a.status!==202){let l=await It(a);return l?this.directTelemetry?.terminal({outcome:l,stage:"processing",requestCategory:"process_payment",statusClass:"4xx"}):this.directTelemetry?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",requestCategory:"process_payment",statusClass:(0,d.telemetryStatusClass)(a.status),failureCategory:a.status>=500?"server_error":void 0}),a}try{let l=await this.resolveProcessResponse(a,t.sessionId,{...r,nonce:s});return this.directTelemetry?.log({name:"payment.processing.completed",stage:"processing",requestCategory:"process_payment",statusClass:(0,d.telemetryStatusClass)(l.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"process_payment",statusClass:(0,d.telemetryStatusClass)(l.status)}),l}catch(l){throw l instanceof d.FloPayError&&l.code==="checkout_processing_timeout"||this.reportDirectFailure(l,"PAYMENT_PROCESSING_FAILED","processing","process_payment"),l}}async patchAccountSnapshot(e,t,r,o){this.beginDirectTelemetryCheckout(e);let s=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.state_transition",stage:"processing",requestCategory:"account_snapshot"});let i=o?.timeoutMs??Pt,a=new AbortController,l=()=>a.abort();o?.signal&&(o.signal.aborted?a.abort():o.signal.addEventListener("abort",l,{once:!0}));let c=setTimeout(()=>a.abort(),i);try{let u;try{u=await Te(`${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},ue,y=>{this.telemetryHooks?.onRetry?.("account_snapshot",y),this.directTelemetry?.log({name:"operation.retry",stage:"processing",requestCategory:"account_snapshot",attempt:y})})}finally{clearTimeout(c),o?.signal?.removeEventListener("abort",l)}if(!u.ok)throw await q(u,"Failed to persist account snapshot");this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"account_snapshot",statusClass:"2xx"})}catch(u){throw this.reportAccountSnapshotFailure(u,o?.telemetryMode??"blocking"),u}}async createSessionIntent(e,t,r,o){if(!t)throw new d.FloPayError("createSessionIntent requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let s=r,i=s.paymentMethodType,a=typeof i=="string"&&i.trim().toLowerCase()==="card",l=typeof i=="string"&&i.length>0&&!a&&(typeof s.paymentMethodId=="string"||s.paymentMethodId===null),c=s.provider==="stripe"&&(s.paymentMethodCategory==="wallet"||s.paymentMethodCategory==="apm")&&(s.intentKind==="payment"||s.intentKind==="setup"),u=s.provider==="paypal"&&s.paymentMethodCategory==="wallet"&&s.paymentMethodType==="paypal"&&s.paymentMethodId===null&&s.intentKind==="payment";if(!l||!c&&!u)throw new d.FloPayError("Only wallet, APM, and PayPal session intents are supported.","validation_error",{code:"InvalidSessionIntentRequest"});let y=s.authorizationAttemptId;if(y!==void 0&&!(0,d.isUuidV4)(y))throw new d.FloPayError("authorizationAttemptId must be a v4 UUID identifying one buyer authorization attempt.","validation_error",{code:"InvalidAuthorizationAttemptId",param:"authorizationAttemptId"});let p=(0,d.isUuidV4)(y)?y:(0,d.randomUuidV4)();this.beginDirectTelemetryCheckout(e);let m=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.intent.started",stage:"processing",requestCategory:"intent_create"});let k={"Content-Type":"application/json","x-checkout-session-token":t,[d.IDEMPOTENCY_KEY_HEADER]:o?.idempotencyKey||p},w=!1;try{let b=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents`,{method:"POST",headers:k,body:JSON.stringify({...r,authorizationAttemptId:p}),signal:o?.signal});if(!b.ok){w=!0;let W=await q(b,"Failed to create checkout intent"),te=(0,d.classifyTelemetryFailure)(W,"PAYMENT_PROCESSING_FAILED");throw De(W.statusCode)?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"intent_create",statusClass:"4xx"}):this.directTelemetry?.error({...te,stage:"processing",requestCategory:"intent_create"}),W}let Y=(await b.json()).data;if(!Y||typeof Y!="object")throw new d.FloPayError("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});let g=Y,Z=g.paymentMethodType,ee=(g.paymentMethodCategory==="wallet"||g.paymentMethodCategory==="apm")&&typeof Z=="string"&&Z.trim().toLowerCase()!=="card"&&(typeof g.paymentMethodId=="string"||g.paymentMethodId===null)&&typeof g.providerObjectId=="string",x=g.provider==="stripe"&&(g.intentKind==="payment"||g.intentKind==="setup")&&typeof g.clientSecret=="string",R=g.provider==="paypal"&&g.paymentMethodCategory==="wallet"&&g.paymentMethodType==="paypal"&&g.paymentMethodId===null&&g.intentKind==="payment"&&(g.providerObjectType==="order"||g.providerObjectType==="subscription")&&g.clientSecret===null,N=g.provider===r.provider&&g.paymentMethodCategory===r.paymentMethodCategory&&g.paymentMethodType===r.paymentMethodType&&g.paymentMethodId===r.paymentMethodId&&g.intentKind===r.intentKind;if(!ee||!x&&!R||!N)throw new d.FloPayError("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});return this.directTelemetry?.log({name:"payment.intent.completed",stage:"processing",requestCategory:"intent_create",statusClass:(0,d.telemetryStatusClass)(b.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-m),durationMode:"machine",requestCategory:"intent_create",statusClass:(0,d.telemetryStatusClass)(b.status)}),g}catch(b){throw w||this.reportDirectFailure(b,"PAYMENT_PROCESSING_FAILED","processing","intent_create"),b}}async reportSessionIntentDecline(e,t,r,o){if(!t)throw new d.FloPayError("reportSessionIntentDecline requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let s=r,i=s.providerDeclineReason,a=s.paymentMethodType,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),c=typeof a=="string"&&a.length>0&&a.trim().toLowerCase()!=="card"&&l,u=s.provider==="stripe"&&(s.paymentMethodCategory==="wallet"||s.paymentMethodCategory==="apm"),y=s.provider==="paypal"&&s.paymentMethodCategory==="wallet"&&s.paymentMethodType==="paypal";if(!c||!u&&!y)throw new d.FloPayError("Invalid non-card decline classification.","validation_error",{code:"InvalidSessionIntentDeclineRequest"});let p=y?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:i}:{provider:"stripe",paymentMethodCategory:s.paymentMethodCategory,paymentMethodType:s.paymentMethodType,providerDeclineReason:i},m=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents/decline`,{method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":t},body:JSON.stringify(p),signal:o?.signal});if(!m.ok)throw await q(m,"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 o=t?.page??1,s=t?.limit??1,i=new URLSearchParams({email:e,page:String(o),limit:String(s),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 d.FloPayError("Failed to fetch payments","api_error",{statusCode:a.status});let l=await a.json();return this.directTelemetry?.log({name:"operation.recovery.completed",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),this.directTelemetry?.performance({stage:"recovery",durationMs:Math.max(0,this.telemetryTimestamp()-r),durationMode:"machine",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),l}catch(a){throw this.reportDirectFailure(a,"RECOVERY_FAILED","recovery","other","saved"),a}}async createAndFetchSession(e){if((0,d.isDetachedSessionEligible)(e))return(await this.createDetachedSession(e)).claimed;this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp(),r=O(e.timeoutMs??12e3),o={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});try{let s=await this.createAndFetchSessionRequest(e,t,r.signal,o);return this.adoptDirectTelemetryCheckout(s.data.session?.id),this.directTelemetry?.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:o.statusClass}),this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:"session_create",statusClass:o.statusClass,attempt:o.attempt}),s}catch(s){throw this.reportSessionCreateFailure(s,t,o),s}finally{r.clear()}}async createAndFetchSessionRequest(e,t,r,o){let s=e.products??(0,d.foldIntoProducts)(e.items,e.subscriptions);(0,d.assertCaptureMethodEligible)({captureMethod:e.captureMethod,products:s});let i=(0,d.resolveSessionCurrency)(e.currency,e.items,e.subscriptions,s);if(!i)throw new d.FloPayError("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});let a={clientId:e.clientId,checkoutVersion:d.SDK_VERSION,successUrl:e.successUrl,cancelUrl:e.cancelUrl,currency:i,checkoutMode:e.checkoutMode??"full",products:s.map(p=>(0,d.buildProductPayload)(p,i)),accountData:Oe(e.account),couponCodes:e.couponCodes??[]};e.captureMethod==="manual"&&(a.captureMethod=e.captureMethod),e.tokenizedData&&(a.tokenizedData=e.tokenizedData),qe(a,e);let c=await(await this.postCheckoutSessionCreate(a,e,t,r,o)).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 u=c.data?.uuid;if(!u)throw new d.FloPayError("No session ID returned","api_error",{code:"InvalidCheckoutSessionResponse"});return this.autoCacheDisplayData(u,e),this.adoptDirectTelemetryCheckout(u),{...await this.getUnifiedCheckoutSession(u),autoProcessingError:c.autoProcessingError,autoProcessingAttempted:c.autoProcessingAttempted,autoProcessingPending:c.autoProcessingPending}}async postCheckoutSessionCreate(e,t,r,o,s){let i={"Content-Type":"application/json",[d.FLO_SDK_VERSION_HEADER]:d.SDK_VERSION},a=(0,d.resolveIdempotencyKey)(t.idempotencyKey);a&&(i[d.IDEMPOTENCY_KEY_HEADER]=a);let l,c=!1,u=xt(t),y=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;try{u?.onAttempt?.(p)}catch{}try{l=await fetch(`${this.baseUrl}/v1/checkouts/sessions?expand=true`,{method:"POST",headers:i,body:JSON.stringify(e),signal:o})}catch(w){if(s.statusClass=o.aborted||w instanceof Error&&w.name==="AbortError"?"timeout":"network_error",o.aborted||w instanceof Error&&w.name==="AbortError"||p>=2)throw w;let b=p+1;y(b),await B(p,o);continue}let m=(0,d.telemetryStatusClass)(l.status);if(s.statusClass=m,c||(c=!0,this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:m,attempt:p}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:Math.max(0,this.telemetryTimestamp()-r),durationMode:"machine",requestCategory:"session_create",statusClass:m,attempt:p})),l.status===204)throw new d.FloPayError("Session auto-completed \u2014 payment method already on file","api_error",{code:"session_auto_completed"});if(l.ok)break;let k=await q(l,"Failed to create checkout session");if(k.code===d.IDEMPOTENCY_IN_PROGRESS_CODE&&p<2){y(p+1),await B(p,o);continue}throw k}if(!l)throw new TypeError("Checkout-session creation exhausted its retry budget.");return l}async createDetachedSession(e){this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp(),r=O(e.timeoutMs??12e3),o={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let s=e.products??(0,d.foldIntoProducts)(e.items,e.subscriptions);try{(0,d.assertCaptureMethodEligible)({captureMethod:e.captureMethod,products:s})}catch(m){throw r.clear(),this.reportSessionCreateFailure(m,t,o),m}let i=(0,d.resolveSessionCurrency)(e.currency,e.items,e.subscriptions,s);if(!i)throw r.clear(),this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),new d.FloPayError("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});let a;try{a=Ot(e,i,s)}catch(m){throw r.clear(),this.reportSessionCreateFailure(m,t,o),m}let l,c;try{if(c=await(await this.postCheckoutSessionCreate(Ft(e,i),e,t,r.signal,o)).json(),!c.data||!("gateways"in c.data))throw new d.FloPayError("The billing API returned no session shell for a detached create. It must support `deferDataAttachment` (TeamFloPay/backend#1099).","api_error",{code:"InvalidCheckoutSessionResponse"});l=this.normalizeRawSession(this.mergeCachedDisplayData(c.data)),c.vault&&l.data.session&&(l.data.session.vault=this.toVaultBlock(c.vault))}catch(m){throw r.clear(),this.reportSessionCreateFailure(m,t,o),m}let u=l.data.session?.id??c.data.uuid??"",y=l.data.session?.clientSecret??c.data.nonce??"";if(!u||!y){r.clear();let m=new d.FloPayError("Checkout session shell was created without a session id or nonce.","api_error",{code:"InvalidCheckoutSessionResponse"});throw this.reportSessionCreateFailure(m,t,o),m}this.adoptDirectTelemetryCheckout(u),this.directTelemetry?.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",statusClass:o.statusClass,paymentMethodCategory:"card"}),this.directTelemetry?.performance({stage:"session_shell",durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:"session_create",statusClass:o.statusClass,attempt:o.attempt,paymentMethodCategory:"card"});let p=this.claimCheckoutSession(u,y,a,{params:e,startedAt:t,deadline:r,createAttempt:o.attempt});return p.catch(()=>{}),{shell:l,sessionId:u,nonce:y,claimed:p}}async claimCheckoutSession(e,t,r,o){let s=o?.startedAt??this.telemetryTimestamp(),i=this.telemetryTimestamp(),a=o?.deadline??O(12e3),l=JSON.stringify(r),c="unknown",u=0;this.directTelemetry?.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"});try{let y;for(u=0;u<3;u++){try{y=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/claim`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":t,[d.FLO_SDK_VERSION_HEADER]:d.SDK_VERSION},body:l,signal:a.signal})}catch(k){let w=a.signal.aborted||k instanceof Error&&k.name==="AbortError";if(c=w?"timeout":"network_error",w||u>=2)throw k;try{this.telemetryHooks?.onRetry?.("session_claim",u+1),this.directTelemetry?.log({name:"operation.retry",stage:"session_claim",requestCategory:"session_claim",attempt:u+1})}catch{}await B(u,a.signal);continue}if(c=(0,d.telemetryStatusClass)(y.status),y.ok)break;throw await q(y,"Failed to attach checkout session data")}if(!y)throw new TypeError("Checkout-session claim exhausted its retry budget.");let p=await y.json();if(!p.data||!p.data.gateways)throw new d.FloPayError("The billing API returned no checkout session with gateways after claiming it.","api_error",{code:"InvalidCheckoutSessionResponse"});o?.params&&this.autoCacheDisplayData(p.data.uuid??e,o.params);let m=this.normalizeRawSession(this.mergeCachedDisplayData(p.data));return p.vault&&m.data.session&&(m.data.session.vault=this.toVaultBlock(p.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:u}),this.directTelemetry?.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:c}),this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"session_create",statusClass:c,attempt:o?.createAttempt??u}),m}catch(y){throw this.reportSessionCreateFailure(y,s,{attempt:u,statusClass:c},"session_claim"),y}finally{a.clear()}}reportSessionCreateFailure(e,t,r,o="session_create"){if(!(e instanceof d.FloPayError&&e.code==="session_auto_completed"))try{this.telemetryHooks?.onSessionCreateFailure?.(e)}catch{}let s=(0,d.classifyTelemetryFailure)(e,"CHECKOUT_SESSION_CREATE_FAILED");if(this.directTelemetry?.performance({stage:o,durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:o==="session_claim"?"session_claim":"session_create",statusClass:s.statusClass,attempt:r.attempt}),e instanceof d.FloPayError&&e.type==="validation_error"||e instanceof d.FloPayError&&De(e.statusCode)){this.directTelemetry?.terminal({outcome:"validation_rejected",stage:o,requestCategory:o==="session_claim"?"session_claim":"session_create",...e.type==="validation_error"?{}:{statusClass:"4xx"}});return}e instanceof d.FloPayError&&e.code==="session_auto_completed"||this.directTelemetry?.error({...s,stage:o,requestCategory:o==="session_claim"?"session_claim":"session_create"})}async waitForCheckoutSessionCompletion(e,t){this.beginDirectTelemetryCheckout(e);let r=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:"saved"});let o=t?.timeoutMs??Mt,s=Date.now()+o,i=this.clampRetryAfterMs(t?.initialDelayMs??Ie),a=0;try{for(;;){let l=s-Date.now();if(l<=0)throw de();if(i>0){try{a+=1,this.telemetryHooks?.onRetry?.("session_read",a),this.directTelemetry?.log({name:"operation.retry",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:"saved",attempt:a})}catch{}if(await Fe(Math.min(i,l)),Date.now()>=s)throw de()}let c=await this.getUnifiedCheckoutSession(e,t?.nonce),u=c.data.session?.status;if(u==="authorized"||u==="complete"||u==="expired")return this.directTelemetry?.log({name:"operation.recovery.completed",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:"saved"}),this.directTelemetry?.performance({stage:"recovery",durationMs:Math.max(0,this.telemetryTimestamp()-r),durationMode:"machine",requestCategory:"session_read",paymentMethodCategory:"saved"}),c;if(Date.now()>=s)throw de();i=this.clampRetryAfterMs(Math.max(i*2,bt))}}catch(l){throw l instanceof d.FloPayError&&l.code==="checkout_processing_timeout"&&this.reportDirectFailure(l,"RECOVERY_FAILED","recovery","session_read","saved"),l}}normalizeRawSession(e){let t=e.gateways??{},r=[],o={session:this.toCheckoutSession(e)},s=t.stripe;if(s?.publishableKey){r.push("stripe");let l=[e.stripeClientSecret,s.stripeClientSecret].find(c=>typeof c=="string"&&c.length>0);o.stripe={clientSecret:l??"",publishableKey:s.publishableKey??void 0,paypalPublishableKey:s.paypalPublishableKey??void 0,environment:s.environment,enabledPaymentMethods:Array.isArray(s.enabledPaymentMethods)?s.enabledPaymentMethods.filter(c=>typeof c=="string"):void 0}}let i=t.paypal;return i?.publishableKey&&(r.push("paypal"),o.paypal={publishableKey:i.publishableKey,environment:i.environment}),{providers:r,mode:"tokenize",data:o,raw:{data:e}}}toCheckoutSession(e){let t=e.products??[],r=typeof e.totalAmount=="number"&&Number.isFinite(e.totalAmount),o=t.reduce((c,u)=>c+(u.overrideAmount??u.totalAmount??0),0),s=r?e.totalAmount:o,i=Math.round(s*100),a=e.currency??t[0]?.currency??"USD",l=e.checkoutMode==="setup"?"setup":t.some(c=>c.type==="subscription")?"subscription":"payment";return{id:e.uuid,clientSecret:e.nonce,mode:l,status:this.toCheckoutSessionStatus(e.status),amount:i,currency:a,captureMethod:e.captureMethod,paymentId:e.paymentId,authorizationExpiresAt:e.authorizationExpiresAt,failureOutcome:(0,d.normalizeCheckoutFailureOutcome)(e.outcome)??(0,d.normalizeCheckoutFailureOutcome)(e.failureReason)??(e.status==="expired"&&e.captureMethod==="manual"?"authorization_expired":void 0),customer:{id:e.accountData.userId,email:e.accountData.email,firstName:e.accountData.firstName,lastName:e.accountData.lastName,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},metadata:{},checkoutMode:e.checkoutMode,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 o=await e.json().catch(()=>null),s=this.toCheckoutProcessingPending(o,e,t),i=await this.waitForCheckoutSessionCompletion(s.sessionId,{initialDelayMs:s.retryAfterMs,timeoutMs:r?.pollTimeoutMs,nonce:r?.nonce});if(i.data.session?.status==="complete")return new Response(null,{status:204,statusText:"No Content"});if(i.data.session?.status==="authorized"){let a=i.data.session;return new Response(JSON.stringify({status:"authorized",paymentId:a.paymentId,sessionId:a.id||t,authorizationExpiresAt:a.authorizationExpiresAt}),{status:200,headers:{"Content-Type":"application/json"}})}if(i.data.session?.status==="expired"){let a=i.data.session.failureOutcome==="authorization_expired"||i.data.session.captureMethod==="manual";throw new d.FloPayError(a?"Authorization has expired.":"Checkout session has expired.","api_error",{code:a?"authorization_expired":"checkout_session_expired"})}throw de()}toCheckoutProcessingPending(e,t,r){let o=t.headers.get("Retry-After"),s=o===null||o.trim()===""?void 0:Number(o),i=s!==void 0&&Number.isFinite(s)?s*1e3:void 0;return{type:"checkout_processing",sessionId:j(e,"sessionId")??r,retryAfterMs:this.clampRetryAfterMs(At(e,"retryAfterMs")??i??Ie),statusUrl:j(e,"statusUrl"),sessionUrl:j(e,"sessionUrl")}}clampRetryAfterMs(e){return Math.max(0,Math.min(e,kt))}autoCacheDisplayData(e,t){if(!e)return;let r=t.products??(0,d.foldIntoProducts)(t.items,t.subscriptions);if(r.length===0&&!t.currency)return;let o=t.products!==void 0,s=(0,d.resolveSessionCurrency)(t.currency,o?void 0:t.items,o?void 0:t.subscriptions,r);F(e,{currency:s??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??s??void 0}))})}mergeCachedDisplayData(e){let t=le(e.uuid),r=new Map,o=i=>i?`code:${i}`:void 0;for(let i of t?.products??[]){let a=o(i.code);a&&r.set(a,i)}let s=(e.products??[]).map(i=>{let a=o(i.code),l=a?r.get(a):void 0;return{...i,name:i.name??l?.name??null,totalAmount:i.totalAmount??l?.totalAmount,overrideAmount:i.overrideAmount??l?.overrideAmount,currency:i.currency??l?.currency}});return{...e,currency:e.currency??t?.currency,products:s}}};U.activeVaultCaptureRequests=new Map;var I=U;function Ue(n,e){let t=I;return new t(n,e)}function Le(n){return{payment:"payment",address:"address"}[n]}function J(n){switch(n){case"night":return"night";case"flat":return"flat";default:return"stripe"}}function ze(n){return{...n,theme:J(n.theme)}}function we(n){return n?JSON.stringify(n.map(e=>e.trim().toLowerCase())):null}function Ne(n){let e=n;return{mount(t){e.mount(t)},unmount(){e.unmount()},update(t){e.update(t)},on(t,r){e.on?.(t,r)},off(t,r){e.off?.(t,r)},destroy(){e.destroy()}}}function qt(n){return{billing_details:{...n.email?{email:n.email}:{},...n.name?{name:n.name}:{},...n.address?{address:{...n.address.country?{country:n.address.country}:{},...n.address.postal_code?{postal_code:n.address.postal_code}:{},...n.address.city?{city:n.address.city}:{},...n.address.line1?{line1:n.address.line1}:{},...n.address.line2?{line2:n.address.line2}:{},...n.address.state?{state:n.address.state}:{}}}:{}}}}var K=class{constructor(){this.name="stripe";this.stripe=null;this.elements=null;this.appliedAppearanceKey=null;this.appliedPaymentMethodTypesKey=null;this.appliedClientSecret=null;this.verifiedClientSecret=null;this.verifiedPaymentMethodTypesKey=null}async initialize(e){if(typeof window>"u")return;let t=await(0,Ve.loadStripe)(e.publishableKey,{locale:e.locale??"auto"});if(!t)throw new f.FloPayError("Failed to initialize Stripe. Check your publishable key.","authentication_error");this.stripe=t}getElements(e){if(!this.stripe)throw new f.FloPayError("StripeAdapter not initialized. Call initialize() first.","api_error");let t=e?.appearance?{theme:J(e.appearance.theme),variables:e.appearance.variables,rules:e.appearance.rules}:void 0,r=t?JSON.stringify(t):null,o=we(e?.paymentMethodTypes),s=e?.clientSecret??null;if(this.elements&&o&&(o!==this.appliedPaymentMethodTypesKey||s!==this.appliedClientSecret)&&(this.elements=null,this.appliedAppearanceKey=null,this.appliedPaymentMethodTypesKey=null,this.appliedClientSecret=null,this.verifiedClientSecret=null,this.verifiedPaymentMethodTypesKey=null),this.elements)r!==this.appliedAppearanceKey&&(this.elements.update({appearance:t??{}}),this.appliedAppearanceKey=r);else{let i,a=e?.amount??0,l=(e?.currency??"usd").toLowerCase(),c=e?.paymentMethodCreation??"manual";e?.clientSecret?i={clientSecret:e.clientSecret}:a>0?(i={mode:"payment",amount:a,currency:l,paymentMethodCreation:c},e?.setupFutureUsage&&(i.setupFutureUsage=e.setupFutureUsage)):i={mode:"setup",currency:l,paymentMethodCreation:c},!e?.clientSecret&&e?.paymentMethodTypes&&(i.paymentMethodTypes=e.paymentMethodTypes),t&&(i.appearance=t),this.elements=this.stripe.elements(i),this.appliedAppearanceKey=r,this.appliedPaymentMethodTypesKey=o,this.appliedClientSecret=s,this.verifiedClientSecret=null,this.verifiedPaymentMethodTypesKey=null}return this.elements}async assertClientSecretPaymentMethods(e,t){if(!this.stripe)throw new f.FloPayError("StripeAdapter not initialized. Call initialize() first.","api_error");let r,o=!1;if((0,f.isSetupIntentClientSecret)(e)){let{setupIntent:l,error:c}=await this.stripe.retrieveSetupIntent(e);r=l,o=!!c}else{let{paymentIntent:l,error:c}=await this.stripe.retrievePaymentIntent(e);r=l,o=!!c}let s=r?.payment_method_types;if(o||!Array.isArray(s))throw new f.FloPayError("Unable to verify the payment methods configured for this client secret.","api_error",{param:"clientSecret"});let i=new Set(t.map(l=>l.toLowerCase()));if(s.some(l=>typeof l!="string"||!i.has(l.trim().toLowerCase()))||s.length===0)throw new f.FloPayError("The client-secret intent must enable only declared non-card payment methods.","validation_error",{param:"clientSecret"})}async createElement(e,t){let r=t;if(e==="payment"){let l=t.paymentMethodTypes?.map(c=>c.trim()).filter(c=>c&&c.toLowerCase()!=="card");if(!l?.length)throw new f.FloPayError("At least one supported non-card payment method is required.","validation_error",{param:"paymentMethodTypes"});if(r={...t,paymentMethodTypes:l},r.clientSecret){let c=we(l);this.elements&&this.appliedClientSecret===r.clientSecret&&this.appliedPaymentMethodTypesKey===c&&this.verifiedClientSecret===r.clientSecret&&this.verifiedPaymentMethodTypesKey===c||await this.assertClientSecretPaymentMethods(r.clientSecret,l)}}let o=this.getElements(r);e==="payment"&&r.clientSecret&&(this.verifiedClientSecret=r.clientSecret,this.verifiedPaymentMethodTypesKey=we(r.paymentMethodTypes));let s=Le(e),i={};r.layout&&(i.layout=r.layout),r.defaultValues&&(i.defaultValues=r.defaultValues),r.readOnly&&(i.readOnly=r.readOnly),r.mode&&(i.mode=r.mode);let a=o.create(s,i);return Ne(a)}getElement(e){if(!this.elements)return null;let t=Le(e),r=this.elements.getElement(t);return r?Ne(r):null}async submitElements(){if(!this.stripe||!this.elements)return{error:new f.FloPayError("Stripe not initialized","api_error")};let{error:e}=await this.elements.submit();return e?{error:new f.FloPayError(e.message??"Validation failed","validation_error")}:{}}async confirmPayment(e){if(!this.stripe||!this.elements)throw new f.FloPayError("StripeAdapter not initialized or no elements created.","api_error");let t=e.billingDetails,r=t?qt(t):void 0,{error:o,paymentIntent:s}=await this.stripe.confirmPayment({elements:this.elements,clientSecret:e.clientSecret,confirmParams:{return_url:e.returnUrl??window.location.href,...r?{payment_method_data:r}:{}},redirect:"if_required"});return o?{status:"failed",error:new f.FloPayError(o.message??"Payment failed","api_error",{code:o.code,declineCode:o.decline_code})}:s?{status:{succeeded:"succeeded",processing:"processing",requires_action:"requires_action",requires_payment_method:"failed",canceled:"failed"}[s.status]??"failed",paymentIntentId:s.id,paymentMethodId:this.extractPaymentMethodId(s.payment_method)}:{status:"failed",error:new f.FloPayError("No payment intent returned","api_error")}}extractPaymentMethodId(e){if(typeof e=="string"&&e.startsWith("pm_"))return e;if(e&&typeof e=="object"&&typeof e.id=="string")return e.id}async confirmPayPalPayment(e){if(!this.stripe)return{status:"failed",error:new f.FloPayError("Stripe not initialized","api_error")};let t=e.billingApiUrl.replace(/\/+$/,"");if(this.elements){let{error:s}=await this.elements.submit();if(s)return{status:"failed",error:new f.FloPayError(s.message??"PayPal payment failed","validation_error",{code:s.code})}}let r;try{let s=await new I(t).createSessionIntent(e.sessionId,e.nonce??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"});if(s.provider!=="stripe")throw new f.FloPayError("Invalid provider returned for PayPal intent","api_error");r=s.clientSecret}catch(s){return{status:"failed",error:s instanceof f.FloPayError?s:new f.FloPayError("Failed to create PayPal payment intent","api_error")}}let{error:o}=await this.stripe.confirmPayment({clientSecret:r,elements:this.elements??void 0,confirmParams:{return_url:e.returnUrl}});if(o){if(e.nonce)try{await new I(t).reportSessionIntentDecline(e.sessionId,e.nonce,{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:o.code??"provider_declined"})}catch{}return{status:"failed",error:new f.FloPayError(o.message??"PayPal payment failed","api_error",{code:o.code})}}return{status:"processing"}}async resumePayPalPayment(){if(!this.stripe||typeof window>"u")return null;let e=new URLSearchParams(window.location.search),t=e.get("payment_intent"),r=e.get("payment_intent_client_secret"),o=e.get("redirect_status");if(!t||!r)return null;if(o==="failed")return{status:"failed",error:new f.FloPayError("PayPal payment was declined. Please try again.","api_error")};let{paymentIntent:s,error:i}=await this.stripe.retrievePaymentIntent(r);if(i)return{status:"failed",error:new f.FloPayError(i.message??"Failed to retrieve PayPal payment","api_error")};if(s&&(0,f.isMoneySettledOutcome)(s.status)){let a=typeof s.payment_method=="string"?s.payment_method:s.payment_method?.id,l=new URL(window.location.href);return l.searchParams.delete("payment_intent"),l.searchParams.delete("payment_intent_client_secret"),l.searchParams.delete("redirect_status"),window.history.replaceState({},"",l.toString()),{status:s.status,paymentIntentId:s.id,paymentMethodId:a}}return{status:"failed",error:new f.FloPayError("PayPal payment was not completed. Please try again.","api_error")}}getRawProvider(){return this.stripe}createPayPalElements(e){if(!this.stripe)return null;let t={mode:"payment",amount:e.amount??0,currency:(e.currency??"usd").toLowerCase(),captureMethod:"manual"};return e.setupFutureUsage&&(t.setupFutureUsage=e.setupFutureUsage),e.appearance&&(t.appearance={theme:J(e.appearance.theme),variables:e.appearance.variables,rules:e.appearance.rules}),this.stripe.elements(t)}destroy(){this.elements=null,this.appliedAppearanceKey=null,this.appliedPaymentMethodTypesKey=null,this.appliedClientSecret=null,this.verifiedClientSecret=null,this.verifiedPaymentMethodTypesKey=null,this.stripe=null}};var C=require("@flopay/shared");var Be=require("@flopay/shared"),H=class{constructor(e,t){this.elementMap=new Map;this.provider=e,this.baseOptions=t??{}}async create(e,t){let r={...this.baseOptions,...t};if(e==="payment"){let a=r.paymentMethodTypes?.map(l=>l.trim()).filter(l=>l&&l.toLowerCase()!=="card");if(!a?.length)throw new Be.FloPayError("At least one supported non-card payment method is required.","validation_error",{param:"paymentMethodTypes"});r.paymentMethodTypes=a}let o=this.provider.getElement(e);if(o)return this.elementMap.set(e,o),o;let s=this.elementMap.get(e);s&&s.destroy();let i=await this.provider.createElement(e,r);return this.elementMap.set(e,i),i}getElement(e){return this.elementMap.get(e)??null}async submit(){return{}}destroy(){for(let e of this.elementMap.values())e.destroy();this.elementMap.clear()}};var T=require("@flopay/shared");var Se="flopay-vault",je={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 Q(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:n.class==="lifecycle"?n.name:n.class==="technical_error"?n.code:n.class==="expected_outcome"?n.outcome:"sdk.performance",data:e})}catch{}}function pe(n,e){return(0,T.buildTelemetryLogEvent)({eventId:"11111111-1111-4111-8111-111111111111",name:n,stage:e,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}function Ke(n){return n?{errorCode:"VAULT_SUBMIT_FAILED",stage:"vault_submit",failureCategory:"provider_runtime"}:{errorCode:"VAULT_LOAD_FAILED",stage:"vault_mount",failureCategory:"provider_runtime"}}function He(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 Ut(n,e,t,r="checkout"){let{type:o}=n;if(o==="complete"||o==="decline")return(0,T.buildTelemetryTerminalEvent)({eventId:"22222222-2222-4222-8222-222222222222",outcome:He(n,t,r),sequence:0,provider:"pcivault",paymentMethodCategory:"card"});if(o==="error"){let a=Ke(e);return(0,T.buildTelemetryErrorEvent)({eventId:"33333333-3333-4333-8333-333333333333",...a,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}let[s,i]=je[o];return pe(s,i)}function Lt(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===Se&&(e.type==="ready"||e.type==="submitting"||e.type==="blocked"||e.type==="complete"||e.type==="decline"||e.type==="error"||e.type==="action_required")}function Nt(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 Vt(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===Se&&e.type==="validation"&&Array.isArray(e.messages)}function zt(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===Se&&e.type==="resize"&&typeof e.height=="number"&&Number.isFinite(e.height)}var L=class{constructor(e={},t){this.provider="pcivault";this.container=null;this.messageHandler=null;this.actionOverlay=null;this.threeDsReturnHandler=null;this.messageToken=null;this.expectedOrigin=null;this.theme=null;this.submitGateBlocked=!1;this.cardFieldOrder=null;this.cardAutoFocus=!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:(0,T.resolveBillingApiUrl)(),sdkVersion:T.SDK_VERSION}):void 0)}async mount(e,t){this.ownsTelemetryReporter&&!this.telemetryReporter&&(this.telemetryReporter=new _({billingApiUrl:(0,T.resolveBillingApiUrl)(),sdkVersion:T.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?.()??M(),this.vaultReadyReported=!1,this.submissionStarted=!1,this.submissionStartedAt=null,typeof window>"u"||typeof document>"u")throw this.reportVaultLoadFailure(),new T.FloPayError("The vault card form is only available in the browser.","api_error",{code:"card_capture_no_window"});if(!t?.html||!t.html.trim())throw this.reportVaultLoadFailure(),new T.FloPayError("No vault capture widget HTML was provided to mount the secure card form.","api_error",{code:"card_capture_no_widget_html"});this.container=e,this.messageToken=t.messageToken??null,this.expectedOrigin=t.expectedOrigin??this.config.expectedOrigin??null,this.theme=t.theme??null;try{this.attachMessageListener(),this.injectWidget(e,t.html)}catch(o){throw this.reportVaultLoadFailure(),o}this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),Q(pe("vault.widget.mounted","vault_mount")),this.telemetryReporter?.log({name:"vault.widget.mounted",stage:"vault_mount",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 o of r){let s=document.createElement("script");for(let i of Array.from(o.attributes))s.setAttribute(i.name,i.value);s.text=o.text,o.replaceWith(s)}}attachMessageListener(){if(this.messageHandler)return;let e=t=>{if(this.expectedOrigin&&t.origin!==this.expectedOrigin)return;let r=t.data;if(zt(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;this.applyHeight(r.height);return}if(Vt(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;let l=r.messages.filter(c=>typeof c=="string"&&c.trim()).join(" ");this.emit("validation",{sessionId:this.config.sessionId,message:l||void 0});return}if(!Lt(r)||this.messageToken&&r.messageToken!==this.messageToken)return;let o=this.config.sessionId,s=typeof r.sessionId=="string"?r.sessionId:void 0;if(o&&s&&s!==o||(r.type==="complete"||r.type==="decline")&&o&&s!==o)return;let i=Nt(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?.()??M()),Q(Ut(r,this.submissionStarted,this.config.captureMethod,this.config.operation)),this.reportOutcome(r),r.type==="ready"&&(this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder()),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"})),r==="complete"||r==="decline"){t.log({name:"vault.terminal",stage:"completion",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:He(e,this.config.captureMethod,this.config.operation),provider:"pcivault",paymentMethodCategory:"card"});return}if(r==="error"){let i=Ke(this.submissionStarted);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[o,s]=je[r];t.log({name:o,stage:s,provider:"pcivault",paymentMethodCategory:"card"})}applyTheme(e){this.theme=e,this.postTheme()}postTheme(){if(!this.theme||!this.container)return;let t=this.container.querySelector("iframe")?.contentWindow;if(t)try{t.postMessage({source:"flopay-vault-host",type:"theme",theme:this.theme},"*")}catch{}}setSubmitGate(e){this.submitGateBlocked=e,this.postSubmitGate()}postSubmitGate(){if(!this.container)return;let t=this.container.querySelector("iframe")?.contentWindow;if(t)try{t.postMessage({source:"flopay-vault-host",type:"gate",blocked:this.submitGateBlocked},"*")}catch{}}setCardFieldOrder(e,t){this.cardFieldOrder=e,this.cardAutoFocus=t,this.postCardFieldOrder()}postCardFieldOrder(){if(!this.container)return;let t=this.container.querySelector("iframe")?.contentWindow;if(t)try{t.postMessage({source:"flopay-vault-host",type:"fieldOrder",order:this.cardFieldOrder,autoFocus:this.cardAutoFocus},"*")}catch{}}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);return}let t=document.createElement("div");t.setAttribute("data-flopay-action-required","1"),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.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 o=document.createElement("button");o.type="button",o.setAttribute("aria-label","Close card authentication"),o.textContent="\xD7",o.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(";"),o.addEventListener("click",()=>this.abandonActionRequiredOverlay()),t.appendChild(o),t.addEventListener("click",i=>{i.target===t&&this.abandonActionRequiredOverlay()});let s=i=>{if(i.source!==r.contentWindow)return;let a=i.data;if(!a||typeof a!="object")return;let l=a;l.source==="flopay-vault-3ds-return"&&(Q(pe("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(),this.postActionCompleted(l.status))};window.addEventListener("message",s),this.threeDsReturnHandler=s,document.body.appendChild(t),this.actionOverlay=t,Q(pe("vault.three_ds.handoff","three_ds_handoff"))}postActionCompleted(e){if(!this.container)return;let r=this.container.querySelector("iframe")?.contentWindow;if(r)try{r.postMessage({source:"flopay-vault-host",type:"action_completed",status:typeof e=="string"?e:"unknown"},"*")}catch{}}abandonActionRequiredOverlay(){if(!this.actionOverlay)return;let e=(0,T.buildTelemetryTerminalEvent)({eventId:"77777777-7777-4777-8777-777777777777",outcome:"customer_abandoned",stage:"three_ds_handoff",sequence:0,provider:"pcivault",paymentMethodCategory:"card"});Q(e),this.telemetryReporter?.terminal({outcome:"customer_abandoned",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"}),this.hideActionRequiredOverlay(),this.postActionCompleted("abandoned")}hideActionRequiredOverlay(){this.threeDsReturnHandler&&(window.removeEventListener("message",this.threeDsReturnHandler),this.threeDsReturnHandler=null),this.actionOverlay&&(this.actionOverlay.parentNode?.removeChild(this.actionOverlay),this.actionOverlay=null)}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 $e(n,e){let t=L;return new t(n,{reporter:e})}var Ge=Symbol.for("@flopay/js.telemetry.bridge.v1");function Ye(n,e,t){let r=()=>e?.now()??t();Object.defineProperty(n,Ge,{configurable:!1,enumerable:!1,writable:!1,value:{error:s=>e?.error(s),log:s=>e?.log(s),performance:s=>e?.performance(s),terminal:s=>e?.terminal(s),now:r,elapsed:s=>Math.max(0,r()-s),setCheckoutContext:s=>e?.setCheckoutContext(s),beginCheckout:(s={})=>e?.beginCheckout(s)??r(),disable:()=>e?.disable()}})}function We(n){return n[Ge]}function $(n){if(!n)return!1;let e=n.code?.toLowerCase()??"";return!!n.declineCode||e.includes("declin")}function Bt(n){return n==="stripe"||n==="paypal"||n==="pcivault"?n:"other"}var X=class{constructor(e,t,r){this.currentElements=null;this.provider=e,this.config=t,this.telemetryReporter=r??new _({billingApiUrl:(0,C.resolveBillingApiUrl)(t.billingApiUrl),sdkVersion:C.SDK_VERSION,enabled:t.telemetry!==!1}),Ye(this,this.telemetryReporter,M)}now(){return this.telemetryReporter?.now?.()??M()}elements(e){return this.currentElements&&this.currentElements.destroy(),this.currentElements=new H(this.provider,{appearance:this.config.appearance,...e}),this.currentElements}async submitElements(){return this.provider.submitElements()}cardCapture(e){return this.telemetryReporter?.log({name:"vault.capture.requested",stage:"vault_request",provider:"pcivault",paymentMethodCategory:"card"}),this.telemetryReporter?$e({sessionId:e?.sessionId,captureMethod:e?.captureMethod},this.telemetryReporter):new L({sessionId:e?.sessionId,captureMethod:e?.captureMethod,telemetry:!1})}async confirmPayPalPayment(e){let t=this.now();this.telemetryReporter?.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),this.telemetryReporter?.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});try{let r=await this.provider.confirmPayPalPayment(e);return this.telemetryReporter?.performance({stage:"processing",durationMs:this.now()-t,durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),r.error||this.telemetryReporter?.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),r.status==="requires_action"?(this.telemetryReporter?.log({name:"provider.redirect.started",stage:"redirect",provider:"paypal",paymentMethodCategory:"paypal"}),this.telemetryReporter?.terminal({outcome:"action_required",stage:"redirect",provider:"paypal",paymentMethodCategory:"paypal"})):r.status==="succeeded"?this.telemetryReporter?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}):r.status!=="processing"&&($(r.error)?this.telemetryReporter?.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):r.error?.type==="validation_error"?this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal"}):r.error&&this.telemetryReporter?.error({errorCode:"PAYMENT_PROCESSING_FAILED",failureCategory:"provider_runtime",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"})),r}catch(r){if(this.telemetryReporter?.performance({stage:"processing",durationMs:this.now()-t,durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),r instanceof C.FloPayError&&$(r))this.telemetryReporter?.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"});else if(r instanceof C.FloPayError&&r.type==="validation_error")this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal"});else{let o=(0,C.classifyTelemetryFailure)(r,"PAYMENT_PROCESSING_FAILED","unknown");this.telemetryReporter?.error({...o,failureCategory:o.failureCategory??"provider_runtime",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"})}throw r}}async resumePayPalPayment(){let e=this.now();try{let t=await this.provider.resumePayPalPayment();return t===null?null:(this.telemetryReporter?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),this.telemetryReporter?.performance({stage:"redirect_resume",durationMs:this.now()-e,durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),t.status==="succeeded"?this.telemetryReporter?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}):$(t.error)?this.telemetryReporter?.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):t.error?.type==="validation_error"?this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal"}):t.error&&this.telemetryReporter?.error({errorCode:"REDIRECT_RESUME_FAILED",failureCategory:"provider_runtime",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),t)}catch(t){if(this.telemetryReporter?.performance({stage:"redirect_resume",durationMs:this.now()-e,durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),t instanceof C.FloPayError&&$(t))this.telemetryReporter?.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"});else if(t instanceof C.FloPayError&&t.type==="validation_error")this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal"});else{let r=(0,C.classifyTelemetryFailure)(t,"REDIRECT_RESUME_FAILED","unknown");this.telemetryReporter?.error({...r,failureCategory:r.failureCategory??"provider_runtime",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"})}throw t}}async confirmPayment(e){if(e.paymentMethodCategory!=="wallet"&&e.paymentMethodCategory!=="apm"||!e.paymentMethodType?.trim()||e.paymentMethodType.trim().toLowerCase()==="card")throw new C.FloPayError("A supported non-card payment method is required.","validation_error",{param:"paymentMethodType"});let t=this.now(),r=Bt(this.provider.name);this.telemetryReporter?.log({name:"payment.processing.started",stage:"processing",provider:r,paymentMethodCategory:e.paymentMethodCategory});try{let o=await this.provider.confirmPayment(e),s=this.now()-t;return this.telemetryReporter?.performance({stage:"processing",durationMs:s,durationMode:"machine",provider:r,paymentMethodCategory:e.paymentMethodCategory}),o.status==="succeeded"?this.telemetryReporter?.terminal({outcome:"payment_succeeded",provider:r,paymentMethodCategory:e.paymentMethodCategory}):$(o.error)?this.telemetryReporter?.terminal({outcome:"payment_declined",provider:r,paymentMethodCategory:e.paymentMethodCategory}):o.error?.type==="validation_error"?this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:r,paymentMethodCategory:e.paymentMethodCategory}):o.status==="requires_action"?this.telemetryReporter?.terminal({outcome:"action_required",stage:"three_ds_handoff",provider:r,paymentMethodCategory:e.paymentMethodCategory}):o.status==="failed"&&o.error&&this.telemetryReporter?.error({errorCode:"PAYMENT_PROCESSING_FAILED",failureCategory:"provider_runtime",stage:"processing",provider:r,paymentMethodCategory:e.paymentMethodCategory}),o.status==="succeeded"||o.status==="failed"?this.telemetryReporter?.log({name:"payment.processing.completed",stage:"processing",provider:r,paymentMethodCategory:e.paymentMethodCategory}):this.telemetryReporter?.log({name:"operation.state_transition",stage:o.status==="requires_action"?"three_ds_handoff":"processing",provider:r,paymentMethodCategory:e.paymentMethodCategory}),o}catch(o){throw this.telemetryReporter?.performance({stage:"processing",durationMs:this.now()-t,durationMode:"machine",provider:r,paymentMethodCategory:e.paymentMethodCategory}),o instanceof C.FloPayError&&$(o)?this.telemetryReporter?.terminal({outcome:"payment_declined",provider:r,paymentMethodCategory:e.paymentMethodCategory}):o instanceof C.FloPayError&&o.type==="validation_error"?this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:r,paymentMethodCategory:e.paymentMethodCategory}):this.telemetryReporter?.error({errorCode:"PAYMENT_PROCESSING_FAILED",failureCategory:"provider_runtime",stage:"processing",provider:r,paymentMethodCategory:e.paymentMethodCategory}),o}}async retrieveSession(e,t){if(!e)throw new C.FloPayError("sessionId is required to retrieve a session.","validation_error",{param:"sessionId"});let r=await this.retrieveUnifiedSession(e,t);if(!r.data.session)throw new C.FloPayError("Session not found","api_error");return r.data.session}async retrieveUnifiedSession(e,t){if(!e)throw new C.FloPayError("sessionId is required.","validation_error",{param:"sessionId"});let r=(0,C.resolveBillingApiUrl)(t??this.config.billingApiUrl),o=this.now();this.telemetryReporter?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let s,i=Ue(r,{now:()=>this.telemetryReporter?.now()??M(),onFirstByte:a=>{s=a},onRetry:(a,l)=>{this.telemetryReporter?.log({name:"operation.retry",stage:a==="session_read"?"session_read":"processing",requestCategory:a,attempt:l})}});try{let a=await i.getUnifiedCheckoutSession(e);return s!==void 0&&(this.telemetryReporter?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:"2xx"}),this.telemetryReporter?.performance({stage:"session_first_byte",durationMs:s,durationMode:"machine",requestCategory:"session_read",statusClass:"2xx"})),this.telemetryReporter?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:"2xx"}),this.telemetryReporter?.log({name:"checkout.data.ready",stage:"checkout_data_ready"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-o,durationMode:"machine",requestCategory:"session_read",statusClass:"2xx"}),a}catch(a){let l=(0,C.classifyTelemetryFailure)(a,a instanceof C.FloPayError&&a.code==="checkout_processing_timeout"?"REQUEST_TIMEOUT":"NETWORK_REQUEST_FAILED");throw this.telemetryReporter?.error({...l,stage:"session_read",provider:"flo",paymentMethodCategory:"unknown"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-o,durationMode:"machine",requestCategory:"session_read",statusClass:l.statusClass}),a}}getRawProvider(){return this.provider.getRawProvider()}destroy(){this.telemetryReporter?.log({name:"checkout.unmount",stage:"unmount"}),this.telemetryReporter?.destroy(),this.currentElements?.destroy(),this.currentElements=null,this.provider.destroy()}};function Je(n,e,t){let r=X;return new r(n,e,t)}var Qe=new Map;function be(n){return Array.isArray(n)?n.map(be):n&&typeof n=="object"?Object.fromEntries(Object.entries(n).filter(([,e])=>e!==void 0).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,be(t)])):n}function jt(n,e){return JSON.stringify([n,(0,E.resolveBillingApiUrl)(e?.billingApiUrl),e?.telemetry!==!1,e?.locale??"auto",e?.apiVersion??null,be(e?.appearance??null)])}var me=new Map;async function Xe(n,e){if(!n){let a=new _({billingApiUrl:(0,E.resolveBillingApiUrl)(e?.billingApiUrl),sdkVersion:E.SDK_VERSION,enabled:e?.telemetry!==!1});throw a.error({errorCode:"CONFIGURATION_INVALID",stage:"sdk_initialize",paymentMethodCategory:"unknown"}),a.flush().catch(()=>{}).finally(()=>a.destroy()),new E.FloPayError("A publishable key is required to initialize FloPay.","validation_error",{param:"publishableKey"})}let t=jt(n,e),r=Qe.get(t);if(r)return e?.telemetry!==!1&&We(r)?.log({name:"sdk.cache.hit",stage:"sdk_initialize"}),r;let o=me.get(t);if(o)return o;let s={...e,publishableKey:n},i=(async()=>{let a=new _({billingApiUrl:(0,E.resolveBillingApiUrl)(s.billingApiUrl),sdkVersion:E.SDK_VERSION,enabled:s.telemetry!==!1}),l=a.now();a.log({name:"sdk.initialize.started",stage:"sdk_initialize"}),a.log({name:"sdk.cache.miss",stage:"sdk_initialize"}),a.log({name:"provider.load.started",stage:"provider_load",provider:"stripe"});let c=new K,u=a.now();try{await c.initialize(s)}catch(m){throw a.error({errorCode:"SDK_INITIALIZATION_FAILED",failureCategory:"provider_runtime",stage:"sdk_initialize",provider:"stripe",paymentMethodCategory:"unknown"}),a.destroy(),m}let y=a.now();a.log({name:"provider.ready",stage:"provider_ready",provider:"stripe"}),a.log({name:"provider.availability.checked",stage:"provider_ready",provider:"stripe"}),a.log({name:"sdk.initialize.ready",stage:"sdk_initialize"}),a.performance({stage:"sdk_initialize",durationMs:y-l,durationMode:"machine",provider:"stripe"}),a.performance({stage:"provider_ready",durationMs:y-u,durationMode:"machine",provider:"stripe"});let p=Je(c,s,a);return Qe.set(t,p),p})();me.set(t,i);try{return await i}finally{me.get(t)===i&&me.delete(t)}}var h=require("@flopay/shared");var Me=5,Ze=new WeakSet;function Kt(n){(typeof n=="object"&&n!==null||typeof n=="function")&&Ze.add(n)}function Ht(n){return(typeof n=="object"&&n!==null||typeof n=="function")&&Ze.has(n)}function $t(n,e){let t=e?.error,r=D(e?.code)??D(t?.code)??`http_${n}`,o=D(e?.message)??D(t?.message)??Gt(r,n);return new h.FloPayError(o,"api_error",{code:r,statusCode:n})}function Gt(n,e){switch(n){case"CouponLimitExceeded":return`Too many coupon codes \u2014 a checkout session accepts at most ${Me}.`;case"CouponCurrencyUnsupported":return"One of the applied coupons has no price configured for the cart currency.";default:return`Failed to create checkout session (HTTP ${e}).`}}async function et(n,e,t){let{billingApiUrl:r,checkoutBaseUrl:o,items:s=[],subscriptions:i=[],products:a,account:l,successUrl:c,cancelUrl:u,checkoutMode:y="confirm",captureMethod:p,couponCodes:m=[],tagsData:k,redirectParams:w={},setCookie:b=!0,clientId:ke,currency:Y,utmMetadata:g,idempotencyKey:Z}=n,ee=(0,h.resolveIdempotencyKey)(Z);if(m.length>Me)throw new h.FloPayError(`Too many coupon codes \u2014 a checkout session accepts at most ${Me}.`,"validation_error",{code:"CouponLimitExceeded",param:"couponCodes"});let x=a??(0,h.foldIntoProducts)(s,i);(0,h.assertCaptureMethodEligible)({captureMethod:p,products:x});let R=(0,h.resolveSessionCurrency)(Y,s,i,x);if(!R)throw new h.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 N={clientId:ke,checkoutVersion:h.SDK_VERSION,successUrl:c,cancelUrl:u,currency:R,checkoutMode:y,products:x.map(A=>(0,h.buildProductPayload)(A,R)),accountData:{userId:l.userId,firstName:l.firstName??null,lastName:l.lastName??null,email:l.email,country:l.country??null,gender:l.gender??null,city:l.city??null,state:l.state??null,zip:l.zip??null,addressLine1:l.addressLine1??null,addressLine2:l.addressLine2??null},couponCodes:m};p==="manual"&&(N.captureMethod=p),k&&(N.tagsData=k),g?.length&&(N.utmMetadata=g);let W=`${r.replace(/\/+$/,"")}/v1/checkouts/sessions`,te={"Content-Type":"application/json"};ee&&(te[h.IDEMPOTENCY_KEY_HEADER]=ee);let V,re,at={method:"POST",headers:te,body:JSON.stringify(N),signal:e},ne;try{ne=await fetch(W,at)}catch(A){throw Kt(A),A}try{t?.(ne.status)}catch{}V=ne.status;try{re=await ne.json()}catch{}if(V>=400)throw $t(V,re);if(V===201){let A=re?.data?.uuid,he=re?.data?.nonce;if(!A)throw new Error("Checkout session created but no UUID was returned by the billing API");if(!he)throw new h.FloPayError("Checkout session created but no `nonce` was returned by the billing API. Upgrade the billing service to TeamFloPay/backend#640 or later.","api_error",{code:"MissingCheckoutSessionToken"});(x.length||R)&&F(A,{currency:R,products:x.map(v=>({code:v.code??v.providerItemId??v.providerPlanId,type:v.type,name:v.name??v.itemName??v.providerItemName??v.subscriptionName??v.providerPlanName??null,totalAmount:v.totalAmount,overrideAmount:v.overrideAmount,currency:v.currency??R}))});let oe=new URL(`${o.replace(/\/+$/,"")}/secure`);oe.searchParams.set("id",A);for(let[v,se]of Object.entries(w))oe.searchParams.set(v,se);if(b&&typeof window<"u"&&typeof document<"u"){let v=JSON.stringify({origin_url:u}),se=window.location.hostname.split(".").slice(-2).join(".");document.cookie=`checkout_data=${encodeURIComponent(v)}; domain=.${se}; path=/; max-age=3600; SameSite=Lax; Secure;`,document.cookie=`flopay_checkout_token=${encodeURIComponent(he)}; domain=.${se}; path=/; max-age=3600; SameSite=Lax; Secure;`}return typeof window<"u"&&(window.location.href=oe.toString()),{status:201,redirectUrl:oe.toString(),nonce:he}}return V===204?(typeof window<"u"&&(window.location.href=c),{status:204}):{status:V}}async function tt(n){let e=nt(n),t=rt(e),r=O(n.timeoutMs);try{let o=await et(n,r.signal,t);return ot(e,o),o}catch(o){throw ye(e,o),o}finally{r.clear(),G(e.reporter)}}function rt(n){let e=!1;return t=>{if(e)return;e=!0;let r=(0,h.telemetryStatusClass)(t);n.reporter.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:r,attempt:n.attempt}),n.reporter.performance({stage:"session_first_byte",durationMs:n.reporter.now()-n.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:r,attempt:n.attempt})}}function nt(n){let e=new _({billingApiUrl:n.billingApiUrl,sdkVersion:h.SDK_VERSION,enabled:n.telemetry!==!1}),t=e.now();return e.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"}),{reporter:e,startedAt:t,attempt:0}}function ot(n,e){let t=(0,h.telemetryStatusClass)(e.status);n.reporter.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:t}),n.reporter.performance({stage:"session_create",durationMs:n.reporter.now()-n.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:t,attempt:n.attempt})}function ye(n,e){let{reporter:t}=n,r=(0,h.classifyTelemetryFailure)(e,"CHECKOUT_SESSION_CREATE_FAILED");if(t.performance({stage:"session_create",durationMs:t.now()-n.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:r.statusClass,attempt:n.attempt}),e instanceof h.FloPayError&&e.type==="validation_error"){t.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"});return}if(r.statusClass==="4xx"){t.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create",statusClass:"4xx"});return}t.error({...r,stage:"session_create",requestCategory:"session_create"})}function G(n){n.flush().catch(()=>{}).finally(()=>n.destroy())}async function st(n){let{maxRetries:e=2,...t}=n,r=nt(n),o=rt(r);if(!Number.isFinite(e)||!Number.isInteger(e)||e<0||e>=3)throw r.reporter.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),G(r.reporter),new Error(`Number of retries must be an integer between 0 and ${2}`);let s={...t,idempotencyKey:(0,h.resolveIdempotencyKey)(t.idempotencyKey)},i=O(t.timeoutMs),a;for(let l=0;l<=e;l++){r.attempt=l;try{let c=await et(s,i.signal,o);return ot(r,c),i.clear(),G(r.reporter),c}catch(c){a=c;let u=c instanceof Error&&c.name==="AbortError",y=Ht(c),p=c instanceof h.FloPayError&&c.code===h.IDEMPOTENCY_IN_PROGRESS_CODE;if((u||y||p)&&!i.signal.aborted&&l<e){r.reporter.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:l+1});try{await B(l,i.signal)}catch(m){throw ye(r,m),i.clear(),G(r.reporter),m}continue}throw ye(r,c),i.clear(),G(r.reporter),c}}throw ye(r,a),i.clear(),G(r.reporter),a??new Error("Unknown error during checkout session creation")}var it=require("@flopay/shared");0&&(module.exports={FloPay,FloPayElements,PaymentAPI,PciVaultCardCapture,SESSION_CREATE_TELEMETRY,StripeAdapter,cacheSessionDisplayData,clearSessionDisplayData,createCheckoutSession,createCheckoutSessionWithRetries,dropThirdPartyOnlyError,getSessionDisplayData,loadFloPay,toStripeAppearance,toStripeAppearanceTheme});
|
package/dist/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as _flopay_shared from '@flopay/shared';
|
|
2
|
-
import { PaymentProviderAdapter, ElementOptions, ElementType, MountedElement, FloPayError, FloPayConfig, CaptureMethod, CardCaptureAdapter, PayPalPaymentResult, ConfirmPaymentParams, PaymentResult, CheckoutSession, NormalizedCheckoutSession, FloPayThemeVariables, FloPayAppearance, CheckoutGateways, VaultCaptureBlock, ProcessPaymentParams, CreateSessionIntentRequest, SessionIntent, SessionIntentDeclineRequest, InlineSessionDraft, DetachedCheckoutSession, CardCaptureProviderId, CardCaptureMountOptions, CardCaptureEventType, CardCaptureOutcomeEvent, VaultCardThemeColors, VaultCardFieldKey, CreateSessionParams, CheckoutSessionResult } from '@flopay/shared';
|
|
2
|
+
import { PaymentProviderAdapter, ElementOptions, ElementType, MountedElement, FloPayError, FloPayConfig, CaptureMethod, CardCaptureAdapter, PayPalPaymentResult, ConfirmPaymentParams, PaymentResult, CheckoutSession, NormalizedCheckoutSession, FloPayThemeVariables, FloPayAppearance, CheckoutSessionMode, CheckoutGateways, VaultCaptureBlock, ProcessPaymentParams, CreateSessionIntentRequest, SessionIntent, SessionIntentDeclineRequest, InlineSessionDraft, DetachedCheckoutSession, CardCaptureProviderId, CardCaptureMountOptions, CardCaptureEventType, CardCaptureOutcomeEvent, VaultCardThemeColors, VaultCardFieldKey, CreateSessionParams, CheckoutSessionResult } from '@flopay/shared';
|
|
3
3
|
export { SentryEventLike, SentryStackFrameLike, dropThirdPartyOnlyError } from '@flopay/shared';
|
|
4
4
|
|
|
5
5
|
/**
|
|
@@ -301,7 +301,7 @@ interface RawCheckoutSession {
|
|
|
301
301
|
discountAmount?: number;
|
|
302
302
|
/** Final charge amount after coupon discount (cart-currency major units). */
|
|
303
303
|
totalAmount?: number;
|
|
304
|
-
checkoutMode?:
|
|
304
|
+
checkoutMode?: CheckoutSessionMode;
|
|
305
305
|
captureMethod?: 'automatic' | 'manual';
|
|
306
306
|
paymentId?: string;
|
|
307
307
|
authorizationExpiresAt?: string;
|
|
@@ -651,12 +651,16 @@ declare class PaymentAPI {
|
|
|
651
651
|
private mergeCachedDisplayData;
|
|
652
652
|
}
|
|
653
653
|
|
|
654
|
+
/** Browser operation hosted by the PCIVault card-capture adapter. */
|
|
655
|
+
type CardCaptureOperation = 'checkout' | 'card_setup';
|
|
654
656
|
/** Configuration for a {@link PciVaultCardCapture} instance. */
|
|
655
657
|
interface PciVaultCardCaptureConfig {
|
|
656
658
|
/** Checkout session id bound to the capture (for outcome correlation + trust). */
|
|
657
659
|
sessionId?: string;
|
|
658
660
|
/** Capture behavior of the checkout session, used to classify legacy outcomes safely. */
|
|
659
661
|
captureMethod?: CaptureMethod;
|
|
662
|
+
/** Distinguishes no-charge card verification telemetry from checkout payment telemetry. */
|
|
663
|
+
operation?: CardCaptureOperation;
|
|
660
664
|
/**
|
|
661
665
|
* Default strict origin for vault `postMessage` outcomes. Overridden by
|
|
662
666
|
* {@link CardCaptureMountOptions.expectedOrigin} when that is supplied at
|
|
@@ -680,6 +684,8 @@ declare class PciVaultCardCapture implements CardCaptureAdapter {
|
|
|
680
684
|
readonly provider: CardCaptureProviderId;
|
|
681
685
|
private readonly config;
|
|
682
686
|
private telemetryReporter?;
|
|
687
|
+
/** Reporter already initialized for this adapter's setup operation. */
|
|
688
|
+
private setupTelemetryReporter?;
|
|
683
689
|
private readonly ownsTelemetryReporter;
|
|
684
690
|
private container;
|
|
685
691
|
private messageHandler;
|
|
@@ -810,4 +816,4 @@ declare function createCheckoutSessionWithRetries(options: CreateSessionParams &
|
|
|
810
816
|
maxRetries?: number;
|
|
811
817
|
}): Promise<CheckoutSessionResult>;
|
|
812
818
|
|
|
813
|
-
export { FloPay, FloPayElements, PaymentAPI, PciVaultCardCapture, type PciVaultCardCaptureConfig, SESSION_CREATE_TELEMETRY, type SessionDisplayCacheData, type SessionDisplayProduct, StripeAdapter, type StripeSafeAppearance, cacheSessionDisplayData, clearSessionDisplayData, createCheckoutSession, createCheckoutSessionWithRetries, getSessionDisplayData, loadFloPay, toStripeAppearance, toStripeAppearanceTheme };
|
|
819
|
+
export { type CardCaptureOperation, FloPay, FloPayElements, PaymentAPI, PciVaultCardCapture, type PciVaultCardCaptureConfig, SESSION_CREATE_TELEMETRY, type SessionDisplayCacheData, type SessionDisplayProduct, StripeAdapter, type StripeSafeAppearance, cacheSessionDisplayData, clearSessionDisplayData, createCheckoutSession, createCheckoutSessionWithRetries, getSessionDisplayData, loadFloPay, toStripeAppearance, toStripeAppearanceTheme };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as _flopay_shared from '@flopay/shared';
|
|
2
|
-
import { PaymentProviderAdapter, ElementOptions, ElementType, MountedElement, FloPayError, FloPayConfig, CaptureMethod, CardCaptureAdapter, PayPalPaymentResult, ConfirmPaymentParams, PaymentResult, CheckoutSession, NormalizedCheckoutSession, FloPayThemeVariables, FloPayAppearance, CheckoutGateways, VaultCaptureBlock, ProcessPaymentParams, CreateSessionIntentRequest, SessionIntent, SessionIntentDeclineRequest, InlineSessionDraft, DetachedCheckoutSession, CardCaptureProviderId, CardCaptureMountOptions, CardCaptureEventType, CardCaptureOutcomeEvent, VaultCardThemeColors, VaultCardFieldKey, CreateSessionParams, CheckoutSessionResult } from '@flopay/shared';
|
|
2
|
+
import { PaymentProviderAdapter, ElementOptions, ElementType, MountedElement, FloPayError, FloPayConfig, CaptureMethod, CardCaptureAdapter, PayPalPaymentResult, ConfirmPaymentParams, PaymentResult, CheckoutSession, NormalizedCheckoutSession, FloPayThemeVariables, FloPayAppearance, CheckoutSessionMode, CheckoutGateways, VaultCaptureBlock, ProcessPaymentParams, CreateSessionIntentRequest, SessionIntent, SessionIntentDeclineRequest, InlineSessionDraft, DetachedCheckoutSession, CardCaptureProviderId, CardCaptureMountOptions, CardCaptureEventType, CardCaptureOutcomeEvent, VaultCardThemeColors, VaultCardFieldKey, CreateSessionParams, CheckoutSessionResult } from '@flopay/shared';
|
|
3
3
|
export { SentryEventLike, SentryStackFrameLike, dropThirdPartyOnlyError } from '@flopay/shared';
|
|
4
4
|
|
|
5
5
|
/**
|
|
@@ -301,7 +301,7 @@ interface RawCheckoutSession {
|
|
|
301
301
|
discountAmount?: number;
|
|
302
302
|
/** Final charge amount after coupon discount (cart-currency major units). */
|
|
303
303
|
totalAmount?: number;
|
|
304
|
-
checkoutMode?:
|
|
304
|
+
checkoutMode?: CheckoutSessionMode;
|
|
305
305
|
captureMethod?: 'automatic' | 'manual';
|
|
306
306
|
paymentId?: string;
|
|
307
307
|
authorizationExpiresAt?: string;
|
|
@@ -651,12 +651,16 @@ declare class PaymentAPI {
|
|
|
651
651
|
private mergeCachedDisplayData;
|
|
652
652
|
}
|
|
653
653
|
|
|
654
|
+
/** Browser operation hosted by the PCIVault card-capture adapter. */
|
|
655
|
+
type CardCaptureOperation = 'checkout' | 'card_setup';
|
|
654
656
|
/** Configuration for a {@link PciVaultCardCapture} instance. */
|
|
655
657
|
interface PciVaultCardCaptureConfig {
|
|
656
658
|
/** Checkout session id bound to the capture (for outcome correlation + trust). */
|
|
657
659
|
sessionId?: string;
|
|
658
660
|
/** Capture behavior of the checkout session, used to classify legacy outcomes safely. */
|
|
659
661
|
captureMethod?: CaptureMethod;
|
|
662
|
+
/** Distinguishes no-charge card verification telemetry from checkout payment telemetry. */
|
|
663
|
+
operation?: CardCaptureOperation;
|
|
660
664
|
/**
|
|
661
665
|
* Default strict origin for vault `postMessage` outcomes. Overridden by
|
|
662
666
|
* {@link CardCaptureMountOptions.expectedOrigin} when that is supplied at
|
|
@@ -680,6 +684,8 @@ declare class PciVaultCardCapture implements CardCaptureAdapter {
|
|
|
680
684
|
readonly provider: CardCaptureProviderId;
|
|
681
685
|
private readonly config;
|
|
682
686
|
private telemetryReporter?;
|
|
687
|
+
/** Reporter already initialized for this adapter's setup operation. */
|
|
688
|
+
private setupTelemetryReporter?;
|
|
683
689
|
private readonly ownsTelemetryReporter;
|
|
684
690
|
private container;
|
|
685
691
|
private messageHandler;
|
|
@@ -810,4 +816,4 @@ declare function createCheckoutSessionWithRetries(options: CreateSessionParams &
|
|
|
810
816
|
maxRetries?: number;
|
|
811
817
|
}): Promise<CheckoutSessionResult>;
|
|
812
818
|
|
|
813
|
-
export { FloPay, FloPayElements, PaymentAPI, PciVaultCardCapture, type PciVaultCardCaptureConfig, SESSION_CREATE_TELEMETRY, type SessionDisplayCacheData, type SessionDisplayProduct, StripeAdapter, type StripeSafeAppearance, cacheSessionDisplayData, clearSessionDisplayData, createCheckoutSession, createCheckoutSessionWithRetries, getSessionDisplayData, loadFloPay, toStripeAppearance, toStripeAppearanceTheme };
|
|
819
|
+
export { type CardCaptureOperation, FloPay, FloPayElements, PaymentAPI, PciVaultCardCapture, type PciVaultCardCaptureConfig, SESSION_CREATE_TELEMETRY, type SessionDisplayCacheData, type SessionDisplayProduct, StripeAdapter, type StripeSafeAppearance, cacheSessionDisplayData, clearSessionDisplayData, createCheckoutSession, createCheckoutSessionWithRetries, getSessionDisplayData, loadFloPay, toStripeAppearance, toStripeAppearanceTheme };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{FloPayError as pr,resolveBillingApiUrl as ke,SDK_VERSION as ct}from"@flopay/shared";import{loadStripe as Xt}from"@stripe/stripe-js";import{FloPayError as g,isMoneySettledOutcome as Zt,isSetupIntentClientSecret as er}from"@flopay/shared";import{FloPayError as h,SDK_VERSION as N,FLO_SDK_VERSION_HEADER as ve,IDEMPOTENCY_KEY_HEADER as Oe,IDEMPOTENCY_IN_PROGRESS_CODE as Ot,assertCaptureMethodEligible as qe,buildProductPayload as Be,classifyPaymentRejection as qt,classifyTelemetryFailure as G,foldIntoProducts as Te,isDetachedSessionEligible as Ut,isUuidV4 as Ue,normalizeCheckoutFailureOutcome as Le,randomUuidV4 as Lt,resolveIdempotencyKey as Nt,resolveSessionCurrency as _e,telemetryStatusClass as A}from"@flopay/shared";function E(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}var Tt="flopay_session_display:";var oe=new Map;function se(n){return`${Tt}${n}`}function ye(){if(typeof window>"u")return null;try{return window.sessionStorage}catch{return null}}function q(n,e,t){if(!n)return;let r=t?.ttlMs??36e5,s={data:e,expiresAt:Date.now()+r},o=ye();if(o)try{o.setItem(se(n),JSON.stringify(s));return}catch{}oe.set(n,s)}function he(n){if(!n)return null;let e=ye();if(e)try{let r=e.getItem(se(n));if(r){let s=JSON.parse(r);if(s&&typeof s.expiresAt=="number"&&s.expiresAt>Date.now())return s.data;e.removeItem(se(n))}}catch{}let t=oe.get(n);if(t){if(t.expiresAt>Date.now())return t.data;oe.delete(n)}return null}function ge(n){if(!n)return;oe.delete(n);let e=ye();if(e)try{e.removeItem(se(n))}catch{}}import{buildTelemetryErrorEvent as Ie,buildTelemetryLogEvent as _t,buildTelemetryPerformanceEvent as wt,buildTelemetryTerminalEvent as St,serializeTelemetryBatch as bt,TELEMETRY_MAX_BATCH_BYTES as Mt}from"@flopay/shared";var kt="/v1/sdk-telemetry/events",fe=16,Pt=64,Et=1500,De=1e3,Rt=64,At="00000000-0000-4000-8000-000000000000",It={technical_error:8,lifecycle:32,expected_outcome:32,performance:24};function U(){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]&15|64,n[8]=n[8]&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 Dt(n){try{return new TextEncoder().encode(n).byteLength}catch{return n.length}}function xt(n){return JSON.stringify([n.code,n.failureCategory,n.stage,n.provider,n.attempt,n.statusClass,n.requestCategory,n.paymentMethodCategory,n.checkoutMode,n.layout])}function _(){return globalThis.performance?.now()??0}var C=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.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(/\/+$/,"")}${kt}`,this.sdkPackage=e.sdkPackage??"@flopay/js",this.sdkVersion=e.sdkVersion,this.correlationId=U(),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.canCollect()&&this.enqueue(_t({...this.checkoutContext,...e,eventId:U(),sequence:this.sequence++}))}error(e){if(!this.canCollect())return;let t=Ie({...this.checkoutContext,...e,eventId:At,sequence:0}),r=xt(t),s=this.now();this.pruneReportedFailures(s);let o=this.reportedFailures.get(r);if(o!==void 0&&s>=o&&s-o<De){this.log({name:"operation.deduplicated",stage:e.stage,provider:e.provider,paymentMethodCategory:e.paymentMethodCategory,attempt:e.attempt});return}this.rememberReportedFailure(r,s),this.enqueue(Ie({...this.checkoutContext,...e,eventId:U(),sequence:this.sequence++}))}performance(e){this.canCollect()&&this.enqueue(wt({...this.checkoutContext,...e,eventId:U(),sequence:this.sequence++}))}terminal(e){if(this.canCollect()&&(this.enqueue(St({...this.checkoutContext,...e,eventId:U(),sequence:this.sequence++})),e.outcome!=="action_required"&&this.checkoutStartedAt!==null)){let t=this.checkoutStartedAt;this.checkoutStartedAt=null,this.performance({stage:"total_journey",durationMs:Math.max(0,this.now()-t),durationMode:"total",provider:e.provider,paymentMethodCategory:e.paymentMethodCategory})}}now(){try{return this.clock()}catch{return _()}}pruneReportedFailures(e){for(let[t,r]of this.reportedFailures)(e<r||e-r>=De)&&this.reportedFailures.delete(t)}rememberReportedFailure(e,t){for(;this.reportedFailures.size>=Rt;){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>=Pt||this.eventCounts[e.class]>=It[e.class])){if(this.eventCounts[e.class]+=1,this.queue.push(e),this.queue.length>=fe){this.flush();return}this.scheduleFlush()}}canCollect(){return this.browserTransportAvailable&&this.merchantEnabled&&!this.ingestionDisabled&&!this.destroyed}async flush(){if(this.flushInFlight)return this.flushInFlight;if(!this.browserTransportAvailable||this.destroyed||this.ingestionDisabled||this.queue.length===0)return;this.clearFlushTimer();let e=this.queue.splice(0,fe);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())}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,fe);this.sendBatch(e)}}async sendBatch(e){if(!this.browserTransportAvailable||this.ingestionDisabled)return;let t=bt(e,{correlationId:this.correlationId,sdkPackage:this.sdkPackage,sdkVersion:this.sdkVersion,batchId:U()});if(Dt(t)>Mt)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 a=>a.status!==202?null:(await a.json().catch(()=>null))?.status==="disabled"?"disabled":null).catch(()=>null),i=new Promise(a=>{s=setTimeout(()=>{r?.abort(),a(null)},Et)});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)}},xe=Symbol.for("@flopay/js.telemetry.reporter-factory.v1"),Fe=globalThis;Fe[xe]===void 0&&Object.defineProperty(Fe,xe,{configurable:!0,enumerable:!1,writable:!1,value:n=>new C(n)});function R(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 Ft(){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,l=()=>e.removeEventListener("abort",a),a=()=>{i!==void 0&&clearTimeout(i),l(),o(Ft())};if(e.aborted){a();return}i=setTimeout(()=>{l(),s()},r),e.addEventListener("abort",a,{once:!0})})}var Ne=1e3,Vt=500,zt=15e3,Bt=3e3,jt=1e4,Kt=1e4;function Ht(n){return typeof n=="object"&&n!==null}function V(n,e){return E(n?.[e])}function Ve(n,e){return Ae(n?.[e])}function $t(n,e){let t=n?.[e];return typeof t=="number"&&Number.isFinite(t)?t:void 0}function je(n){return new Promise(e=>setTimeout(e,n))}function ie(){return new h("Checkout is still processing. Please try again shortly.","api_error",{code:"checkout_processing_timeout"})}async function I(n,e){let t=await n.json().catch(()=>null),r=Ht(t?.error)?t.error:null,s=Ve(t,"message")??Ve(r,"message")??e,o=V(t,"code")??V(t,"gatewayErrorCode")??V(r,"code")??`http_${n.status}`;return new h(s,"api_error",{code:o,statusCode:n.status})}async function Gt(n){let e=n.status===400?await n.clone().json().catch(()=>null):null;return qt(n.status,e)}function ze(n){return n===400||n===422}var ae=2;async function we(n,e,t=ae,r){let s;for(let o=0;;o++)try{return await fetch(n,e)}catch(i){if(e?.signal?.aborted||i instanceof Error&&i.name==="AbortError")throw i;if(s=i,o>=t)throw s;try{r?.(o+1)}catch{}await je(150*2**o)}}var Ke=Symbol.for("@flopay/js.session-create.telemetry.v1");function Yt(n){return n[Ke]}function Wt(n){return"now"in n||"onFirstByte"in n||"onSessionCreateFailure"in n||"onRetry"in n}function He(n){return{userId:n.userId,firstName:n.firstName??null,lastName: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 $e(n,e){e.tagsData&&(n.tagsData=e.tagsData),e.utmMetadata?.length&&(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 Jt(n,e){let t={clientId:n.clientId,checkoutVersion:N,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}),$e(t,n),t}function Qt(n,e,t){return{currency:e,products:t.map(r=>Be(r,e)),couponCodes:n.couponCodes??[],accountData:He(n.account)}}var D=class D{constructor(e,t={}){this.baseUrl=e.replace(/\/+$/,"");let r=Wt(t);this.telemetryHooks=r?t:void 0,this.directTelemetry=r||t.telemetry===!1?void 0:new C({billingApiUrl:this.baseUrl,sdkVersion:N})}destroy(){this.directTelemetry?.destroy()}reportDirectFailure(e,t,r,s,o="unknown"){let i=G(e,t);this.directTelemetry?.error({...i,stage:r,requestCategory:s,paymentMethodCategory:o})}reportAccountSnapshotFailure(e,t){let r=G(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){this.beginDirectTelemetryCheckout(e);let r=this.telemetryTimestamp();this.directTelemetry?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let s={[ve]:N};t&&(s["x-checkout-session-token"]=t);try{let o=await we(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}`,{headers:s},ae,c=>{this.telemetryHooks?.onRetry?.("session_read",c),this.directTelemetry?.log({name:"operation.retry",stage:"session_read",requestCategory:"session_read",attempt:c})}),i=Math.max(0,this.telemetryTimestamp()-r);try{this.telemetryHooks?.onFirstByte?.(i)}catch{}let l=`${Math.floor(o.status/100)}xx`;if(this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:l}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:i,durationMode:"machine",requestCategory:"session_read",statusClass:l}),!o.ok)throw await I(o,"Failed to get checkout session");let a=await o.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()-r),durationMode:"machine",requestCategory:"session_read",statusClass:l}),{...a,data:this.mergeCachedDisplayData(a.data)}}catch(o){throw this.directTelemetry?.error({...G(o,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"}),o}}cacheSessionDisplayData(e,t,r){q(e,t,r)}clearSessionDisplayData(e){ge(e)}async getVaultCapture(e,t){let r=`${this.baseUrl}\0${e}\0${t??""}`,s=D.activeVaultCaptureRequests.get(r);if(s)return s;let o=this.requestVaultCapture(e,t);D.activeVaultCaptureRequests.set(r,o);try{return await o}finally{D.activeVaultCaptureRequests.get(r)===o&&D.activeVaultCaptureRequests.delete(r)}}async requestVaultCapture(e,t){let r=new AbortController,s=setTimeout(()=>r.abort(),Kt);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 l=await we(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/vault/capture`,{method:"POST",headers:i,signal:r.signal},ae,c=>{this.telemetryHooks?.onRetry?.("vault_capture",c),this.directTelemetry?.log({name:"operation.retry",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card",attempt:c})});if(!l.ok)throw await I(l,"Failed to load the secure card form");let a=await l.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(a)}catch(l){let a=r.signal.aborted?new h("Timed out while loading the secure card form. Please try again.","api_error",{code:"vault_capture_timeout"}):l;throw this.reportDirectFailure(a,"VAULT_LOAD_FAILED","vault_request","vault_capture","card"),a}finally{clearTimeout(s)}}async getUnifiedCheckoutSession(e,t){let r=await this.getCheckoutSession(e,t),s=this.normalizeRawSession(r.data),o=r.vault;return o&&s.data.session&&(s.data.session.vault=this.toVaultBlock(o)),s}async processPayment(e,t,r){if(this.beginDirectTelemetryCheckout(t.sessionId),!t.nonce)throw this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"process_payment"}),new h("processPayment requires `nonce` \u2014 pass the value returned from session creation.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let s=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.processing.started",stage:"processing",requestCategory:"process_payment"});let{nonce:o,...i}=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":o},body:JSON.stringify(i)})}catch(a){throw this.reportDirectFailure(a,"PAYMENT_PROCESSING_FAILED","processing","process_payment"),a}if(!l.ok&&l.status!==202){let a=await Gt(l);return a?this.directTelemetry?.terminal({outcome:a,stage:"processing",requestCategory:"process_payment",statusClass:"4xx"}):this.directTelemetry?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",requestCategory:"process_payment",statusClass:A(l.status),failureCategory:l.status>=500?"server_error":void 0}),l}try{let a=await this.resolveProcessResponse(l,t.sessionId,{...r,nonce:o});return this.directTelemetry?.log({name:"payment.processing.completed",stage:"processing",requestCategory:"process_payment",statusClass:A(a.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"process_payment",statusClass:A(a.status)}),a}catch(a){throw a instanceof h&&a.code==="checkout_processing_timeout"||this.reportDirectFailure(a,"PAYMENT_PROCESSING_FAILED","processing","process_payment"),a}}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??jt,l=new AbortController,a=()=>l.abort();s?.signal&&(s.signal.aborted?l.abort():s.signal.addEventListener("abort",a,{once:!0}));let c=setTimeout(()=>l.abort(),i);try{let d;try{d=await we(`${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:l.signal},ae,m=>{this.telemetryHooks?.onRetry?.("account_snapshot",m),this.directTelemetry?.log({name:"operation.retry",stage:"processing",requestCategory:"account_snapshot",attempt:m})})}finally{clearTimeout(c),s?.signal?.removeEventListener("abort",a)}if(!d.ok)throw await I(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 h("createSessionIntent requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let o=r,i=o.paymentMethodType,l=typeof i=="string"&&i.trim().toLowerCase()==="card",a=typeof i=="string"&&i.length>0&&!l&&(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.paymentMethodType==="paypal"&&o.paymentMethodId===null&&o.intentKind==="payment";if(!a||!c&&!d)throw new h("Only wallet, APM, and PayPal session intents are supported.","validation_error",{code:"InvalidSessionIntentRequest"});let m=o.authorizationAttemptId;if(m!==void 0&&!Ue(m))throw new h("authorizationAttemptId must be a v4 UUID identifying one buyer authorization attempt.","validation_error",{code:"InvalidAuthorizationAttemptId",param:"authorizationAttemptId"});let u=Ue(m)?m:Lt();this.beginDirectTelemetryCheckout(e);let p=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.intent.started",stage:"processing",requestCategory:"intent_create"});let w={"Content-Type":"application/json","x-checkout-session-token":t,[Oe]:s?.idempotencyKey||u},v=!1;try{let T=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents`,{method:"POST",headers:w,body:JSON.stringify({...r,authorizationAttemptId:u}),signal:s?.signal});if(!T.ok){v=!0;let $=await I(T,"Failed to create checkout intent"),Z=G($,"PAYMENT_PROCESSING_FAILED");throw ze($.statusCode)?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"intent_create",statusClass:"4xx"}):this.directTelemetry?.error({...Z,stage:"processing",requestCategory:"intent_create"}),$}let H=(await T.json()).data;if(!H||typeof H!="object")throw new h("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});let y=H,Q=y.paymentMethodType,X=(y.paymentMethodCategory==="wallet"||y.paymentMethodCategory==="apm")&&typeof Q=="string"&&Q.trim().toLowerCase()!=="card"&&(typeof y.paymentMethodId=="string"||y.paymentMethodId===null)&&typeof y.providerObjectId=="string",P=y.provider==="stripe"&&(y.intentKind==="payment"||y.intentKind==="setup")&&typeof y.clientSecret=="string",M=y.provider==="paypal"&&y.paymentMethodCategory==="wallet"&&y.paymentMethodType==="paypal"&&y.paymentMethodId===null&&y.intentKind==="payment"&&(y.providerObjectType==="order"||y.providerObjectType==="subscription")&&y.clientSecret===null,F=y.provider===r.provider&&y.paymentMethodCategory===r.paymentMethodCategory&&y.paymentMethodType===r.paymentMethodType&&y.paymentMethodId===r.paymentMethodId&&y.intentKind===r.intentKind;if(!X||!P&&!M||!F)throw new h("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});return this.directTelemetry?.log({name:"payment.intent.completed",stage:"processing",requestCategory:"intent_create",statusClass:A(T.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-p),durationMode:"machine",requestCategory:"intent_create",statusClass:A(T.status)}),y}catch(T){throw v||this.reportDirectFailure(T,"PAYMENT_PROCESSING_FAILED","processing","intent_create"),T}}async reportSessionIntentDecline(e,t,r,s){if(!t)throw new h("reportSessionIntentDecline requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let o=r,i=o.providerDeclineReason,l=o.paymentMethodType,a=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),c=typeof l=="string"&&l.length>0&&l.trim().toLowerCase()!=="card"&&a,d=o.provider==="stripe"&&(o.paymentMethodCategory==="wallet"||o.paymentMethodCategory==="apm"),m=o.provider==="paypal"&&o.paymentMethodCategory==="wallet"&&o.paymentMethodType==="paypal";if(!c||!d&&!m)throw new h("Invalid non-card decline classification.","validation_error",{code:"InvalidSessionIntentDeclineRequest"});let u=m?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:i}:{provider:"stripe",paymentMethodCategory:o.paymentMethodCategory,paymentMethodType:o.paymentMethodType,providerDeclineReason:i},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(u),signal:s?.signal});if(!p.ok)throw await I(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 l=await fetch(`${this.baseUrl}/v1/payments?${i.toString()}`,{method:"GET",signal:t?.signal,keepalive:!0});if(!l.ok)throw new h("Failed to fetch payments","api_error",{statusCode:l.status});let a=await l.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"}),a}catch(l){throw this.reportDirectFailure(l,"RECOVERY_FAILED","recovery","other","saved"),l}}async createAndFetchSession(e){if(Ut(e))return(await this.createDetachedSession(e)).claimed;this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp(),r=R(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,t,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,s){let o=e.products??Te(e.items,e.subscriptions);qe({captureMethod:e.captureMethod,products:o});let i=_e(e.currency,e.items,e.subscriptions,o);if(!i)throw new h("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 l={clientId:e.clientId,checkoutVersion:N,successUrl:e.successUrl,cancelUrl:e.cancelUrl,currency:i,checkoutMode:e.checkoutMode??"full",products:o.map(u=>Be(u,i)),accountData:He(e.account),couponCodes:e.couponCodes??[]};e.captureMethod==="manual"&&(l.captureMethod=e.captureMethod),e.tokenizedData&&(l.tokenizedData=e.tokenizedData),$e(l,e);let c=await(await this.postCheckoutSessionCreate(l,e,t,r,s)).json();if(c.data&&"gateways"in c.data){this.autoCacheDisplayData(c.data.uuid,e);let u=this.mergeCachedDisplayData(c.data),p=this.normalizeRawSession(u);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 d=c.data?.uuid;if(!d)throw new h("No session ID returned","api_error",{code:"InvalidCheckoutSessionResponse"});return this.autoCacheDisplayData(d,e),this.adoptDirectTelemetryCheckout(d),{...await this.getUnifiedCheckoutSession(d),autoProcessingError:c.autoProcessingError,autoProcessingAttempted:c.autoProcessingAttempted,autoProcessingPending:c.autoProcessingPending}}async postCheckoutSessionCreate(e,t,r,s,o){let i={"Content-Type":"application/json",[ve]:N},l=Nt(t.idempotencyKey);l&&(i[Oe]=l);let a,c=!1,d=Yt(t),m=u=>{try{this.telemetryHooks?.onRetry?.("session_create",u),this.directTelemetry?.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:u})}catch{}};for(let u=0;u<3;u++){o.attempt=u;try{d?.onAttempt?.(u)}catch{}try{a=await fetch(`${this.baseUrl}/v1/checkouts/sessions?expand=true`,{method:"POST",headers:i,body:JSON.stringify(e),signal:s})}catch(v){if(o.statusClass=s.aborted||v instanceof Error&&v.name==="AbortError"?"timeout":"network_error",s.aborted||v instanceof Error&&v.name==="AbortError"||u>=2)throw v;let T=u+1;m(T),await L(u,s);continue}let p=A(a.status);if(o.statusClass=p,c||(c=!0,this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:p,attempt:u}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:Math.max(0,this.telemetryTimestamp()-r),durationMode:"machine",requestCategory:"session_create",statusClass:p,attempt:u})),a.status===204)throw new h("Session auto-completed \u2014 payment method already on file","api_error",{code:"session_auto_completed"});if(a.ok)break;let w=await I(a,"Failed to create checkout session");if(w.code===Ot&&u<2){m(u+1),await L(u,s);continue}throw w}if(!a)throw new TypeError("Checkout-session creation exhausted its retry budget.");return a}async createDetachedSession(e){this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp(),r=R(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??Te(e.items,e.subscriptions);try{qe({captureMethod:e.captureMethod,products:o})}catch(p){throw r.clear(),this.reportSessionCreateFailure(p,t,s),p}let i=_e(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 h("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 l;try{l=Qt(e,i,o)}catch(p){throw r.clear(),this.reportSessionCreateFailure(p,t,s),p}let a,c;try{if(c=await(await this.postCheckoutSessionCreate(Jt(e,i),e,t,r.signal,s)).json(),!c.data||!("gateways"in c.data))throw new h("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(p){throw r.clear(),this.reportSessionCreateFailure(p,t,s),p}let d=a.data.session?.id??c.data.uuid??"",m=a.data.session?.clientSecret??c.data.nonce??"";if(!d||!m){r.clear();let p=new h("Checkout session shell was created without a session id or nonce.","api_error",{code:"InvalidCheckoutSessionResponse"});throw this.reportSessionCreateFailure(p,t,s),p}this.adoptDirectTelemetryCheckout(d),this.directTelemetry?.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",statusClass:s.statusClass,paymentMethodCategory:"card"}),this.directTelemetry?.performance({stage:"session_shell",durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:"session_create",statusClass:s.statusClass,attempt:s.attempt,paymentMethodCategory:"card"});let u=this.claimCheckoutSession(d,m,l,{params:e,startedAt:t,deadline:r,createAttempt:s.attempt});return u.catch(()=>{}),{shell:a,sessionId:d,nonce:m,claimed:u}}async claimCheckoutSession(e,t,r,s){let o=s?.startedAt??this.telemetryTimestamp(),i=this.telemetryTimestamp(),l=s?.deadline??R(12e3),a=JSON.stringify(r),c="unknown",d=0;this.directTelemetry?.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"});try{let m;for(d=0;d<3;d++){try{m=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/claim`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":t,[ve]:N},body:a,signal:l.signal})}catch(w){let v=l.signal.aborted||w instanceof Error&&w.name==="AbortError";if(c=v?"timeout":"network_error",v||d>=2)throw w;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,l.signal);continue}if(c=A(m.status),m.ok)break;throw await I(m,"Failed to attach checkout session data")}if(!m)throw new TypeError("Checkout-session claim exhausted its retry budget.");let u=await m.json();if(!u.data||!u.data.gateways)throw new h("The billing API returned no checkout session with gateways after claiming it.","api_error",{code:"InvalidCheckoutSessionResponse"});s?.params&&this.autoCacheDisplayData(u.data.uuid??e,s.params);let p=this.normalizeRawSession(this.mergeCachedDisplayData(u.data));return u.vault&&p.data.session&&(p.data.session.vault=this.toVaultBlock(u.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}),p}catch(m){throw this.reportSessionCreateFailure(m,o,{attempt:d,statusClass:c},"session_claim"),m}finally{l.clear()}}reportSessionCreateFailure(e,t,r,s="session_create"){if(!(e instanceof h&&e.code==="session_auto_completed"))try{this.telemetryHooks?.onSessionCreateFailure?.(e)}catch{}let o=G(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 h&&e.type==="validation_error"||e instanceof h&&ze(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 h&&e.code==="session_auto_completed"||this.directTelemetry?.error({...o,stage:s,requestCategory:s==="session_claim"?"session_claim":"session_create"})}async waitForCheckoutSessionCompletion(e,t){this.beginDirectTelemetryCheckout(e);let r=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:"saved"});let s=t?.timeoutMs??zt,o=Date.now()+s,i=this.clampRetryAfterMs(t?.initialDelayMs??Ne),l=0;try{for(;;){let a=o-Date.now();if(a<=0)throw ie();if(i>0){try{l+=1,this.telemetryHooks?.onRetry?.("session_read",l),this.directTelemetry?.log({name:"operation.retry",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:"saved",attempt:l})}catch{}if(await je(Math.min(i,a)),Date.now()>=o)throw ie()}let c=await this.getUnifiedCheckoutSession(e,t?.nonce),d=c.data.session?.status;if(d==="authorized"||d==="complete"||d==="expired")return this.directTelemetry?.log({name:"operation.recovery.completed",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:"saved"}),this.directTelemetry?.performance({stage:"recovery",durationMs:Math.max(0,this.telemetryTimestamp()-r),durationMode:"machine",requestCategory:"session_read",paymentMethodCategory:"saved"}),c;if(Date.now()>=o)throw ie();i=this.clampRetryAfterMs(Math.max(i*2,Vt))}}catch(a){throw a instanceof h&&a.code==="checkout_processing_timeout"&&this.reportDirectFailure(a,"RECOVERY_FAILED","recovery","session_read","saved"),a}}normalizeRawSession(e){let t=e.gateways??{},r=[],s={session:this.toCheckoutSession(e)},o=t.stripe;if(o?.publishableKey){r.push("stripe");let a=[e.stripeClientSecret,o.stripeClientSecret].find(c=>typeof c=="string"&&c.length>0);s.stripe={clientSecret:a??"",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}),{providers:r,mode:"tokenize",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),l=e.currency??t[0]?.currency??"USD",a=t.some(c=>c.type==="subscription")?"subscription":"payment";return{id:e.uuid,clientSecret:e.nonce,mode:a,status:this.toCheckoutSessionStatus(e.status),amount:i,currency:l,captureMethod:e.captureMethod,paymentId:e.paymentId,authorizationExpiresAt:e.authorizationExpiresAt,failureOutcome:Le(e.outcome)??Le(e.failureReason)??(e.status==="expired"&&e.captureMethod==="manual"?"authorization_expired":void 0),customer:{id:e.accountData.userId,email:e.accountData.email,firstName:e.accountData.firstName,lastName:e.accountData.lastName,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},metadata:{},checkoutMode:e.checkoutMode,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=await this.waitForCheckoutSessionCompletion(o.sessionId,{initialDelayMs:o.retryAfterMs,timeoutMs:r?.pollTimeoutMs,nonce:r?.nonce});if(i.data.session?.status==="complete")return new Response(null,{status:204,statusText:"No Content"});if(i.data.session?.status==="authorized"){let l=i.data.session;return new Response(JSON.stringify({status:"authorized",paymentId:l.paymentId,sessionId:l.id||t,authorizationExpiresAt:l.authorizationExpiresAt}),{status:200,headers:{"Content-Type":"application/json"}})}if(i.data.session?.status==="expired"){let l=i.data.session.failureOutcome==="authorization_expired"||i.data.session.captureMethod==="manual";throw new h(l?"Authorization has expired.":"Checkout session has expired.","api_error",{code:l?"authorization_expired":"checkout_session_expired"})}throw ie()}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:V(e,"sessionId")??r,retryAfterMs:this.clampRetryAfterMs($t(e,"retryAfterMs")??i??Ne),statusUrl:V(e,"statusUrl"),sessionUrl:V(e,"sessionUrl")}}clampRetryAfterMs(e){return Math.max(0,Math.min(e,Bt))}autoCacheDisplayData(e,t){if(!e)return;let r=t.products??Te(t.items,t.subscriptions);if(r.length===0&&!t.currency)return;let s=t.products!==void 0,o=_e(t.currency,s?void 0:t.items,s?void 0:t.subscriptions,r);q(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=he(e.uuid),r=new Map,s=i=>i?`code:${i}`:void 0;for(let i of t?.products??[]){let l=s(i.code);l&&r.set(l,i)}let o=(e.products??[]).map(i=>{let l=s(i.code),a=l?r.get(l):void 0;return{...i,name:i.name??a?.name??null,totalAmount:i.totalAmount??a?.totalAmount,overrideAmount:i.overrideAmount??a?.overrideAmount,currency:i.currency??a?.currency}});return{...e,currency:e.currency??t?.currency,products:o}}};D.activeVaultCaptureRequests=new Map;var x=D;function Ge(n,e){let t=x;return new t(n,e)}function Ye(n){return{payment:"payment",address:"address"}[n]}function le(n){switch(n){case"night":return"night";case"flat":return"flat";default:return"stripe"}}function tr(n){return{...n,theme:le(n.theme)}}function Se(n){return n?JSON.stringify(n.map(e=>e.trim().toLowerCase())):null}function We(n){let e=n;return{mount(t){e.mount(t)},unmount(){e.unmount()},update(t){e.update(t)},on(t,r){e.on?.(t,r)},off(t,r){e.off?.(t,r)},destroy(){e.destroy()}}}function rr(n){return{billing_details:{...n.email?{email:n.email}:{},...n.name?{name:n.name}:{},...n.address?{address:{...n.address.country?{country:n.address.country}:{},...n.address.postal_code?{postal_code:n.address.postal_code}:{},...n.address.city?{city:n.address.city}:{},...n.address.line1?{line1:n.address.line1}:{},...n.address.line2?{line2:n.address.line2}:{},...n.address.state?{state:n.address.state}:{}}}:{}}}}var Y=class{constructor(){this.name="stripe";this.stripe=null;this.elements=null;this.appliedAppearanceKey=null;this.appliedPaymentMethodTypesKey=null;this.appliedClientSecret=null;this.verifiedClientSecret=null;this.verifiedPaymentMethodTypesKey=null}async initialize(e){if(typeof window>"u")return;let t=await Xt(e.publishableKey,{locale:e.locale??"auto"});if(!t)throw new g("Failed to initialize Stripe. Check your publishable key.","authentication_error");this.stripe=t}getElements(e){if(!this.stripe)throw new g("StripeAdapter not initialized. Call initialize() first.","api_error");let t=e?.appearance?{theme:le(e.appearance.theme),variables:e.appearance.variables,rules:e.appearance.rules}:void 0,r=t?JSON.stringify(t):null,s=Se(e?.paymentMethodTypes),o=e?.clientSecret??null;if(this.elements&&s&&(s!==this.appliedPaymentMethodTypesKey||o!==this.appliedClientSecret)&&(this.elements=null,this.appliedAppearanceKey=null,this.appliedPaymentMethodTypesKey=null,this.appliedClientSecret=null,this.verifiedClientSecret=null,this.verifiedPaymentMethodTypesKey=null),this.elements)r!==this.appliedAppearanceKey&&(this.elements.update({appearance:t??{}}),this.appliedAppearanceKey=r);else{let i,l=e?.amount??0,a=(e?.currency??"usd").toLowerCase(),c=e?.paymentMethodCreation??"manual";e?.clientSecret?i={clientSecret:e.clientSecret}:l>0?(i={mode:"payment",amount:l,currency:a,paymentMethodCreation:c},e?.setupFutureUsage&&(i.setupFutureUsage=e.setupFutureUsage)):i={mode:"setup",currency:a,paymentMethodCreation:c},!e?.clientSecret&&e?.paymentMethodTypes&&(i.paymentMethodTypes=e.paymentMethodTypes),t&&(i.appearance=t),this.elements=this.stripe.elements(i),this.appliedAppearanceKey=r,this.appliedPaymentMethodTypesKey=s,this.appliedClientSecret=o,this.verifiedClientSecret=null,this.verifiedPaymentMethodTypesKey=null}return this.elements}async assertClientSecretPaymentMethods(e,t){if(!this.stripe)throw new g("StripeAdapter not initialized. Call initialize() first.","api_error");let r,s=!1;if(er(e)){let{setupIntent:a,error:c}=await this.stripe.retrieveSetupIntent(e);r=a,s=!!c}else{let{paymentIntent:a,error:c}=await this.stripe.retrievePaymentIntent(e);r=a,s=!!c}let o=r?.payment_method_types;if(s||!Array.isArray(o))throw new g("Unable to verify the payment methods configured for this client secret.","api_error",{param:"clientSecret"});let i=new Set(t.map(a=>a.toLowerCase()));if(o.some(a=>typeof a!="string"||!i.has(a.trim().toLowerCase()))||o.length===0)throw new g("The client-secret intent must enable only declared non-card payment methods.","validation_error",{param:"clientSecret"})}async createElement(e,t){let r=t;if(e==="payment"){let a=t.paymentMethodTypes?.map(c=>c.trim()).filter(c=>c&&c.toLowerCase()!=="card");if(!a?.length)throw new g("At least one supported non-card payment method is required.","validation_error",{param:"paymentMethodTypes"});if(r={...t,paymentMethodTypes:a},r.clientSecret){let c=Se(a);this.elements&&this.appliedClientSecret===r.clientSecret&&this.appliedPaymentMethodTypesKey===c&&this.verifiedClientSecret===r.clientSecret&&this.verifiedPaymentMethodTypesKey===c||await this.assertClientSecretPaymentMethods(r.clientSecret,a)}}let s=this.getElements(r);e==="payment"&&r.clientSecret&&(this.verifiedClientSecret=r.clientSecret,this.verifiedPaymentMethodTypesKey=Se(r.paymentMethodTypes));let o=Ye(e),i={};r.layout&&(i.layout=r.layout),r.defaultValues&&(i.defaultValues=r.defaultValues),r.readOnly&&(i.readOnly=r.readOnly),r.mode&&(i.mode=r.mode);let l=s.create(o,i);return We(l)}getElement(e){if(!this.elements)return null;let t=Ye(e),r=this.elements.getElement(t);return r?We(r):null}async submitElements(){if(!this.stripe||!this.elements)return{error:new g("Stripe not initialized","api_error")};let{error:e}=await this.elements.submit();return e?{error:new g(e.message??"Validation failed","validation_error")}:{}}async confirmPayment(e){if(!this.stripe||!this.elements)throw new g("StripeAdapter not initialized or no elements created.","api_error");let t=e.billingDetails,r=t?rr(t):void 0,{error:s,paymentIntent:o}=await this.stripe.confirmPayment({elements:this.elements,clientSecret:e.clientSecret,confirmParams:{return_url:e.returnUrl??window.location.href,...r?{payment_method_data:r}:{}},redirect:"if_required"});return s?{status:"failed",error:new g(s.message??"Payment failed","api_error",{code:s.code,declineCode:s.decline_code})}:o?{status:{succeeded:"succeeded",processing:"processing",requires_action:"requires_action",requires_payment_method:"failed",canceled:"failed"}[o.status]??"failed",paymentIntentId:o.id,paymentMethodId:this.extractPaymentMethodId(o.payment_method)}:{status:"failed",error:new g("No payment intent returned","api_error")}}extractPaymentMethodId(e){if(typeof e=="string"&&e.startsWith("pm_"))return e;if(e&&typeof e=="object"&&typeof e.id=="string")return e.id}async confirmPayPalPayment(e){if(!this.stripe)return{status:"failed",error:new g("Stripe not initialized","api_error")};let t=e.billingApiUrl.replace(/\/+$/,"");if(this.elements){let{error:o}=await this.elements.submit();if(o)return{status:"failed",error:new g(o.message??"PayPal payment failed","validation_error",{code:o.code})}}let r;try{let o=await new x(t).createSessionIntent(e.sessionId,e.nonce??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"});if(o.provider!=="stripe")throw new g("Invalid provider returned for PayPal intent","api_error");r=o.clientSecret}catch(o){return{status:"failed",error:o instanceof g?o:new g("Failed to create PayPal payment intent","api_error")}}let{error:s}=await this.stripe.confirmPayment({clientSecret:r,elements:this.elements??void 0,confirmParams:{return_url:e.returnUrl}});if(s){if(e.nonce)try{await new x(t).reportSessionIntentDecline(e.sessionId,e.nonce,{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:s.code??"provider_declined"})}catch{}return{status:"failed",error:new g(s.message??"PayPal payment failed","api_error",{code:s.code})}}return{status:"processing"}}async resumePayPalPayment(){if(!this.stripe||typeof window>"u")return null;let e=new URLSearchParams(window.location.search),t=e.get("payment_intent"),r=e.get("payment_intent_client_secret"),s=e.get("redirect_status");if(!t||!r)return null;if(s==="failed")return{status:"failed",error:new g("PayPal payment was declined. Please try again.","api_error")};let{paymentIntent:o,error:i}=await this.stripe.retrievePaymentIntent(r);if(i)return{status:"failed",error:new g(i.message??"Failed to retrieve PayPal payment","api_error")};if(o&&Zt(o.status)){let l=typeof o.payment_method=="string"?o.payment_method:o.payment_method?.id,a=new URL(window.location.href);return a.searchParams.delete("payment_intent"),a.searchParams.delete("payment_intent_client_secret"),a.searchParams.delete("redirect_status"),window.history.replaceState({},"",a.toString()),{status:o.status,paymentIntentId:o.id,paymentMethodId:l}}return{status:"failed",error:new g("PayPal payment was not completed. Please try again.","api_error")}}getRawProvider(){return this.stripe}createPayPalElements(e){if(!this.stripe)return null;let t={mode:"payment",amount:e.amount??0,currency:(e.currency??"usd").toLowerCase(),captureMethod:"manual"};return e.setupFutureUsage&&(t.setupFutureUsage=e.setupFutureUsage),e.appearance&&(t.appearance={theme:le(e.appearance.theme),variables:e.appearance.variables,rules:e.appearance.rules}),this.stripe.elements(t)}destroy(){this.elements=null,this.appliedAppearanceKey=null,this.appliedPaymentMethodTypesKey=null,this.appliedClientSecret=null,this.verifiedClientSecret=null,this.verifiedPaymentMethodTypesKey=null,this.stripe=null}};import{FloPayError as S,classifyTelemetryFailure as Me,resolveBillingApiUrl as at,SDK_VERSION as dr}from"@flopay/shared";import{FloPayError as nr}from"@flopay/shared";var W=class{constructor(e,t){this.elementMap=new Map;this.provider=e,this.baseOptions=t??{}}async create(e,t){let r={...this.baseOptions,...t};if(e==="payment"){let l=r.paymentMethodTypes?.map(a=>a.trim()).filter(a=>a&&a.toLowerCase()!=="card");if(!l?.length)throw new nr("At least one supported non-card payment method is required.","validation_error",{param:"paymentMethodTypes"});r.paymentMethodTypes=l}let s=this.provider.getElement(e);if(s)return this.elementMap.set(e,s),s;let o=this.elementMap.get(e);o&&o.destroy();let i=await this.provider.createElement(e,r);return this.elementMap.set(e,i),i}getElement(e){return this.elementMap.get(e)??null}async submit(){return{}}destroy(){for(let e of this.elementMap.values())e.destroy();this.elementMap.clear()}};import{buildTelemetryErrorEvent as or,buildTelemetryLogEvent as sr,buildTelemetryTerminalEvent as Ze,FloPayError as Je,resolveBillingApiUrl as Qe,SDK_VERSION as Xe}from"@flopay/shared";var be="flopay-vault",et={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 J(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:n.class==="lifecycle"?n.name:n.class==="technical_error"?n.code:n.class==="expected_outcome"?n.outcome:"sdk.performance",data:e})}catch{}}function ce(n,e){return sr({eventId:"11111111-1111-4111-8111-111111111111",name:n,stage:e,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}function tt(n){return n?{errorCode:"VAULT_SUBMIT_FAILED",stage:"vault_submit",failureCategory:"provider_runtime"}:{errorCode:"VAULT_LOAD_FAILED",stage:"vault_mount",failureCategory:"provider_runtime"}}function rt(n,e){return n.type==="decline"?"payment_declined":n.outcome==="authorized"||e==="manual"?"payment_authorized":"payment_succeeded"}function ir(n,e,t){let{type:r}=n;if(r==="complete"||r==="decline")return Ze({eventId:"22222222-2222-4222-8222-222222222222",outcome:rt(n,t),sequence:0,provider:"pcivault",paymentMethodCategory:"card"});if(r==="error"){let i=tt(e);return or({eventId:"33333333-3333-4333-8333-333333333333",...i,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}let[s,o]=et[r];return ce(s,o)}function ar(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===be&&(e.type==="ready"||e.type==="submitting"||e.type==="blocked"||e.type==="complete"||e.type==="decline"||e.type==="error"||e.type==="action_required")}function lr(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===be&&e.type==="validation"&&Array.isArray(e.messages)}function cr(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===be&&e.type==="resize"&&typeof e.height=="number"&&Number.isFinite(e.height)}var z=class{constructor(e={},t){this.provider="pcivault";this.container=null;this.messageHandler=null;this.actionOverlay=null;this.threeDsReturnHandler=null;this.messageToken=null;this.expectedOrigin=null;this.theme=null;this.submitGateBlocked=!1;this.cardFieldOrder=null;this.cardAutoFocus=!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 C({billingApiUrl:Qe(),sdkVersion:Xe}):void 0)}async mount(e,t){if(this.ownsTelemetryReporter&&!this.telemetryReporter&&(this.telemetryReporter=new C({billingApiUrl:Qe(),sdkVersion:Xe})),this.mountStartedAt=this.telemetryReporter?.now?.()??_(),this.vaultReadyReported=!1,this.submissionStarted=!1,this.submissionStartedAt=null,typeof window>"u"||typeof document>"u")throw this.reportVaultLoadFailure(),new Je("The vault card form is only available in the browser.","api_error",{code:"card_capture_no_window"});if(!t?.html||!t.html.trim())throw this.reportVaultLoadFailure(),new Je("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??null;try{this.attachMessageListener(),this.injectWidget(e,t.html)}catch(r){throw this.reportVaultLoadFailure(),r}this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),J(ce("vault.widget.mounted","vault_mount")),this.telemetryReporter?.log({name:"vault.widget.mounted",stage:"vault_mount",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(cr(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;this.applyHeight(r.height);return}if(lr(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;let l=r.messages.filter(a=>typeof a=="string"&&a.trim()).join(" ");this.emit("validation",{sessionId:this.config.sessionId,message:l||void 0});return}if(!ar(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={...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}:{}};r.type==="submitting"&&(this.submissionStarted=!0,this.submissionStartedAt=this.telemetryReporter?.now?.()??_()),J(ir(r,this.submissionStarted,this.config.captureMethod)),this.reportOutcome(r),r.type==="ready"&&(this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder()),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,i)};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"})),r==="complete"||r==="decline"){t.log({name:"vault.terminal",stage:"completion",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:rt(e,this.config.captureMethod),provider:"pcivault",paymentMethodCategory:"card"});return}if(r==="error"){let i=tt(this.submissionStarted);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]=et[r];t.log({name:s,stage:o,provider:"pcivault",paymentMethodCategory:"card"})}applyTheme(e){this.theme=e,this.postTheme()}postTheme(){if(!this.theme||!this.container)return;let t=this.container.querySelector("iframe")?.contentWindow;if(t)try{t.postMessage({source:"flopay-vault-host",type:"theme",theme:this.theme},"*")}catch{}}setSubmitGate(e){this.submitGateBlocked=e,this.postSubmitGate()}postSubmitGate(){if(!this.container)return;let t=this.container.querySelector("iframe")?.contentWindow;if(t)try{t.postMessage({source:"flopay-vault-host",type:"gate",blocked:this.submitGateBlocked},"*")}catch{}}setCardFieldOrder(e,t){this.cardFieldOrder=e,this.cardAutoFocus=t,this.postCardFieldOrder()}postCardFieldOrder(){if(!this.container)return;let t=this.container.querySelector("iframe")?.contentWindow;if(t)try{t.postMessage({source:"flopay-vault-host",type:"fieldOrder",order:this.cardFieldOrder,autoFocus:this.cardAutoFocus},"*")}catch{}}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);return}let t=document.createElement("div");t.setAttribute("data-flopay-action-required","1"),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.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 l=i.data;if(!l||typeof l!="object")return;let a=l;a.source==="flopay-vault-3ds-return"&&(J(ce("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(),this.postActionCompleted(a.status))};window.addEventListener("message",o),this.threeDsReturnHandler=o,document.body.appendChild(t),this.actionOverlay=t,J(ce("vault.three_ds.handoff","three_ds_handoff"))}postActionCompleted(e){if(!this.container)return;let r=this.container.querySelector("iframe")?.contentWindow;if(r)try{r.postMessage({source:"flopay-vault-host",type:"action_completed",status:typeof e=="string"?e:"unknown"},"*")}catch{}}abandonActionRequiredOverlay(){if(!this.actionOverlay)return;let e=Ze({eventId:"77777777-7777-4777-8777-777777777777",outcome:"customer_abandoned",stage:"three_ds_handoff",sequence:0,provider:"pcivault",paymentMethodCategory:"card"});J(e),this.telemetryReporter?.terminal({outcome:"customer_abandoned",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"}),this.hideActionRequiredOverlay(),this.postActionCompleted("abandoned")}hideActionRequiredOverlay(){this.threeDsReturnHandler&&(window.removeEventListener("message",this.threeDsReturnHandler),this.threeDsReturnHandler=null),this.actionOverlay&&(this.actionOverlay.parentNode?.removeChild(this.actionOverlay),this.actionOverlay=null)}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 nt(n,e){let t=z;return new t(n,{reporter:e})}var ot=Symbol.for("@flopay/js.telemetry.bridge.v1");function st(n,e,t){let r=()=>e?.now()??t();Object.defineProperty(n,ot,{configurable:!1,enumerable:!1,writable:!1,value:{error:o=>e?.error(o),log:o=>e?.log(o),performance:o=>e?.performance(o),terminal:o=>e?.terminal(o),now:r,elapsed:o=>Math.max(0,r()-o),setCheckoutContext:o=>e?.setCheckoutContext(o),beginCheckout:(o={})=>e?.beginCheckout(o)??r(),disable:()=>e?.disable()}})}function it(n){return n[ot]}function B(n){if(!n)return!1;let e=n.code?.toLowerCase()??"";return!!n.declineCode||e.includes("declin")}function ur(n){return n==="stripe"||n==="paypal"||n==="pcivault"?n:"other"}var de=class{constructor(e,t,r){this.currentElements=null;this.provider=e,this.config=t,this.telemetryReporter=r??new C({billingApiUrl:at(t.billingApiUrl),sdkVersion:dr,enabled:t.telemetry!==!1}),st(this,this.telemetryReporter,_)}now(){return this.telemetryReporter?.now?.()??_()}elements(e){return this.currentElements&&this.currentElements.destroy(),this.currentElements=new W(this.provider,{appearance:this.config.appearance,...e}),this.currentElements}async submitElements(){return this.provider.submitElements()}cardCapture(e){return this.telemetryReporter?.log({name:"vault.capture.requested",stage:"vault_request",provider:"pcivault",paymentMethodCategory:"card"}),this.telemetryReporter?nt({sessionId:e?.sessionId,captureMethod:e?.captureMethod},this.telemetryReporter):new z({sessionId:e?.sessionId,captureMethod:e?.captureMethod,telemetry:!1})}async confirmPayPalPayment(e){let t=this.now();this.telemetryReporter?.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),this.telemetryReporter?.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});try{let r=await this.provider.confirmPayPalPayment(e);return this.telemetryReporter?.performance({stage:"processing",durationMs:this.now()-t,durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),r.error||this.telemetryReporter?.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),r.status==="requires_action"?(this.telemetryReporter?.log({name:"provider.redirect.started",stage:"redirect",provider:"paypal",paymentMethodCategory:"paypal"}),this.telemetryReporter?.terminal({outcome:"action_required",stage:"redirect",provider:"paypal",paymentMethodCategory:"paypal"})):r.status==="succeeded"?this.telemetryReporter?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}):r.status!=="processing"&&(B(r.error)?this.telemetryReporter?.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):r.error?.type==="validation_error"?this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal"}):r.error&&this.telemetryReporter?.error({errorCode:"PAYMENT_PROCESSING_FAILED",failureCategory:"provider_runtime",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"})),r}catch(r){if(this.telemetryReporter?.performance({stage:"processing",durationMs:this.now()-t,durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),r instanceof S&&B(r))this.telemetryReporter?.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"});else if(r instanceof S&&r.type==="validation_error")this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal"});else{let s=Me(r,"PAYMENT_PROCESSING_FAILED","unknown");this.telemetryReporter?.error({...s,failureCategory:s.failureCategory??"provider_runtime",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"})}throw r}}async resumePayPalPayment(){let e=this.now();try{let t=await this.provider.resumePayPalPayment();return t===null?null:(this.telemetryReporter?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),this.telemetryReporter?.performance({stage:"redirect_resume",durationMs:this.now()-e,durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),t.status==="succeeded"?this.telemetryReporter?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}):B(t.error)?this.telemetryReporter?.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):t.error?.type==="validation_error"?this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal"}):t.error&&this.telemetryReporter?.error({errorCode:"REDIRECT_RESUME_FAILED",failureCategory:"provider_runtime",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),t)}catch(t){if(this.telemetryReporter?.performance({stage:"redirect_resume",durationMs:this.now()-e,durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),t instanceof S&&B(t))this.telemetryReporter?.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"});else if(t instanceof S&&t.type==="validation_error")this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal"});else{let r=Me(t,"REDIRECT_RESUME_FAILED","unknown");this.telemetryReporter?.error({...r,failureCategory:r.failureCategory??"provider_runtime",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"})}throw t}}async confirmPayment(e){if(e.paymentMethodCategory!=="wallet"&&e.paymentMethodCategory!=="apm"||!e.paymentMethodType?.trim()||e.paymentMethodType.trim().toLowerCase()==="card")throw new S("A supported non-card payment method is required.","validation_error",{param:"paymentMethodType"});let t=this.now(),r=ur(this.provider.name);this.telemetryReporter?.log({name:"payment.processing.started",stage:"processing",provider:r,paymentMethodCategory:e.paymentMethodCategory});try{let s=await this.provider.confirmPayment(e),o=this.now()-t;return this.telemetryReporter?.performance({stage:"processing",durationMs:o,durationMode:"machine",provider:r,paymentMethodCategory:e.paymentMethodCategory}),s.status==="succeeded"?this.telemetryReporter?.terminal({outcome:"payment_succeeded",provider:r,paymentMethodCategory:e.paymentMethodCategory}):B(s.error)?this.telemetryReporter?.terminal({outcome:"payment_declined",provider:r,paymentMethodCategory:e.paymentMethodCategory}):s.error?.type==="validation_error"?this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:r,paymentMethodCategory:e.paymentMethodCategory}):s.status==="requires_action"?this.telemetryReporter?.terminal({outcome:"action_required",stage:"three_ds_handoff",provider:r,paymentMethodCategory:e.paymentMethodCategory}):s.status==="failed"&&s.error&&this.telemetryReporter?.error({errorCode:"PAYMENT_PROCESSING_FAILED",failureCategory:"provider_runtime",stage:"processing",provider:r,paymentMethodCategory:e.paymentMethodCategory}),s.status==="succeeded"||s.status==="failed"?this.telemetryReporter?.log({name:"payment.processing.completed",stage:"processing",provider:r,paymentMethodCategory:e.paymentMethodCategory}):this.telemetryReporter?.log({name:"operation.state_transition",stage:s.status==="requires_action"?"three_ds_handoff":"processing",provider:r,paymentMethodCategory:e.paymentMethodCategory}),s}catch(s){throw this.telemetryReporter?.performance({stage:"processing",durationMs:this.now()-t,durationMode:"machine",provider:r,paymentMethodCategory:e.paymentMethodCategory}),s instanceof S&&B(s)?this.telemetryReporter?.terminal({outcome:"payment_declined",provider:r,paymentMethodCategory:e.paymentMethodCategory}):s instanceof S&&s.type==="validation_error"?this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:r,paymentMethodCategory:e.paymentMethodCategory}):this.telemetryReporter?.error({errorCode:"PAYMENT_PROCESSING_FAILED",failureCategory:"provider_runtime",stage:"processing",provider:r,paymentMethodCategory:e.paymentMethodCategory}),s}}async retrieveSession(e,t){if(!e)throw new S("sessionId is required to retrieve a session.","validation_error",{param:"sessionId"});let r=await this.retrieveUnifiedSession(e,t);if(!r.data.session)throw new S("Session not found","api_error");return r.data.session}async retrieveUnifiedSession(e,t){if(!e)throw new S("sessionId is required.","validation_error",{param:"sessionId"});let r=at(t??this.config.billingApiUrl),s=this.now();this.telemetryReporter?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let o,i=Ge(r,{now:()=>this.telemetryReporter?.now()??_(),onFirstByte:l=>{o=l},onRetry:(l,a)=>{this.telemetryReporter?.log({name:"operation.retry",stage:l==="session_read"?"session_read":"processing",requestCategory:l,attempt:a})}});try{let l=await i.getUnifiedCheckoutSession(e);return o!==void 0&&(this.telemetryReporter?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:"2xx"}),this.telemetryReporter?.performance({stage:"session_first_byte",durationMs:o,durationMode:"machine",requestCategory:"session_read",statusClass:"2xx"})),this.telemetryReporter?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:"2xx"}),this.telemetryReporter?.log({name:"checkout.data.ready",stage:"checkout_data_ready"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-s,durationMode:"machine",requestCategory:"session_read",statusClass:"2xx"}),l}catch(l){let a=Me(l,l instanceof S&&l.code==="checkout_processing_timeout"?"REQUEST_TIMEOUT":"NETWORK_REQUEST_FAILED");throw this.telemetryReporter?.error({...a,stage:"session_read",provider:"flo",paymentMethodCategory:"unknown"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-s,durationMode:"machine",requestCategory:"session_read",statusClass:a.statusClass}),l}}getRawProvider(){return this.provider.getRawProvider()}destroy(){this.telemetryReporter?.log({name:"checkout.unmount",stage:"unmount"}),this.telemetryReporter?.destroy(),this.currentElements?.destroy(),this.currentElements=null,this.provider.destroy()}};function lt(n,e,t){let r=de;return new r(n,e,t)}var dt=new Map;function Pe(n){return Array.isArray(n)?n.map(Pe):n&&typeof n=="object"?Object.fromEntries(Object.entries(n).filter(([,e])=>e!==void 0).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,Pe(t)])):n}function mr(n,e){return JSON.stringify([n,ke(e?.billingApiUrl),e?.telemetry!==!1,e?.locale??"auto",e?.apiVersion??null,Pe(e?.appearance??null)])}var ue=new Map;async function yr(n,e){if(!n){let l=new C({billingApiUrl:ke(e?.billingApiUrl),sdkVersion:ct,enabled:e?.telemetry!==!1});throw l.error({errorCode:"CONFIGURATION_INVALID",stage:"sdk_initialize",paymentMethodCategory:"unknown"}),l.flush().catch(()=>{}).finally(()=>l.destroy()),new pr("A publishable key is required to initialize FloPay.","validation_error",{param:"publishableKey"})}let t=mr(n,e),r=dt.get(t);if(r)return e?.telemetry!==!1&&it(r)?.log({name:"sdk.cache.hit",stage:"sdk_initialize"}),r;let s=ue.get(t);if(s)return s;let o={...e,publishableKey:n},i=(async()=>{let l=new C({billingApiUrl:ke(o.billingApiUrl),sdkVersion:ct,enabled:o.telemetry!==!1}),a=l.now();l.log({name:"sdk.initialize.started",stage:"sdk_initialize"}),l.log({name:"sdk.cache.miss",stage:"sdk_initialize"}),l.log({name:"provider.load.started",stage:"provider_load",provider:"stripe"});let c=new Y,d=l.now();try{await c.initialize(o)}catch(p){throw l.error({errorCode:"SDK_INITIALIZATION_FAILED",failureCategory:"provider_runtime",stage:"sdk_initialize",provider:"stripe",paymentMethodCategory:"unknown"}),l.destroy(),p}let m=l.now();l.log({name:"provider.ready",stage:"provider_ready",provider:"stripe"}),l.log({name:"provider.availability.checked",stage:"provider_ready",provider:"stripe"}),l.log({name:"sdk.initialize.ready",stage:"sdk_initialize"}),l.performance({stage:"sdk_initialize",durationMs:m-a,durationMode:"machine",provider:"stripe"}),l.performance({stage:"provider_ready",durationMs:m-d,durationMode:"machine",provider:"stripe"});let u=lt(c,o,l);return dt.set(t,u),u})();ue.set(t,i);try{return await i}finally{ue.get(t)===i&&ue.delete(t)}}import{FloPayError as K,IDEMPOTENCY_IN_PROGRESS_CODE as hr,IDEMPOTENCY_KEY_HEADER as gr,SDK_VERSION as ut,assertCaptureMethodEligible as fr,buildProductPayload as Cr,classifyTelemetryFailure as vr,foldIntoProducts as Tr,resolveIdempotencyKey as pt,resolveSessionCurrency as _r,telemetryStatusClass as mt}from"@flopay/shared";var Ee=5,yt=new WeakSet;function wr(n){(typeof n=="object"&&n!==null||typeof n=="function")&&yt.add(n)}function Sr(n){return(typeof n=="object"&&n!==null||typeof n=="function")&&yt.has(n)}function br(n,e){let t=e?.error,r=E(e?.code)??E(t?.code)??`http_${n}`,s=E(e?.message)??E(t?.message)??Mr(r,n);return new K(s,"api_error",{code:r,statusCode:n})}function Mr(n,e){switch(n){case"CouponLimitExceeded":return`Too many coupon codes \u2014 a checkout session accepts at most ${Ee}.`;case"CouponCurrencyUnsupported":return"One of the applied coupons has no price configured for the cart currency.";default:return`Failed to create checkout session (HTTP ${e}).`}}async function ht(n,e,t){let{billingApiUrl:r,checkoutBaseUrl:s,items:o=[],subscriptions:i=[],products:l,account:a,successUrl:c,cancelUrl:d,checkoutMode:m="confirm",captureMethod:u,couponCodes:p=[],tagsData:w,redirectParams:v={},setCookie:T=!0,clientId:Re,currency:H,utmMetadata:y,idempotencyKey:Q}=n,X=pt(Q);if(p.length>Ee)throw new K(`Too many coupon codes \u2014 a checkout session accepts at most ${Ee}.`,"validation_error",{code:"CouponLimitExceeded",param:"couponCodes"});let P=l??Tr(o,i);fr({captureMethod:u,products:P});let M=_r(H,o,i,P);if(!M)throw new K("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 F={clientId:Re,checkoutVersion:ut,successUrl:c,cancelUrl:d,currency:M,checkoutMode:m,products:P.map(k=>Cr(k,M)),accountData:{userId:a.userId,firstName:a.firstName??null,lastName:a.lastName??null,email:a.email,country:a.country??null,gender:a.gender??null,city:a.city??null,state:a.state??null,zip:a.zip??null,addressLine1:a.addressLine1??null,addressLine2:a.addressLine2??null},couponCodes:p};u==="manual"&&(F.captureMethod=u),w&&(F.tagsData=w),y?.length&&(F.utmMetadata=y);let $=`${r.replace(/\/+$/,"")}/v1/checkouts/sessions`,Z={"Content-Type":"application/json"};X&&(Z[gr]=X);let O,ee,vt={method:"POST",headers:Z,body:JSON.stringify(F),signal:e},te;try{te=await fetch($,vt)}catch(k){throw wr(k),k}try{t?.(te.status)}catch{}O=te.status;try{ee=await te.json()}catch{}if(O>=400)throw br(O,ee);if(O===201){let k=ee?.data?.uuid,me=ee?.data?.nonce;if(!k)throw new Error("Checkout session created but no UUID was returned by the billing API");if(!me)throw new K("Checkout session created but no `nonce` was returned by the billing API. Upgrade the billing service to TeamFloPay/backend#640 or later.","api_error",{code:"MissingCheckoutSessionToken"});(P.length||M)&&q(k,{currency:M,products:P.map(f=>({code:f.code??f.providerItemId??f.providerPlanId,type:f.type,name:f.name??f.itemName??f.providerItemName??f.subscriptionName??f.providerPlanName??null,totalAmount:f.totalAmount,overrideAmount:f.overrideAmount,currency:f.currency??M}))});let re=new URL(`${s.replace(/\/+$/,"")}/secure`);re.searchParams.set("id",k);for(let[f,ne]of Object.entries(v))re.searchParams.set(f,ne);if(T&&typeof window<"u"&&typeof document<"u"){let f=JSON.stringify({origin_url:d}),ne=window.location.hostname.split(".").slice(-2).join(".");document.cookie=`checkout_data=${encodeURIComponent(f)}; domain=.${ne}; path=/; max-age=3600; SameSite=Lax; Secure;`,document.cookie=`flopay_checkout_token=${encodeURIComponent(me)}; domain=.${ne}; path=/; max-age=3600; SameSite=Lax; Secure;`}return typeof window<"u"&&(window.location.href=re.toString()),{status:201,redirectUrl:re.toString(),nonce:me}}return O===204?(typeof window<"u"&&(window.location.href=c),{status:204}):{status:O}}async function kr(n){let e=ft(n),t=gt(e),r=R(n.timeoutMs);try{let s=await ht(n,r.signal,t);return Ct(e,s),s}catch(s){throw pe(e,s),s}finally{r.clear(),j(e.reporter)}}function gt(n){let e=!1;return t=>{if(e)return;e=!0;let r=mt(t);n.reporter.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:r,attempt:n.attempt}),n.reporter.performance({stage:"session_first_byte",durationMs:n.reporter.now()-n.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:r,attempt:n.attempt})}}function ft(n){let e=new C({billingApiUrl:n.billingApiUrl,sdkVersion:ut,enabled:n.telemetry!==!1}),t=e.now();return e.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"}),{reporter:e,startedAt:t,attempt:0}}function Ct(n,e){let t=mt(e.status);n.reporter.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:t}),n.reporter.performance({stage:"session_create",durationMs:n.reporter.now()-n.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:t,attempt:n.attempt})}function pe(n,e){let{reporter:t}=n,r=vr(e,"CHECKOUT_SESSION_CREATE_FAILED");if(t.performance({stage:"session_create",durationMs:t.now()-n.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:r.statusClass,attempt:n.attempt}),e instanceof K&&e.type==="validation_error"){t.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"});return}if(r.statusClass==="4xx"){t.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create",statusClass:"4xx"});return}t.error({...r,stage:"session_create",requestCategory:"session_create"})}function j(n){n.flush().catch(()=>{}).finally(()=>n.destroy())}async function Pr(n){let{maxRetries:e=2,...t}=n,r=ft(n),s=gt(r);if(!Number.isFinite(e)||!Number.isInteger(e)||e<0||e>=3)throw r.reporter.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),j(r.reporter),new Error(`Number of retries must be an integer between 0 and ${2}`);let o={...t,idempotencyKey:pt(t.idempotencyKey)},i=R(t.timeoutMs),l;for(let a=0;a<=e;a++){r.attempt=a;try{let c=await ht(o,i.signal,s);return Ct(r,c),i.clear(),j(r.reporter),c}catch(c){l=c;let d=c instanceof Error&&c.name==="AbortError",m=Sr(c),u=c instanceof K&&c.code===hr;if((d||m||u)&&!i.signal.aborted&&a<e){r.reporter.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:a+1});try{await L(a,i.signal)}catch(p){throw pe(r,p),i.clear(),j(r.reporter),p}continue}throw pe(r,c),i.clear(),j(r.reporter),c}}throw pe(r,l),i.clear(),j(r.reporter),l??new Error("Unknown error during checkout session creation")}import{dropThirdPartyOnlyError as Pn}from"@flopay/shared";export{de as FloPay,W as FloPayElements,x as PaymentAPI,z as PciVaultCardCapture,Ke as SESSION_CREATE_TELEMETRY,Y as StripeAdapter,q as cacheSessionDisplayData,ge as clearSessionDisplayData,kr as createCheckoutSession,Pr as createCheckoutSessionWithRetries,Pn as dropThirdPartyOnlyError,he as getSessionDisplayData,yr as loadFloPay,tr as toStripeAppearance,le as toStripeAppearanceTheme};
|
|
1
|
+
import{FloPayError as mr,resolveBillingApiUrl as ke,SDK_VERSION as ct}from"@flopay/shared";import{loadStripe as Xt}from"@stripe/stripe-js";import{FloPayError as g,isMoneySettledOutcome as Zt,isSetupIntentClientSecret as er}from"@flopay/shared";import{FloPayError as h,SDK_VERSION as N,FLO_SDK_VERSION_HEADER as ve,IDEMPOTENCY_KEY_HEADER as Oe,IDEMPOTENCY_IN_PROGRESS_CODE as Ot,assertCaptureMethodEligible as qe,buildProductPayload as Be,classifyPaymentRejection as qt,classifyTelemetryFailure as G,foldIntoProducts as Te,isDetachedSessionEligible as Ut,isUuidV4 as Ue,normalizeCheckoutFailureOutcome as Le,randomUuidV4 as Lt,resolveIdempotencyKey as Nt,resolveSessionCurrency as _e,telemetryStatusClass as A}from"@flopay/shared";function E(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}var Tt="flopay_session_display:";var oe=new Map;function se(n){return`${Tt}${n}`}function ye(){if(typeof window>"u")return null;try{return window.sessionStorage}catch{return null}}function q(n,e,t){if(!n)return;let r=t?.ttlMs??36e5,o={data:e,expiresAt:Date.now()+r},s=ye();if(s)try{s.setItem(se(n),JSON.stringify(o));return}catch{}oe.set(n,o)}function he(n){if(!n)return null;let e=ye();if(e)try{let r=e.getItem(se(n));if(r){let o=JSON.parse(r);if(o&&typeof o.expiresAt=="number"&&o.expiresAt>Date.now())return o.data;e.removeItem(se(n))}}catch{}let t=oe.get(n);if(t){if(t.expiresAt>Date.now())return t.data;oe.delete(n)}return null}function ge(n){if(!n)return;oe.delete(n);let e=ye();if(e)try{e.removeItem(se(n))}catch{}}import{buildTelemetryErrorEvent as Ie,buildTelemetryLogEvent as _t,buildTelemetryPerformanceEvent as wt,buildTelemetryTerminalEvent as St,serializeTelemetryBatch as bt,TELEMETRY_MAX_BATCH_BYTES as Mt}from"@flopay/shared";var kt="/v1/sdk-telemetry/events",fe=16,Pt=64,Et=1500,xe=1e3,Rt=64,At="00000000-0000-4000-8000-000000000000",It={technical_error:8,lifecycle:32,expected_outcome:32,performance:24};function U(){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]&15|64,n[8]=n[8]&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 xt(n){try{return new TextEncoder().encode(n).byteLength}catch{return n.length}}function Dt(n){return JSON.stringify([n.code,n.failureCategory,n.stage,n.provider,n.attempt,n.statusClass,n.requestCategory,n.paymentMethodCategory,n.checkoutMode,n.layout])}function _(){return globalThis.performance?.now()??0}var C=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.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(/\/+$/,"")}${kt}`,this.sdkPackage=e.sdkPackage??"@flopay/js",this.sdkVersion=e.sdkVersion,this.correlationId=U(),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.canCollect()&&this.enqueue(_t({...this.checkoutContext,...e,eventId:U(),sequence:this.sequence++}))}error(e){if(!this.canCollect())return;let t=Ie({...this.checkoutContext,...e,eventId:At,sequence:0}),r=Dt(t),o=this.now();this.pruneReportedFailures(o);let s=this.reportedFailures.get(r);if(s!==void 0&&o>=s&&o-s<xe){this.log({name:"operation.deduplicated",stage:e.stage,provider:e.provider,paymentMethodCategory:e.paymentMethodCategory,attempt:e.attempt});return}this.rememberReportedFailure(r,o),this.enqueue(Ie({...this.checkoutContext,...e,eventId:U(),sequence:this.sequence++}))}performance(e){this.canCollect()&&this.enqueue(wt({...this.checkoutContext,...e,eventId:U(),sequence:this.sequence++}))}terminal(e){if(this.canCollect()&&(this.enqueue(St({...this.checkoutContext,...e,eventId:U(),sequence:this.sequence++})),e.outcome!=="action_required"&&this.checkoutStartedAt!==null)){let t=this.checkoutStartedAt;this.checkoutStartedAt=null,this.performance({stage:"total_journey",durationMs:Math.max(0,this.now()-t),durationMode:"total",provider:e.provider,paymentMethodCategory:e.paymentMethodCategory})}}now(){try{return this.clock()}catch{return _()}}pruneReportedFailures(e){for(let[t,r]of this.reportedFailures)(e<r||e-r>=xe)&&this.reportedFailures.delete(t)}rememberReportedFailure(e,t){for(;this.reportedFailures.size>=Rt;){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>=Pt||this.eventCounts[e.class]>=It[e.class])){if(this.eventCounts[e.class]+=1,this.queue.push(e),this.queue.length>=fe){this.flush();return}this.scheduleFlush()}}canCollect(){return this.browserTransportAvailable&&this.merchantEnabled&&!this.ingestionDisabled&&!this.destroyed}async flush(){if(this.flushInFlight)return this.flushInFlight;if(!this.browserTransportAvailable||this.destroyed||this.ingestionDisabled||this.queue.length===0)return;this.clearFlushTimer();let e=this.queue.splice(0,fe);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())}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,fe);this.sendBatch(e)}}async sendBatch(e){if(!this.browserTransportAvailable||this.ingestionDisabled)return;let t=bt(e,{correlationId:this.correlationId,sdkPackage:this.sdkPackage,sdkVersion:this.sdkVersion,batchId:U()});if(xt(t)>Mt)return;let r=typeof AbortController>"u"?null:new AbortController,o=null;try{let s=fetch(this.endpoint,{method:"POST",headers:{"content-type":"text/plain;charset=UTF-8"},body:t,credentials:"omit",keepalive:!0,referrerPolicy:"no-referrer",signal:r?.signal}).then(async l=>l.status!==202?null:(await l.json().catch(()=>null))?.status==="disabled"?"disabled":null).catch(()=>null),i=new Promise(l=>{o=setTimeout(()=>{r?.abort(),l(null)},Et)});await Promise.race([s,i])==="disabled"&&this.disableFromIngestion()}catch{}finally{o&&clearTimeout(o)}}disableFromIngestion(){this.ingestionDisabled=!0,this.queue.splice(0),this.reportedFailures.clear(),this.clearFlushTimer()}scheduleFlush(){this.flushTimer||this.destroyed||this.ingestionDisabled||(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush()},0))}clearFlushTimer(){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null)}},De=Symbol.for("@flopay/js.telemetry.reporter-factory.v1"),Fe=globalThis;Fe[De]===void 0&&Object.defineProperty(Fe,De,{configurable:!0,enumerable:!1,writable:!1,value:n=>new C(n)});function R(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 Ft(){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((o,s)=>{let i,a=()=>e.removeEventListener("abort",l),l=()=>{i!==void 0&&clearTimeout(i),a(),s(Ft())};if(e.aborted){l();return}i=setTimeout(()=>{a(),o()},r),e.addEventListener("abort",l,{once:!0})})}var Ne=1e3,Vt=500,zt=15e3,Bt=3e3,jt=1e4,Kt=1e4;function Ht(n){return typeof n=="object"&&n!==null}function V(n,e){return E(n?.[e])}function Ve(n,e){return Ae(n?.[e])}function $t(n,e){let t=n?.[e];return typeof t=="number"&&Number.isFinite(t)?t:void 0}function je(n){return new Promise(e=>setTimeout(e,n))}function ie(){return new h("Checkout is still processing. Please try again shortly.","api_error",{code:"checkout_processing_timeout"})}async function I(n,e){let t=await n.json().catch(()=>null),r=Ht(t?.error)?t.error:null,o=Ve(t,"message")??Ve(r,"message")??e,s=V(t,"code")??V(t,"gatewayErrorCode")??V(r,"code")??`http_${n.status}`;return new h(o,"api_error",{code:s,statusCode:n.status})}async function Gt(n){let e=n.status===400?await n.clone().json().catch(()=>null):null;return qt(n.status,e)}function ze(n){return n===400||n===422}var ae=2;async function we(n,e,t=ae,r){let o;for(let s=0;;s++)try{return await fetch(n,e)}catch(i){if(e?.signal?.aborted||i instanceof Error&&i.name==="AbortError")throw i;if(o=i,s>=t)throw o;try{r?.(s+1)}catch{}await je(150*2**s)}}var Ke=Symbol.for("@flopay/js.session-create.telemetry.v1");function Yt(n){return n[Ke]}function Wt(n){return"now"in n||"onFirstByte"in n||"onSessionCreateFailure"in n||"onRetry"in n}function He(n){return{userId:n.userId,firstName:n.firstName??null,lastName: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 $e(n,e){e.tagsData&&(n.tagsData=e.tagsData),e.utmMetadata?.length&&(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 Jt(n,e){let t={clientId:n.clientId,checkoutVersion:N,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}),$e(t,n),t}function Qt(n,e,t){return{currency:e,products:t.map(r=>Be(r,e)),couponCodes:n.couponCodes??[],accountData:He(n.account)}}var x=class x{constructor(e,t={}){this.baseUrl=e.replace(/\/+$/,"");let r=Wt(t);this.telemetryHooks=r?t:void 0,this.directTelemetry=r||t.telemetry===!1?void 0:new C({billingApiUrl:this.baseUrl,sdkVersion:N})}destroy(){this.directTelemetry?.destroy()}reportDirectFailure(e,t,r,o,s="unknown"){let i=G(e,t);this.directTelemetry?.error({...i,stage:r,requestCategory:o,paymentMethodCategory:s})}reportAccountSnapshotFailure(e,t){let r=G(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){this.beginDirectTelemetryCheckout(e);let r=this.telemetryTimestamp();this.directTelemetry?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let o={[ve]:N};t&&(o["x-checkout-session-token"]=t);try{let s=await we(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}`,{headers:o},ae,c=>{this.telemetryHooks?.onRetry?.("session_read",c),this.directTelemetry?.log({name:"operation.retry",stage:"session_read",requestCategory:"session_read",attempt:c})}),i=Math.max(0,this.telemetryTimestamp()-r);try{this.telemetryHooks?.onFirstByte?.(i)}catch{}let a=`${Math.floor(s.status/100)}xx`;if(this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:a}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:i,durationMode:"machine",requestCategory:"session_read",statusClass:a}),!s.ok)throw await I(s,"Failed to get checkout session");let l=await s.json();return this.directTelemetry?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:a}),this.directTelemetry?.performance({stage:"session_complete",durationMs:Math.max(0,this.telemetryTimestamp()-r),durationMode:"machine",requestCategory:"session_read",statusClass:a}),{...l,data:this.mergeCachedDisplayData(l.data)}}catch(s){throw this.directTelemetry?.error({...G(s,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"}),s}}cacheSessionDisplayData(e,t,r){q(e,t,r)}clearSessionDisplayData(e){ge(e)}async getVaultCapture(e,t){let r=`${this.baseUrl}\0${e}\0${t??""}`,o=x.activeVaultCaptureRequests.get(r);if(o)return o;let s=this.requestVaultCapture(e,t);x.activeVaultCaptureRequests.set(r,s);try{return await s}finally{x.activeVaultCaptureRequests.get(r)===s&&x.activeVaultCaptureRequests.delete(r)}}async requestVaultCapture(e,t){let r=new AbortController,o=setTimeout(()=>r.abort(),Kt);this.beginDirectTelemetryCheckout(e);let s=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 we(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/vault/capture`,{method:"POST",headers:i,signal:r.signal},ae,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 I(a,"Failed to load the secure card form");let l=await a.json();return this.directTelemetry?.performance({stage:"vault_request",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"2xx"}),this.toVaultBlock(l)}catch(a){let l=r.signal.aborted?new h("Timed out while loading the secure card form. Please try again.","api_error",{code:"vault_capture_timeout"}):a;throw this.reportDirectFailure(l,"VAULT_LOAD_FAILED","vault_request","vault_capture","card"),l}finally{clearTimeout(o)}}async getUnifiedCheckoutSession(e,t){let r=await this.getCheckoutSession(e,t),o=this.normalizeRawSession(r.data),s=r.vault;return s&&o.data.session&&(o.data.session.vault=this.toVaultBlock(s)),o}async processPayment(e,t,r){if(this.beginDirectTelemetryCheckout(t.sessionId),!t.nonce)throw this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"process_payment"}),new h("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"});let{nonce:s,...i}=t,a;try{a=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(t.sessionId)}/process`,{method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":s},body:JSON.stringify(i)})}catch(l){throw this.reportDirectFailure(l,"PAYMENT_PROCESSING_FAILED","processing","process_payment"),l}if(!a.ok&&a.status!==202){let l=await Gt(a);return l?this.directTelemetry?.terminal({outcome:l,stage:"processing",requestCategory:"process_payment",statusClass:"4xx"}):this.directTelemetry?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",requestCategory:"process_payment",statusClass:A(a.status),failureCategory:a.status>=500?"server_error":void 0}),a}try{let l=await this.resolveProcessResponse(a,t.sessionId,{...r,nonce:s});return this.directTelemetry?.log({name:"payment.processing.completed",stage:"processing",requestCategory:"process_payment",statusClass:A(l.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"process_payment",statusClass:A(l.status)}),l}catch(l){throw l instanceof h&&l.code==="checkout_processing_timeout"||this.reportDirectFailure(l,"PAYMENT_PROCESSING_FAILED","processing","process_payment"),l}}async patchAccountSnapshot(e,t,r,o){this.beginDirectTelemetryCheckout(e);let s=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.state_transition",stage:"processing",requestCategory:"account_snapshot"});let i=o?.timeoutMs??jt,a=new AbortController,l=()=>a.abort();o?.signal&&(o.signal.aborted?a.abort():o.signal.addEventListener("abort",l,{once:!0}));let c=setTimeout(()=>a.abort(),i);try{let d;try{d=await we(`${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},ae,m=>{this.telemetryHooks?.onRetry?.("account_snapshot",m),this.directTelemetry?.log({name:"operation.retry",stage:"processing",requestCategory:"account_snapshot",attempt:m})})}finally{clearTimeout(c),o?.signal?.removeEventListener("abort",l)}if(!d.ok)throw await I(d,"Failed to persist account snapshot");this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"account_snapshot",statusClass:"2xx"})}catch(d){throw this.reportAccountSnapshotFailure(d,o?.telemetryMode??"blocking"),d}}async createSessionIntent(e,t,r,o){if(!t)throw new h("createSessionIntent requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let s=r,i=s.paymentMethodType,a=typeof i=="string"&&i.trim().toLowerCase()==="card",l=typeof i=="string"&&i.length>0&&!a&&(typeof s.paymentMethodId=="string"||s.paymentMethodId===null),c=s.provider==="stripe"&&(s.paymentMethodCategory==="wallet"||s.paymentMethodCategory==="apm")&&(s.intentKind==="payment"||s.intentKind==="setup"),d=s.provider==="paypal"&&s.paymentMethodCategory==="wallet"&&s.paymentMethodType==="paypal"&&s.paymentMethodId===null&&s.intentKind==="payment";if(!l||!c&&!d)throw new h("Only wallet, APM, and PayPal session intents are supported.","validation_error",{code:"InvalidSessionIntentRequest"});let m=s.authorizationAttemptId;if(m!==void 0&&!Ue(m))throw new h("authorizationAttemptId must be a v4 UUID identifying one buyer authorization attempt.","validation_error",{code:"InvalidAuthorizationAttemptId",param:"authorizationAttemptId"});let u=Ue(m)?m:Lt();this.beginDirectTelemetryCheckout(e);let p=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.intent.started",stage:"processing",requestCategory:"intent_create"});let w={"Content-Type":"application/json","x-checkout-session-token":t,[Oe]:o?.idempotencyKey||u},v=!1;try{let T=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents`,{method:"POST",headers:w,body:JSON.stringify({...r,authorizationAttemptId:u}),signal:o?.signal});if(!T.ok){v=!0;let $=await I(T,"Failed to create checkout intent"),Z=G($,"PAYMENT_PROCESSING_FAILED");throw ze($.statusCode)?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"intent_create",statusClass:"4xx"}):this.directTelemetry?.error({...Z,stage:"processing",requestCategory:"intent_create"}),$}let H=(await T.json()).data;if(!H||typeof H!="object")throw new h("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});let y=H,Q=y.paymentMethodType,X=(y.paymentMethodCategory==="wallet"||y.paymentMethodCategory==="apm")&&typeof Q=="string"&&Q.trim().toLowerCase()!=="card"&&(typeof y.paymentMethodId=="string"||y.paymentMethodId===null)&&typeof y.providerObjectId=="string",P=y.provider==="stripe"&&(y.intentKind==="payment"||y.intentKind==="setup")&&typeof y.clientSecret=="string",M=y.provider==="paypal"&&y.paymentMethodCategory==="wallet"&&y.paymentMethodType==="paypal"&&y.paymentMethodId===null&&y.intentKind==="payment"&&(y.providerObjectType==="order"||y.providerObjectType==="subscription")&&y.clientSecret===null,F=y.provider===r.provider&&y.paymentMethodCategory===r.paymentMethodCategory&&y.paymentMethodType===r.paymentMethodType&&y.paymentMethodId===r.paymentMethodId&&y.intentKind===r.intentKind;if(!X||!P&&!M||!F)throw new h("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});return this.directTelemetry?.log({name:"payment.intent.completed",stage:"processing",requestCategory:"intent_create",statusClass:A(T.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-p),durationMode:"machine",requestCategory:"intent_create",statusClass:A(T.status)}),y}catch(T){throw v||this.reportDirectFailure(T,"PAYMENT_PROCESSING_FAILED","processing","intent_create"),T}}async reportSessionIntentDecline(e,t,r,o){if(!t)throw new h("reportSessionIntentDecline requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let s=r,i=s.providerDeclineReason,a=s.paymentMethodType,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),c=typeof a=="string"&&a.length>0&&a.trim().toLowerCase()!=="card"&&l,d=s.provider==="stripe"&&(s.paymentMethodCategory==="wallet"||s.paymentMethodCategory==="apm"),m=s.provider==="paypal"&&s.paymentMethodCategory==="wallet"&&s.paymentMethodType==="paypal";if(!c||!d&&!m)throw new h("Invalid non-card decline classification.","validation_error",{code:"InvalidSessionIntentDeclineRequest"});let u=m?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:i}:{provider:"stripe",paymentMethodCategory:s.paymentMethodCategory,paymentMethodType:s.paymentMethodType,providerDeclineReason:i},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(u),signal:o?.signal});if(!p.ok)throw await I(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 o=t?.page??1,s=t?.limit??1,i=new URLSearchParams({email:e,page:String(o),limit:String(s),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 h("Failed to fetch payments","api_error",{statusCode:a.status});let l=await a.json();return this.directTelemetry?.log({name:"operation.recovery.completed",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),this.directTelemetry?.performance({stage:"recovery",durationMs:Math.max(0,this.telemetryTimestamp()-r),durationMode:"machine",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),l}catch(a){throw this.reportDirectFailure(a,"RECOVERY_FAILED","recovery","other","saved"),a}}async createAndFetchSession(e){if(Ut(e))return(await this.createDetachedSession(e)).claimed;this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp(),r=R(e.timeoutMs??12e3),o={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});try{let s=await this.createAndFetchSessionRequest(e,t,r.signal,o);return this.adoptDirectTelemetryCheckout(s.data.session?.id),this.directTelemetry?.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:o.statusClass}),this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:"session_create",statusClass:o.statusClass,attempt:o.attempt}),s}catch(s){throw this.reportSessionCreateFailure(s,t,o),s}finally{r.clear()}}async createAndFetchSessionRequest(e,t,r,o){let s=e.products??Te(e.items,e.subscriptions);qe({captureMethod:e.captureMethod,products:s});let i=_e(e.currency,e.items,e.subscriptions,s);if(!i)throw new h("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});let a={clientId:e.clientId,checkoutVersion:N,successUrl:e.successUrl,cancelUrl:e.cancelUrl,currency:i,checkoutMode:e.checkoutMode??"full",products:s.map(u=>Be(u,i)),accountData:He(e.account),couponCodes:e.couponCodes??[]};e.captureMethod==="manual"&&(a.captureMethod=e.captureMethod),e.tokenizedData&&(a.tokenizedData=e.tokenizedData),$e(a,e);let c=await(await this.postCheckoutSessionCreate(a,e,t,r,o)).json();if(c.data&&"gateways"in c.data){this.autoCacheDisplayData(c.data.uuid,e);let u=this.mergeCachedDisplayData(c.data),p=this.normalizeRawSession(u);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 d=c.data?.uuid;if(!d)throw new h("No session ID returned","api_error",{code:"InvalidCheckoutSessionResponse"});return this.autoCacheDisplayData(d,e),this.adoptDirectTelemetryCheckout(d),{...await this.getUnifiedCheckoutSession(d),autoProcessingError:c.autoProcessingError,autoProcessingAttempted:c.autoProcessingAttempted,autoProcessingPending:c.autoProcessingPending}}async postCheckoutSessionCreate(e,t,r,o,s){let i={"Content-Type":"application/json",[ve]:N},a=Nt(t.idempotencyKey);a&&(i[Oe]=a);let l,c=!1,d=Yt(t),m=u=>{try{this.telemetryHooks?.onRetry?.("session_create",u),this.directTelemetry?.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:u})}catch{}};for(let u=0;u<3;u++){s.attempt=u;try{d?.onAttempt?.(u)}catch{}try{l=await fetch(`${this.baseUrl}/v1/checkouts/sessions?expand=true`,{method:"POST",headers:i,body:JSON.stringify(e),signal:o})}catch(v){if(s.statusClass=o.aborted||v instanceof Error&&v.name==="AbortError"?"timeout":"network_error",o.aborted||v instanceof Error&&v.name==="AbortError"||u>=2)throw v;let T=u+1;m(T),await L(u,o);continue}let p=A(l.status);if(s.statusClass=p,c||(c=!0,this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:p,attempt:u}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:Math.max(0,this.telemetryTimestamp()-r),durationMode:"machine",requestCategory:"session_create",statusClass:p,attempt:u})),l.status===204)throw new h("Session auto-completed \u2014 payment method already on file","api_error",{code:"session_auto_completed"});if(l.ok)break;let w=await I(l,"Failed to create checkout session");if(w.code===Ot&&u<2){m(u+1),await L(u,o);continue}throw w}if(!l)throw new TypeError("Checkout-session creation exhausted its retry budget.");return l}async createDetachedSession(e){this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp(),r=R(e.timeoutMs??12e3),o={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let s=e.products??Te(e.items,e.subscriptions);try{qe({captureMethod:e.captureMethod,products:s})}catch(p){throw r.clear(),this.reportSessionCreateFailure(p,t,o),p}let i=_e(e.currency,e.items,e.subscriptions,s);if(!i)throw r.clear(),this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),new h("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});let a;try{a=Qt(e,i,s)}catch(p){throw r.clear(),this.reportSessionCreateFailure(p,t,o),p}let l,c;try{if(c=await(await this.postCheckoutSessionCreate(Jt(e,i),e,t,r.signal,o)).json(),!c.data||!("gateways"in c.data))throw new h("The billing API returned no session shell for a detached create. It must support `deferDataAttachment` (TeamFloPay/backend#1099).","api_error",{code:"InvalidCheckoutSessionResponse"});l=this.normalizeRawSession(this.mergeCachedDisplayData(c.data)),c.vault&&l.data.session&&(l.data.session.vault=this.toVaultBlock(c.vault))}catch(p){throw r.clear(),this.reportSessionCreateFailure(p,t,o),p}let d=l.data.session?.id??c.data.uuid??"",m=l.data.session?.clientSecret??c.data.nonce??"";if(!d||!m){r.clear();let p=new h("Checkout session shell was created without a session id or nonce.","api_error",{code:"InvalidCheckoutSessionResponse"});throw this.reportSessionCreateFailure(p,t,o),p}this.adoptDirectTelemetryCheckout(d),this.directTelemetry?.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",statusClass:o.statusClass,paymentMethodCategory:"card"}),this.directTelemetry?.performance({stage:"session_shell",durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:"session_create",statusClass:o.statusClass,attempt:o.attempt,paymentMethodCategory:"card"});let u=this.claimCheckoutSession(d,m,a,{params:e,startedAt:t,deadline:r,createAttempt:o.attempt});return u.catch(()=>{}),{shell:l,sessionId:d,nonce:m,claimed:u}}async claimCheckoutSession(e,t,r,o){let s=o?.startedAt??this.telemetryTimestamp(),i=this.telemetryTimestamp(),a=o?.deadline??R(12e3),l=JSON.stringify(r),c="unknown",d=0;this.directTelemetry?.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"});try{let m;for(d=0;d<3;d++){try{m=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/claim`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":t,[ve]:N},body:l,signal:a.signal})}catch(w){let v=a.signal.aborted||w instanceof Error&&w.name==="AbortError";if(c=v?"timeout":"network_error",v||d>=2)throw w;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(m.status),m.ok)break;throw await I(m,"Failed to attach checkout session data")}if(!m)throw new TypeError("Checkout-session claim exhausted its retry budget.");let u=await m.json();if(!u.data||!u.data.gateways)throw new h("The billing API returned no checkout session with gateways after claiming it.","api_error",{code:"InvalidCheckoutSessionResponse"});o?.params&&this.autoCacheDisplayData(u.data.uuid??e,o.params);let p=this.normalizeRawSession(this.mergeCachedDisplayData(u.data));return u.vault&&p.data.session&&(p.data.session.vault=this.toVaultBlock(u.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()-s),durationMode:"machine",requestCategory:"session_create",statusClass:c,attempt:o?.createAttempt??d}),p}catch(m){throw this.reportSessionCreateFailure(m,s,{attempt:d,statusClass:c},"session_claim"),m}finally{a.clear()}}reportSessionCreateFailure(e,t,r,o="session_create"){if(!(e instanceof h&&e.code==="session_auto_completed"))try{this.telemetryHooks?.onSessionCreateFailure?.(e)}catch{}let s=G(e,"CHECKOUT_SESSION_CREATE_FAILED");if(this.directTelemetry?.performance({stage:o,durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:o==="session_claim"?"session_claim":"session_create",statusClass:s.statusClass,attempt:r.attempt}),e instanceof h&&e.type==="validation_error"||e instanceof h&&ze(e.statusCode)){this.directTelemetry?.terminal({outcome:"validation_rejected",stage:o,requestCategory:o==="session_claim"?"session_claim":"session_create",...e.type==="validation_error"?{}:{statusClass:"4xx"}});return}e instanceof h&&e.code==="session_auto_completed"||this.directTelemetry?.error({...s,stage:o,requestCategory:o==="session_claim"?"session_claim":"session_create"})}async waitForCheckoutSessionCompletion(e,t){this.beginDirectTelemetryCheckout(e);let r=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:"saved"});let o=t?.timeoutMs??zt,s=Date.now()+o,i=this.clampRetryAfterMs(t?.initialDelayMs??Ne),a=0;try{for(;;){let l=s-Date.now();if(l<=0)throw ie();if(i>0){try{a+=1,this.telemetryHooks?.onRetry?.("session_read",a),this.directTelemetry?.log({name:"operation.retry",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:"saved",attempt:a})}catch{}if(await je(Math.min(i,l)),Date.now()>=s)throw ie()}let c=await this.getUnifiedCheckoutSession(e,t?.nonce),d=c.data.session?.status;if(d==="authorized"||d==="complete"||d==="expired")return this.directTelemetry?.log({name:"operation.recovery.completed",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:"saved"}),this.directTelemetry?.performance({stage:"recovery",durationMs:Math.max(0,this.telemetryTimestamp()-r),durationMode:"machine",requestCategory:"session_read",paymentMethodCategory:"saved"}),c;if(Date.now()>=s)throw ie();i=this.clampRetryAfterMs(Math.max(i*2,Vt))}}catch(l){throw l instanceof h&&l.code==="checkout_processing_timeout"&&this.reportDirectFailure(l,"RECOVERY_FAILED","recovery","session_read","saved"),l}}normalizeRawSession(e){let t=e.gateways??{},r=[],o={session:this.toCheckoutSession(e)},s=t.stripe;if(s?.publishableKey){r.push("stripe");let l=[e.stripeClientSecret,s.stripeClientSecret].find(c=>typeof c=="string"&&c.length>0);o.stripe={clientSecret:l??"",publishableKey:s.publishableKey??void 0,paypalPublishableKey:s.paypalPublishableKey??void 0,environment:s.environment,enabledPaymentMethods:Array.isArray(s.enabledPaymentMethods)?s.enabledPaymentMethods.filter(c=>typeof c=="string"):void 0}}let i=t.paypal;return i?.publishableKey&&(r.push("paypal"),o.paypal={publishableKey:i.publishableKey,environment:i.environment}),{providers:r,mode:"tokenize",data:o,raw:{data:e}}}toCheckoutSession(e){let t=e.products??[],r=typeof e.totalAmount=="number"&&Number.isFinite(e.totalAmount),o=t.reduce((c,d)=>c+(d.overrideAmount??d.totalAmount??0),0),s=r?e.totalAmount:o,i=Math.round(s*100),a=e.currency??t[0]?.currency??"USD",l=e.checkoutMode==="setup"?"setup":t.some(c=>c.type==="subscription")?"subscription":"payment";return{id:e.uuid,clientSecret:e.nonce,mode:l,status:this.toCheckoutSessionStatus(e.status),amount:i,currency:a,captureMethod:e.captureMethod,paymentId:e.paymentId,authorizationExpiresAt:e.authorizationExpiresAt,failureOutcome:Le(e.outcome)??Le(e.failureReason)??(e.status==="expired"&&e.captureMethod==="manual"?"authorization_expired":void 0),customer:{id:e.accountData.userId,email:e.accountData.email,firstName:e.accountData.firstName,lastName:e.accountData.lastName,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},metadata:{},checkoutMode:e.checkoutMode,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 o=await e.json().catch(()=>null),s=this.toCheckoutProcessingPending(o,e,t),i=await this.waitForCheckoutSessionCompletion(s.sessionId,{initialDelayMs:s.retryAfterMs,timeoutMs:r?.pollTimeoutMs,nonce:r?.nonce});if(i.data.session?.status==="complete")return new Response(null,{status:204,statusText:"No Content"});if(i.data.session?.status==="authorized"){let a=i.data.session;return new Response(JSON.stringify({status:"authorized",paymentId:a.paymentId,sessionId:a.id||t,authorizationExpiresAt:a.authorizationExpiresAt}),{status:200,headers:{"Content-Type":"application/json"}})}if(i.data.session?.status==="expired"){let a=i.data.session.failureOutcome==="authorization_expired"||i.data.session.captureMethod==="manual";throw new h(a?"Authorization has expired.":"Checkout session has expired.","api_error",{code:a?"authorization_expired":"checkout_session_expired"})}throw ie()}toCheckoutProcessingPending(e,t,r){let o=t.headers.get("Retry-After"),s=o===null||o.trim()===""?void 0:Number(o),i=s!==void 0&&Number.isFinite(s)?s*1e3:void 0;return{type:"checkout_processing",sessionId:V(e,"sessionId")??r,retryAfterMs:this.clampRetryAfterMs($t(e,"retryAfterMs")??i??Ne),statusUrl:V(e,"statusUrl"),sessionUrl:V(e,"sessionUrl")}}clampRetryAfterMs(e){return Math.max(0,Math.min(e,Bt))}autoCacheDisplayData(e,t){if(!e)return;let r=t.products??Te(t.items,t.subscriptions);if(r.length===0&&!t.currency)return;let o=t.products!==void 0,s=_e(t.currency,o?void 0:t.items,o?void 0:t.subscriptions,r);q(e,{currency:s??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??s??void 0}))})}mergeCachedDisplayData(e){let t=he(e.uuid),r=new Map,o=i=>i?`code:${i}`:void 0;for(let i of t?.products??[]){let a=o(i.code);a&&r.set(a,i)}let s=(e.products??[]).map(i=>{let a=o(i.code),l=a?r.get(a):void 0;return{...i,name:i.name??l?.name??null,totalAmount:i.totalAmount??l?.totalAmount,overrideAmount:i.overrideAmount??l?.overrideAmount,currency:i.currency??l?.currency}});return{...e,currency:e.currency??t?.currency,products:s}}};x.activeVaultCaptureRequests=new Map;var D=x;function Ge(n,e){let t=D;return new t(n,e)}function Ye(n){return{payment:"payment",address:"address"}[n]}function le(n){switch(n){case"night":return"night";case"flat":return"flat";default:return"stripe"}}function tr(n){return{...n,theme:le(n.theme)}}function Se(n){return n?JSON.stringify(n.map(e=>e.trim().toLowerCase())):null}function We(n){let e=n;return{mount(t){e.mount(t)},unmount(){e.unmount()},update(t){e.update(t)},on(t,r){e.on?.(t,r)},off(t,r){e.off?.(t,r)},destroy(){e.destroy()}}}function rr(n){return{billing_details:{...n.email?{email:n.email}:{},...n.name?{name:n.name}:{},...n.address?{address:{...n.address.country?{country:n.address.country}:{},...n.address.postal_code?{postal_code:n.address.postal_code}:{},...n.address.city?{city:n.address.city}:{},...n.address.line1?{line1:n.address.line1}:{},...n.address.line2?{line2:n.address.line2}:{},...n.address.state?{state:n.address.state}:{}}}:{}}}}var Y=class{constructor(){this.name="stripe";this.stripe=null;this.elements=null;this.appliedAppearanceKey=null;this.appliedPaymentMethodTypesKey=null;this.appliedClientSecret=null;this.verifiedClientSecret=null;this.verifiedPaymentMethodTypesKey=null}async initialize(e){if(typeof window>"u")return;let t=await Xt(e.publishableKey,{locale:e.locale??"auto"});if(!t)throw new g("Failed to initialize Stripe. Check your publishable key.","authentication_error");this.stripe=t}getElements(e){if(!this.stripe)throw new g("StripeAdapter not initialized. Call initialize() first.","api_error");let t=e?.appearance?{theme:le(e.appearance.theme),variables:e.appearance.variables,rules:e.appearance.rules}:void 0,r=t?JSON.stringify(t):null,o=Se(e?.paymentMethodTypes),s=e?.clientSecret??null;if(this.elements&&o&&(o!==this.appliedPaymentMethodTypesKey||s!==this.appliedClientSecret)&&(this.elements=null,this.appliedAppearanceKey=null,this.appliedPaymentMethodTypesKey=null,this.appliedClientSecret=null,this.verifiedClientSecret=null,this.verifiedPaymentMethodTypesKey=null),this.elements)r!==this.appliedAppearanceKey&&(this.elements.update({appearance:t??{}}),this.appliedAppearanceKey=r);else{let i,a=e?.amount??0,l=(e?.currency??"usd").toLowerCase(),c=e?.paymentMethodCreation??"manual";e?.clientSecret?i={clientSecret:e.clientSecret}:a>0?(i={mode:"payment",amount:a,currency:l,paymentMethodCreation:c},e?.setupFutureUsage&&(i.setupFutureUsage=e.setupFutureUsage)):i={mode:"setup",currency:l,paymentMethodCreation:c},!e?.clientSecret&&e?.paymentMethodTypes&&(i.paymentMethodTypes=e.paymentMethodTypes),t&&(i.appearance=t),this.elements=this.stripe.elements(i),this.appliedAppearanceKey=r,this.appliedPaymentMethodTypesKey=o,this.appliedClientSecret=s,this.verifiedClientSecret=null,this.verifiedPaymentMethodTypesKey=null}return this.elements}async assertClientSecretPaymentMethods(e,t){if(!this.stripe)throw new g("StripeAdapter not initialized. Call initialize() first.","api_error");let r,o=!1;if(er(e)){let{setupIntent:l,error:c}=await this.stripe.retrieveSetupIntent(e);r=l,o=!!c}else{let{paymentIntent:l,error:c}=await this.stripe.retrievePaymentIntent(e);r=l,o=!!c}let s=r?.payment_method_types;if(o||!Array.isArray(s))throw new g("Unable to verify the payment methods configured for this client secret.","api_error",{param:"clientSecret"});let i=new Set(t.map(l=>l.toLowerCase()));if(s.some(l=>typeof l!="string"||!i.has(l.trim().toLowerCase()))||s.length===0)throw new g("The client-secret intent must enable only declared non-card payment methods.","validation_error",{param:"clientSecret"})}async createElement(e,t){let r=t;if(e==="payment"){let l=t.paymentMethodTypes?.map(c=>c.trim()).filter(c=>c&&c.toLowerCase()!=="card");if(!l?.length)throw new g("At least one supported non-card payment method is required.","validation_error",{param:"paymentMethodTypes"});if(r={...t,paymentMethodTypes:l},r.clientSecret){let c=Se(l);this.elements&&this.appliedClientSecret===r.clientSecret&&this.appliedPaymentMethodTypesKey===c&&this.verifiedClientSecret===r.clientSecret&&this.verifiedPaymentMethodTypesKey===c||await this.assertClientSecretPaymentMethods(r.clientSecret,l)}}let o=this.getElements(r);e==="payment"&&r.clientSecret&&(this.verifiedClientSecret=r.clientSecret,this.verifiedPaymentMethodTypesKey=Se(r.paymentMethodTypes));let s=Ye(e),i={};r.layout&&(i.layout=r.layout),r.defaultValues&&(i.defaultValues=r.defaultValues),r.readOnly&&(i.readOnly=r.readOnly),r.mode&&(i.mode=r.mode);let a=o.create(s,i);return We(a)}getElement(e){if(!this.elements)return null;let t=Ye(e),r=this.elements.getElement(t);return r?We(r):null}async submitElements(){if(!this.stripe||!this.elements)return{error:new g("Stripe not initialized","api_error")};let{error:e}=await this.elements.submit();return e?{error:new g(e.message??"Validation failed","validation_error")}:{}}async confirmPayment(e){if(!this.stripe||!this.elements)throw new g("StripeAdapter not initialized or no elements created.","api_error");let t=e.billingDetails,r=t?rr(t):void 0,{error:o,paymentIntent:s}=await this.stripe.confirmPayment({elements:this.elements,clientSecret:e.clientSecret,confirmParams:{return_url:e.returnUrl??window.location.href,...r?{payment_method_data:r}:{}},redirect:"if_required"});return o?{status:"failed",error:new g(o.message??"Payment failed","api_error",{code:o.code,declineCode:o.decline_code})}:s?{status:{succeeded:"succeeded",processing:"processing",requires_action:"requires_action",requires_payment_method:"failed",canceled:"failed"}[s.status]??"failed",paymentIntentId:s.id,paymentMethodId:this.extractPaymentMethodId(s.payment_method)}:{status:"failed",error:new g("No payment intent returned","api_error")}}extractPaymentMethodId(e){if(typeof e=="string"&&e.startsWith("pm_"))return e;if(e&&typeof e=="object"&&typeof e.id=="string")return e.id}async confirmPayPalPayment(e){if(!this.stripe)return{status:"failed",error:new g("Stripe not initialized","api_error")};let t=e.billingApiUrl.replace(/\/+$/,"");if(this.elements){let{error:s}=await this.elements.submit();if(s)return{status:"failed",error:new g(s.message??"PayPal payment failed","validation_error",{code:s.code})}}let r;try{let s=await new D(t).createSessionIntent(e.sessionId,e.nonce??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"});if(s.provider!=="stripe")throw new g("Invalid provider returned for PayPal intent","api_error");r=s.clientSecret}catch(s){return{status:"failed",error:s instanceof g?s:new g("Failed to create PayPal payment intent","api_error")}}let{error:o}=await this.stripe.confirmPayment({clientSecret:r,elements:this.elements??void 0,confirmParams:{return_url:e.returnUrl}});if(o){if(e.nonce)try{await new D(t).reportSessionIntentDecline(e.sessionId,e.nonce,{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:o.code??"provider_declined"})}catch{}return{status:"failed",error:new g(o.message??"PayPal payment failed","api_error",{code:o.code})}}return{status:"processing"}}async resumePayPalPayment(){if(!this.stripe||typeof window>"u")return null;let e=new URLSearchParams(window.location.search),t=e.get("payment_intent"),r=e.get("payment_intent_client_secret"),o=e.get("redirect_status");if(!t||!r)return null;if(o==="failed")return{status:"failed",error:new g("PayPal payment was declined. Please try again.","api_error")};let{paymentIntent:s,error:i}=await this.stripe.retrievePaymentIntent(r);if(i)return{status:"failed",error:new g(i.message??"Failed to retrieve PayPal payment","api_error")};if(s&&Zt(s.status)){let a=typeof s.payment_method=="string"?s.payment_method:s.payment_method?.id,l=new URL(window.location.href);return l.searchParams.delete("payment_intent"),l.searchParams.delete("payment_intent_client_secret"),l.searchParams.delete("redirect_status"),window.history.replaceState({},"",l.toString()),{status:s.status,paymentIntentId:s.id,paymentMethodId:a}}return{status:"failed",error:new g("PayPal payment was not completed. Please try again.","api_error")}}getRawProvider(){return this.stripe}createPayPalElements(e){if(!this.stripe)return null;let t={mode:"payment",amount:e.amount??0,currency:(e.currency??"usd").toLowerCase(),captureMethod:"manual"};return e.setupFutureUsage&&(t.setupFutureUsage=e.setupFutureUsage),e.appearance&&(t.appearance={theme:le(e.appearance.theme),variables:e.appearance.variables,rules:e.appearance.rules}),this.stripe.elements(t)}destroy(){this.elements=null,this.appliedAppearanceKey=null,this.appliedPaymentMethodTypesKey=null,this.appliedClientSecret=null,this.verifiedClientSecret=null,this.verifiedPaymentMethodTypesKey=null,this.stripe=null}};import{FloPayError as S,classifyTelemetryFailure as Me,resolveBillingApiUrl as at,SDK_VERSION as ur}from"@flopay/shared";import{FloPayError as nr}from"@flopay/shared";var W=class{constructor(e,t){this.elementMap=new Map;this.provider=e,this.baseOptions=t??{}}async create(e,t){let r={...this.baseOptions,...t};if(e==="payment"){let a=r.paymentMethodTypes?.map(l=>l.trim()).filter(l=>l&&l.toLowerCase()!=="card");if(!a?.length)throw new nr("At least one supported non-card payment method is required.","validation_error",{param:"paymentMethodTypes"});r.paymentMethodTypes=a}let o=this.provider.getElement(e);if(o)return this.elementMap.set(e,o),o;let s=this.elementMap.get(e);s&&s.destroy();let i=await this.provider.createElement(e,r);return this.elementMap.set(e,i),i}getElement(e){return this.elementMap.get(e)??null}async submit(){return{}}destroy(){for(let e of this.elementMap.values())e.destroy();this.elementMap.clear()}};import{buildTelemetryErrorEvent as or,buildTelemetryLogEvent as sr,buildTelemetryTerminalEvent as Ze,FloPayError as Je,resolveBillingApiUrl as Qe,SDK_VERSION as Xe}from"@flopay/shared";var be="flopay-vault",et={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 J(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:n.class==="lifecycle"?n.name:n.class==="technical_error"?n.code:n.class==="expected_outcome"?n.outcome:"sdk.performance",data:e})}catch{}}function ce(n,e){return sr({eventId:"11111111-1111-4111-8111-111111111111",name:n,stage:e,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}function tt(n){return n?{errorCode:"VAULT_SUBMIT_FAILED",stage:"vault_submit",failureCategory:"provider_runtime"}:{errorCode:"VAULT_LOAD_FAILED",stage:"vault_mount",failureCategory:"provider_runtime"}}function rt(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 ir(n,e,t,r="checkout"){let{type:o}=n;if(o==="complete"||o==="decline")return Ze({eventId:"22222222-2222-4222-8222-222222222222",outcome:rt(n,t,r),sequence:0,provider:"pcivault",paymentMethodCategory:"card"});if(o==="error"){let a=tt(e);return or({eventId:"33333333-3333-4333-8333-333333333333",...a,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}let[s,i]=et[o];return ce(s,i)}function ar(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===be&&(e.type==="ready"||e.type==="submitting"||e.type==="blocked"||e.type==="complete"||e.type==="decline"||e.type==="error"||e.type==="action_required")}function lr(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 cr(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===be&&e.type==="validation"&&Array.isArray(e.messages)}function dr(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===be&&e.type==="resize"&&typeof e.height=="number"&&Number.isFinite(e.height)}var z=class{constructor(e={},t){this.provider="pcivault";this.container=null;this.messageHandler=null;this.actionOverlay=null;this.threeDsReturnHandler=null;this.messageToken=null;this.expectedOrigin=null;this.theme=null;this.submitGateBlocked=!1;this.cardFieldOrder=null;this.cardAutoFocus=!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 C({billingApiUrl:Qe(),sdkVersion:Xe}):void 0)}async mount(e,t){this.ownsTelemetryReporter&&!this.telemetryReporter&&(this.telemetryReporter=new C({billingApiUrl:Qe(),sdkVersion:Xe}));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 Je("The vault card form is only available in the browser.","api_error",{code:"card_capture_no_window"});if(!t?.html||!t.html.trim())throw this.reportVaultLoadFailure(),new Je("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??null;try{this.attachMessageListener(),this.injectWidget(e,t.html)}catch(o){throw this.reportVaultLoadFailure(),o}this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),J(ce("vault.widget.mounted","vault_mount")),this.telemetryReporter?.log({name:"vault.widget.mounted",stage:"vault_mount",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 o of r){let s=document.createElement("script");for(let i of Array.from(o.attributes))s.setAttribute(i.name,i.value);s.text=o.text,o.replaceWith(s)}}attachMessageListener(){if(this.messageHandler)return;let e=t=>{if(this.expectedOrigin&&t.origin!==this.expectedOrigin)return;let r=t.data;if(dr(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;this.applyHeight(r.height);return}if(cr(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;let l=r.messages.filter(c=>typeof c=="string"&&c.trim()).join(" ");this.emit("validation",{sessionId:this.config.sessionId,message:l||void 0});return}if(!ar(r)||this.messageToken&&r.messageToken!==this.messageToken)return;let o=this.config.sessionId,s=typeof r.sessionId=="string"?r.sessionId:void 0;if(o&&s&&s!==o||(r.type==="complete"||r.type==="decline")&&o&&s!==o)return;let i=lr(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?.()??_()),J(ir(r,this.submissionStarted,this.config.captureMethod,this.config.operation)),this.reportOutcome(r),r.type==="ready"&&(this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder()),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"})),r==="complete"||r==="decline"){t.log({name:"vault.terminal",stage:"completion",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:rt(e,this.config.captureMethod,this.config.operation),provider:"pcivault",paymentMethodCategory:"card"});return}if(r==="error"){let i=tt(this.submissionStarted);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[o,s]=et[r];t.log({name:o,stage:s,provider:"pcivault",paymentMethodCategory:"card"})}applyTheme(e){this.theme=e,this.postTheme()}postTheme(){if(!this.theme||!this.container)return;let t=this.container.querySelector("iframe")?.contentWindow;if(t)try{t.postMessage({source:"flopay-vault-host",type:"theme",theme:this.theme},"*")}catch{}}setSubmitGate(e){this.submitGateBlocked=e,this.postSubmitGate()}postSubmitGate(){if(!this.container)return;let t=this.container.querySelector("iframe")?.contentWindow;if(t)try{t.postMessage({source:"flopay-vault-host",type:"gate",blocked:this.submitGateBlocked},"*")}catch{}}setCardFieldOrder(e,t){this.cardFieldOrder=e,this.cardAutoFocus=t,this.postCardFieldOrder()}postCardFieldOrder(){if(!this.container)return;let t=this.container.querySelector("iframe")?.contentWindow;if(t)try{t.postMessage({source:"flopay-vault-host",type:"fieldOrder",order:this.cardFieldOrder,autoFocus:this.cardAutoFocus},"*")}catch{}}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);return}let t=document.createElement("div");t.setAttribute("data-flopay-action-required","1"),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.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 o=document.createElement("button");o.type="button",o.setAttribute("aria-label","Close card authentication"),o.textContent="\xD7",o.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(";"),o.addEventListener("click",()=>this.abandonActionRequiredOverlay()),t.appendChild(o),t.addEventListener("click",i=>{i.target===t&&this.abandonActionRequiredOverlay()});let s=i=>{if(i.source!==r.contentWindow)return;let a=i.data;if(!a||typeof a!="object")return;let l=a;l.source==="flopay-vault-3ds-return"&&(J(ce("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(),this.postActionCompleted(l.status))};window.addEventListener("message",s),this.threeDsReturnHandler=s,document.body.appendChild(t),this.actionOverlay=t,J(ce("vault.three_ds.handoff","three_ds_handoff"))}postActionCompleted(e){if(!this.container)return;let r=this.container.querySelector("iframe")?.contentWindow;if(r)try{r.postMessage({source:"flopay-vault-host",type:"action_completed",status:typeof e=="string"?e:"unknown"},"*")}catch{}}abandonActionRequiredOverlay(){if(!this.actionOverlay)return;let e=Ze({eventId:"77777777-7777-4777-8777-777777777777",outcome:"customer_abandoned",stage:"three_ds_handoff",sequence:0,provider:"pcivault",paymentMethodCategory:"card"});J(e),this.telemetryReporter?.terminal({outcome:"customer_abandoned",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"}),this.hideActionRequiredOverlay(),this.postActionCompleted("abandoned")}hideActionRequiredOverlay(){this.threeDsReturnHandler&&(window.removeEventListener("message",this.threeDsReturnHandler),this.threeDsReturnHandler=null),this.actionOverlay&&(this.actionOverlay.parentNode?.removeChild(this.actionOverlay),this.actionOverlay=null)}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 nt(n,e){let t=z;return new t(n,{reporter:e})}var ot=Symbol.for("@flopay/js.telemetry.bridge.v1");function st(n,e,t){let r=()=>e?.now()??t();Object.defineProperty(n,ot,{configurable:!1,enumerable:!1,writable:!1,value:{error:s=>e?.error(s),log:s=>e?.log(s),performance:s=>e?.performance(s),terminal:s=>e?.terminal(s),now:r,elapsed:s=>Math.max(0,r()-s),setCheckoutContext:s=>e?.setCheckoutContext(s),beginCheckout:(s={})=>e?.beginCheckout(s)??r(),disable:()=>e?.disable()}})}function it(n){return n[ot]}function B(n){if(!n)return!1;let e=n.code?.toLowerCase()??"";return!!n.declineCode||e.includes("declin")}function pr(n){return n==="stripe"||n==="paypal"||n==="pcivault"?n:"other"}var de=class{constructor(e,t,r){this.currentElements=null;this.provider=e,this.config=t,this.telemetryReporter=r??new C({billingApiUrl:at(t.billingApiUrl),sdkVersion:ur,enabled:t.telemetry!==!1}),st(this,this.telemetryReporter,_)}now(){return this.telemetryReporter?.now?.()??_()}elements(e){return this.currentElements&&this.currentElements.destroy(),this.currentElements=new W(this.provider,{appearance:this.config.appearance,...e}),this.currentElements}async submitElements(){return this.provider.submitElements()}cardCapture(e){return this.telemetryReporter?.log({name:"vault.capture.requested",stage:"vault_request",provider:"pcivault",paymentMethodCategory:"card"}),this.telemetryReporter?nt({sessionId:e?.sessionId,captureMethod:e?.captureMethod},this.telemetryReporter):new z({sessionId:e?.sessionId,captureMethod:e?.captureMethod,telemetry:!1})}async confirmPayPalPayment(e){let t=this.now();this.telemetryReporter?.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),this.telemetryReporter?.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});try{let r=await this.provider.confirmPayPalPayment(e);return this.telemetryReporter?.performance({stage:"processing",durationMs:this.now()-t,durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),r.error||this.telemetryReporter?.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),r.status==="requires_action"?(this.telemetryReporter?.log({name:"provider.redirect.started",stage:"redirect",provider:"paypal",paymentMethodCategory:"paypal"}),this.telemetryReporter?.terminal({outcome:"action_required",stage:"redirect",provider:"paypal",paymentMethodCategory:"paypal"})):r.status==="succeeded"?this.telemetryReporter?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}):r.status!=="processing"&&(B(r.error)?this.telemetryReporter?.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):r.error?.type==="validation_error"?this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal"}):r.error&&this.telemetryReporter?.error({errorCode:"PAYMENT_PROCESSING_FAILED",failureCategory:"provider_runtime",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"})),r}catch(r){if(this.telemetryReporter?.performance({stage:"processing",durationMs:this.now()-t,durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),r instanceof S&&B(r))this.telemetryReporter?.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"});else if(r instanceof S&&r.type==="validation_error")this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal"});else{let o=Me(r,"PAYMENT_PROCESSING_FAILED","unknown");this.telemetryReporter?.error({...o,failureCategory:o.failureCategory??"provider_runtime",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"})}throw r}}async resumePayPalPayment(){let e=this.now();try{let t=await this.provider.resumePayPalPayment();return t===null?null:(this.telemetryReporter?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),this.telemetryReporter?.performance({stage:"redirect_resume",durationMs:this.now()-e,durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),t.status==="succeeded"?this.telemetryReporter?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}):B(t.error)?this.telemetryReporter?.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):t.error?.type==="validation_error"?this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal"}):t.error&&this.telemetryReporter?.error({errorCode:"REDIRECT_RESUME_FAILED",failureCategory:"provider_runtime",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),t)}catch(t){if(this.telemetryReporter?.performance({stage:"redirect_resume",durationMs:this.now()-e,durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),t instanceof S&&B(t))this.telemetryReporter?.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"});else if(t instanceof S&&t.type==="validation_error")this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal"});else{let r=Me(t,"REDIRECT_RESUME_FAILED","unknown");this.telemetryReporter?.error({...r,failureCategory:r.failureCategory??"provider_runtime",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"})}throw t}}async confirmPayment(e){if(e.paymentMethodCategory!=="wallet"&&e.paymentMethodCategory!=="apm"||!e.paymentMethodType?.trim()||e.paymentMethodType.trim().toLowerCase()==="card")throw new S("A supported non-card payment method is required.","validation_error",{param:"paymentMethodType"});let t=this.now(),r=pr(this.provider.name);this.telemetryReporter?.log({name:"payment.processing.started",stage:"processing",provider:r,paymentMethodCategory:e.paymentMethodCategory});try{let o=await this.provider.confirmPayment(e),s=this.now()-t;return this.telemetryReporter?.performance({stage:"processing",durationMs:s,durationMode:"machine",provider:r,paymentMethodCategory:e.paymentMethodCategory}),o.status==="succeeded"?this.telemetryReporter?.terminal({outcome:"payment_succeeded",provider:r,paymentMethodCategory:e.paymentMethodCategory}):B(o.error)?this.telemetryReporter?.terminal({outcome:"payment_declined",provider:r,paymentMethodCategory:e.paymentMethodCategory}):o.error?.type==="validation_error"?this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:r,paymentMethodCategory:e.paymentMethodCategory}):o.status==="requires_action"?this.telemetryReporter?.terminal({outcome:"action_required",stage:"three_ds_handoff",provider:r,paymentMethodCategory:e.paymentMethodCategory}):o.status==="failed"&&o.error&&this.telemetryReporter?.error({errorCode:"PAYMENT_PROCESSING_FAILED",failureCategory:"provider_runtime",stage:"processing",provider:r,paymentMethodCategory:e.paymentMethodCategory}),o.status==="succeeded"||o.status==="failed"?this.telemetryReporter?.log({name:"payment.processing.completed",stage:"processing",provider:r,paymentMethodCategory:e.paymentMethodCategory}):this.telemetryReporter?.log({name:"operation.state_transition",stage:o.status==="requires_action"?"three_ds_handoff":"processing",provider:r,paymentMethodCategory:e.paymentMethodCategory}),o}catch(o){throw this.telemetryReporter?.performance({stage:"processing",durationMs:this.now()-t,durationMode:"machine",provider:r,paymentMethodCategory:e.paymentMethodCategory}),o instanceof S&&B(o)?this.telemetryReporter?.terminal({outcome:"payment_declined",provider:r,paymentMethodCategory:e.paymentMethodCategory}):o instanceof S&&o.type==="validation_error"?this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:r,paymentMethodCategory:e.paymentMethodCategory}):this.telemetryReporter?.error({errorCode:"PAYMENT_PROCESSING_FAILED",failureCategory:"provider_runtime",stage:"processing",provider:r,paymentMethodCategory:e.paymentMethodCategory}),o}}async retrieveSession(e,t){if(!e)throw new S("sessionId is required to retrieve a session.","validation_error",{param:"sessionId"});let r=await this.retrieveUnifiedSession(e,t);if(!r.data.session)throw new S("Session not found","api_error");return r.data.session}async retrieveUnifiedSession(e,t){if(!e)throw new S("sessionId is required.","validation_error",{param:"sessionId"});let r=at(t??this.config.billingApiUrl),o=this.now();this.telemetryReporter?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let s,i=Ge(r,{now:()=>this.telemetryReporter?.now()??_(),onFirstByte:a=>{s=a},onRetry:(a,l)=>{this.telemetryReporter?.log({name:"operation.retry",stage:a==="session_read"?"session_read":"processing",requestCategory:a,attempt:l})}});try{let a=await i.getUnifiedCheckoutSession(e);return s!==void 0&&(this.telemetryReporter?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:"2xx"}),this.telemetryReporter?.performance({stage:"session_first_byte",durationMs:s,durationMode:"machine",requestCategory:"session_read",statusClass:"2xx"})),this.telemetryReporter?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:"2xx"}),this.telemetryReporter?.log({name:"checkout.data.ready",stage:"checkout_data_ready"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-o,durationMode:"machine",requestCategory:"session_read",statusClass:"2xx"}),a}catch(a){let l=Me(a,a instanceof S&&a.code==="checkout_processing_timeout"?"REQUEST_TIMEOUT":"NETWORK_REQUEST_FAILED");throw this.telemetryReporter?.error({...l,stage:"session_read",provider:"flo",paymentMethodCategory:"unknown"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-o,durationMode:"machine",requestCategory:"session_read",statusClass:l.statusClass}),a}}getRawProvider(){return this.provider.getRawProvider()}destroy(){this.telemetryReporter?.log({name:"checkout.unmount",stage:"unmount"}),this.telemetryReporter?.destroy(),this.currentElements?.destroy(),this.currentElements=null,this.provider.destroy()}};function lt(n,e,t){let r=de;return new r(n,e,t)}var dt=new Map;function Pe(n){return Array.isArray(n)?n.map(Pe):n&&typeof n=="object"?Object.fromEntries(Object.entries(n).filter(([,e])=>e!==void 0).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,Pe(t)])):n}function yr(n,e){return JSON.stringify([n,ke(e?.billingApiUrl),e?.telemetry!==!1,e?.locale??"auto",e?.apiVersion??null,Pe(e?.appearance??null)])}var ue=new Map;async function hr(n,e){if(!n){let a=new C({billingApiUrl:ke(e?.billingApiUrl),sdkVersion:ct,enabled:e?.telemetry!==!1});throw a.error({errorCode:"CONFIGURATION_INVALID",stage:"sdk_initialize",paymentMethodCategory:"unknown"}),a.flush().catch(()=>{}).finally(()=>a.destroy()),new mr("A publishable key is required to initialize FloPay.","validation_error",{param:"publishableKey"})}let t=yr(n,e),r=dt.get(t);if(r)return e?.telemetry!==!1&&it(r)?.log({name:"sdk.cache.hit",stage:"sdk_initialize"}),r;let o=ue.get(t);if(o)return o;let s={...e,publishableKey:n},i=(async()=>{let a=new C({billingApiUrl:ke(s.billingApiUrl),sdkVersion:ct,enabled:s.telemetry!==!1}),l=a.now();a.log({name:"sdk.initialize.started",stage:"sdk_initialize"}),a.log({name:"sdk.cache.miss",stage:"sdk_initialize"}),a.log({name:"provider.load.started",stage:"provider_load",provider:"stripe"});let c=new Y,d=a.now();try{await c.initialize(s)}catch(p){throw a.error({errorCode:"SDK_INITIALIZATION_FAILED",failureCategory:"provider_runtime",stage:"sdk_initialize",provider:"stripe",paymentMethodCategory:"unknown"}),a.destroy(),p}let m=a.now();a.log({name:"provider.ready",stage:"provider_ready",provider:"stripe"}),a.log({name:"provider.availability.checked",stage:"provider_ready",provider:"stripe"}),a.log({name:"sdk.initialize.ready",stage:"sdk_initialize"}),a.performance({stage:"sdk_initialize",durationMs:m-l,durationMode:"machine",provider:"stripe"}),a.performance({stage:"provider_ready",durationMs:m-d,durationMode:"machine",provider:"stripe"});let u=lt(c,s,a);return dt.set(t,u),u})();ue.set(t,i);try{return await i}finally{ue.get(t)===i&&ue.delete(t)}}import{FloPayError as K,IDEMPOTENCY_IN_PROGRESS_CODE as gr,IDEMPOTENCY_KEY_HEADER as fr,SDK_VERSION as ut,assertCaptureMethodEligible as Cr,buildProductPayload as vr,classifyTelemetryFailure as Tr,foldIntoProducts as _r,resolveIdempotencyKey as pt,resolveSessionCurrency as wr,telemetryStatusClass as mt}from"@flopay/shared";var Ee=5,yt=new WeakSet;function Sr(n){(typeof n=="object"&&n!==null||typeof n=="function")&&yt.add(n)}function br(n){return(typeof n=="object"&&n!==null||typeof n=="function")&&yt.has(n)}function Mr(n,e){let t=e?.error,r=E(e?.code)??E(t?.code)??`http_${n}`,o=E(e?.message)??E(t?.message)??kr(r,n);return new K(o,"api_error",{code:r,statusCode:n})}function kr(n,e){switch(n){case"CouponLimitExceeded":return`Too many coupon codes \u2014 a checkout session accepts at most ${Ee}.`;case"CouponCurrencyUnsupported":return"One of the applied coupons has no price configured for the cart currency.";default:return`Failed to create checkout session (HTTP ${e}).`}}async function ht(n,e,t){let{billingApiUrl:r,checkoutBaseUrl:o,items:s=[],subscriptions:i=[],products:a,account:l,successUrl:c,cancelUrl:d,checkoutMode:m="confirm",captureMethod:u,couponCodes:p=[],tagsData:w,redirectParams:v={},setCookie:T=!0,clientId:Re,currency:H,utmMetadata:y,idempotencyKey:Q}=n,X=pt(Q);if(p.length>Ee)throw new K(`Too many coupon codes \u2014 a checkout session accepts at most ${Ee}.`,"validation_error",{code:"CouponLimitExceeded",param:"couponCodes"});let P=a??_r(s,i);Cr({captureMethod:u,products:P});let M=wr(H,s,i,P);if(!M)throw new K("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 F={clientId:Re,checkoutVersion:ut,successUrl:c,cancelUrl:d,currency:M,checkoutMode:m,products:P.map(k=>vr(k,M)),accountData:{userId:l.userId,firstName:l.firstName??null,lastName:l.lastName??null,email:l.email,country:l.country??null,gender:l.gender??null,city:l.city??null,state:l.state??null,zip:l.zip??null,addressLine1:l.addressLine1??null,addressLine2:l.addressLine2??null},couponCodes:p};u==="manual"&&(F.captureMethod=u),w&&(F.tagsData=w),y?.length&&(F.utmMetadata=y);let $=`${r.replace(/\/+$/,"")}/v1/checkouts/sessions`,Z={"Content-Type":"application/json"};X&&(Z[fr]=X);let O,ee,vt={method:"POST",headers:Z,body:JSON.stringify(F),signal:e},te;try{te=await fetch($,vt)}catch(k){throw Sr(k),k}try{t?.(te.status)}catch{}O=te.status;try{ee=await te.json()}catch{}if(O>=400)throw Mr(O,ee);if(O===201){let k=ee?.data?.uuid,me=ee?.data?.nonce;if(!k)throw new Error("Checkout session created but no UUID was returned by the billing API");if(!me)throw new K("Checkout session created but no `nonce` was returned by the billing API. Upgrade the billing service to TeamFloPay/backend#640 or later.","api_error",{code:"MissingCheckoutSessionToken"});(P.length||M)&&q(k,{currency:M,products:P.map(f=>({code:f.code??f.providerItemId??f.providerPlanId,type:f.type,name:f.name??f.itemName??f.providerItemName??f.subscriptionName??f.providerPlanName??null,totalAmount:f.totalAmount,overrideAmount:f.overrideAmount,currency:f.currency??M}))});let re=new URL(`${o.replace(/\/+$/,"")}/secure`);re.searchParams.set("id",k);for(let[f,ne]of Object.entries(v))re.searchParams.set(f,ne);if(T&&typeof window<"u"&&typeof document<"u"){let f=JSON.stringify({origin_url:d}),ne=window.location.hostname.split(".").slice(-2).join(".");document.cookie=`checkout_data=${encodeURIComponent(f)}; domain=.${ne}; path=/; max-age=3600; SameSite=Lax; Secure;`,document.cookie=`flopay_checkout_token=${encodeURIComponent(me)}; domain=.${ne}; path=/; max-age=3600; SameSite=Lax; Secure;`}return typeof window<"u"&&(window.location.href=re.toString()),{status:201,redirectUrl:re.toString(),nonce:me}}return O===204?(typeof window<"u"&&(window.location.href=c),{status:204}):{status:O}}async function Pr(n){let e=ft(n),t=gt(e),r=R(n.timeoutMs);try{let o=await ht(n,r.signal,t);return Ct(e,o),o}catch(o){throw pe(e,o),o}finally{r.clear(),j(e.reporter)}}function gt(n){let e=!1;return t=>{if(e)return;e=!0;let r=mt(t);n.reporter.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:r,attempt:n.attempt}),n.reporter.performance({stage:"session_first_byte",durationMs:n.reporter.now()-n.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:r,attempt:n.attempt})}}function ft(n){let e=new C({billingApiUrl:n.billingApiUrl,sdkVersion:ut,enabled:n.telemetry!==!1}),t=e.now();return e.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"}),{reporter:e,startedAt:t,attempt:0}}function Ct(n,e){let t=mt(e.status);n.reporter.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:t}),n.reporter.performance({stage:"session_create",durationMs:n.reporter.now()-n.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:t,attempt:n.attempt})}function pe(n,e){let{reporter:t}=n,r=Tr(e,"CHECKOUT_SESSION_CREATE_FAILED");if(t.performance({stage:"session_create",durationMs:t.now()-n.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:r.statusClass,attempt:n.attempt}),e instanceof K&&e.type==="validation_error"){t.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"});return}if(r.statusClass==="4xx"){t.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create",statusClass:"4xx"});return}t.error({...r,stage:"session_create",requestCategory:"session_create"})}function j(n){n.flush().catch(()=>{}).finally(()=>n.destroy())}async function Er(n){let{maxRetries:e=2,...t}=n,r=ft(n),o=gt(r);if(!Number.isFinite(e)||!Number.isInteger(e)||e<0||e>=3)throw r.reporter.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),j(r.reporter),new Error(`Number of retries must be an integer between 0 and ${2}`);let s={...t,idempotencyKey:pt(t.idempotencyKey)},i=R(t.timeoutMs),a;for(let l=0;l<=e;l++){r.attempt=l;try{let c=await ht(s,i.signal,o);return Ct(r,c),i.clear(),j(r.reporter),c}catch(c){a=c;let d=c instanceof Error&&c.name==="AbortError",m=br(c),u=c instanceof K&&c.code===gr;if((d||m||u)&&!i.signal.aborted&&l<e){r.reporter.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:l+1});try{await L(l,i.signal)}catch(p){throw pe(r,p),i.clear(),j(r.reporter),p}continue}throw pe(r,c),i.clear(),j(r.reporter),c}}throw pe(r,a),i.clear(),j(r.reporter),a??new Error("Unknown error during checkout session creation")}import{dropThirdPartyOnlyError as En}from"@flopay/shared";export{de as FloPay,W as FloPayElements,D as PaymentAPI,z as PciVaultCardCapture,Ke as SESSION_CREATE_TELEMETRY,Y as StripeAdapter,q as cacheSessionDisplayData,ge as clearSessionDisplayData,Pr as createCheckoutSession,Er as createCheckoutSessionWithRetries,En as dropThirdPartyOnlyError,he as getSessionDisplayData,hr as loadFloPay,tr as toStripeAppearance,le as toStripeAppearanceTheme};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@flopay/js",
|
|
3
|
-
"version": "1.4.
|
|
3
|
+
"version": "1.4.22",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"sideEffects": false,
|
|
6
6
|
"publishConfig": {
|
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
],
|
|
28
28
|
"dependencies": {
|
|
29
29
|
"@stripe/stripe-js": "^9.8.0",
|
|
30
|
-
"@flopay/shared": "1.4.
|
|
30
|
+
"@flopay/shared": "1.4.22"
|
|
31
31
|
},
|
|
32
32
|
"devDependencies": {
|
|
33
33
|
"jsdom": "^29.1.1",
|