@flopay/js 1.4.10 → 1.4.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -272,12 +272,13 @@ The same default-on behavior and boolean opt-out apply to direct `FloPay`,
272
272
  Genuine payment failures carry only a bounded technical category:
273
273
  `server_error` for backend 5xx failures, `transport_error` when no usable
274
274
  response arrives, `invalid_response` for malformed closed response shapes, and
275
- `provider_runtime` for provider SDK failures. Categories are never derived
276
- from messages, response bodies, decline text, stacks, or identifiers. Backend
277
- payment declines and request validation failures use the non-error
278
- `payment_declined` and `validation_rejected` outcomes and carry no category.
279
- Uncategorized technical events remain serializable for backend rollout
280
- compatibility.
275
+ `provider_runtime` for provider SDK or hosted-widget runtime failures. Hosted
276
+ vault widget errors use that category both before and after submission without
277
+ including widget messages or session data. Categories are never derived from
278
+ messages, response bodies, decline text, stacks, or identifiers. Backend payment
279
+ declines and request validation failures use the non-error `payment_declined`
280
+ and `validation_rejected` outcomes and carry no category. Uncategorized technical
281
+ events remain serializable for backend rollout compatibility.
281
282
 
282
283
  ### Exports
283
284
 
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var pe=Object.defineProperty;var Xe=Object.getOwnPropertyDescriptor;var Ze=Object.getOwnPropertyNames;var et=Object.prototype.hasOwnProperty;var tt=(n,e)=>{for(var t in e)pe(n,t,{get:e[t],enumerable:!0})},rt=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ze(e))!et.call(n,s)&&s!==t&&pe(n,s,{get:()=>e[s],enumerable:!(r=Xe(e,s))||r.enumerable});return n};var nt=n=>rt(pe({},"__esModule",{value:!0}),n);var It={};tt(It,{FloPay:()=>J,FloPayElements:()=>j,PaymentAPI:()=>A,PciVaultCardCapture:()=>F,StripeAdapter:()=>K,cacheSessionDisplayData:()=>x,clearSessionDisplayData:()=>oe,createCheckoutSession:()=>Ge,createCheckoutSessionWithRetries:()=>Qe,getSessionDisplayData:()=>ne,loadFloPay:()=>He,toStripeAppearance:()=>qe,toStripeAppearanceTheme:()=>Y});module.exports=nt(It);var S=require("@flopay/shared");var Fe=require("@stripe/stripe-js"),h=require("@flopay/shared");var c=require("@flopay/shared");function I(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 ot="flopay_session_display:";var te=new Map;function re(n){return`${ot}${n}`}function me(){if(typeof window>"u")return null;try{return window.sessionStorage}catch{return null}}function x(n,e,t){if(!n)return;let r=t?.ttlMs??36e5,s={data:e,expiresAt:Date.now()+r},o=me();if(o)try{o.setItem(re(n),JSON.stringify(s));return}catch{}te.set(n,s)}function ne(n){if(!n)return null;let e=me();if(e)try{let r=e.getItem(re(n));if(r){let s=JSON.parse(r);if(s&&typeof s.expiresAt=="number"&&s.expiresAt>Date.now())return s.data;e.removeItem(re(n))}}catch{}let t=te.get(n);if(t){if(t.expiresAt>Date.now())return t.data;te.delete(n)}return null}function oe(n){if(!n)return;te.delete(n);let e=me();if(e)try{e.removeItem(re(n))}catch{}}var _=require("@flopay/shared"),st="/v1/sdk-telemetry/events",ye=16,it=64,at=1500,be=1e3,lt=64,ct="00000000-0000-4000-8000-000000000000",dt={technical_error:8,lifecycle:32,expected_outcome:32,performance:24};function N(){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 ut(n){try{return new TextEncoder().encode(n).byteLength}catch{return n.length}}function pt(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 w(){return globalThis.performance?.now()??0}var T=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(/\/+$/,"")}${st}`,this.sdkPackage=e.sdkPackage??"@flopay/js",this.sdkVersion=e.sdkVersion,this.correlationId=N(),this.merchantEnabled=e.enabled!==!1,this.clock=e.clock??w,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,_.buildTelemetryLogEvent)({...this.checkoutContext,...e,eventId:N(),sequence:this.sequence++}))}error(e){if(!this.canCollect())return;let t=(0,_.buildTelemetryErrorEvent)({...this.checkoutContext,...e,eventId:ct,sequence:0}),r=pt(t),s=this.now();this.pruneReportedFailures(s);let o=this.reportedFailures.get(r);if(o!==void 0&&s>=o&&s-o<be){this.log({name:"operation.deduplicated",stage:e.stage,provider:e.provider,paymentMethodCategory:e.paymentMethodCategory,attempt:e.attempt});return}this.rememberReportedFailure(r,s),this.enqueue((0,_.buildTelemetryErrorEvent)({...this.checkoutContext,...e,eventId:N(),sequence:this.sequence++}))}performance(e){this.canCollect()&&this.enqueue((0,_.buildTelemetryPerformanceEvent)({...this.checkoutContext,...e,eventId:N(),sequence:this.sequence++}))}terminal(e){if(this.canCollect()&&(this.enqueue((0,_.buildTelemetryTerminalEvent)({...this.checkoutContext,...e,eventId:N(),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 w()}}pruneReportedFailures(e){for(let[t,r]of this.reportedFailures)(e<r||e-r>=be)&&this.reportedFailures.delete(t)}rememberReportedFailure(e,t){for(;this.reportedFailures.size>=lt;){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>=it||this.eventCounts[e.class]>=dt[e.class])){if(this.eventCounts[e.class]+=1,this.queue.push(e),this.queue.length>=ye){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,ye);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,ye);this.sendBatch(e)}}async sendBatch(e){if(!this.browserTransportAvailable||this.ingestionDisabled)return;let t=(0,_.serializeTelemetryBatch)(e,{correlationId:this.correlationId,sdkPackage:this.sdkPackage,sdkVersion:this.sdkVersion,batchId:N()});if(ut(t)>_.TELEMETRY_MAX_BATCH_BYTES)return;let r=typeof AbortController>"u"?null:new AbortController,s=null;try{let o=fetch(this.endpoint,{method:"POST",headers:{"content-type":"text/plain;charset=UTF-8"},body:t,credentials:"omit",keepalive:!0,referrerPolicy:"no-referrer",signal:r?.signal}).then(async l=>l.status!==202?null:(await l.json().catch(()=>null))?.status==="disabled"?"disabled":null).catch(()=>null),i=new Promise(l=>{s=setTimeout(()=>{r?.abort(),l(null)},at)});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)}},Me=Symbol.for("@flopay/js.telemetry.reporter-factory.v1"),ke=globalThis;ke[Me]===void 0&&Object.defineProperty(ke,Me,{configurable:!0,enumerable:!1,writable:!1,value:n=>new T(n)});var Re=1e3,mt=500,yt=15e3,ht=3e3,gt=1e4,ft=1e4;function Ae(n){return typeof n=="object"&&n!==null}function B(n,e){return I(n?.[e])}function Se(n,e){return Pe(n?.[e])}function Ct(n,e){let t=n?.[e];return typeof t=="number"&&Number.isFinite(t)?t:void 0}function he(n){return new Promise(e=>setTimeout(e,n))}function se(){return new c.FloPayError("Checkout is still processing. Please try again shortly.","api_error",{code:"checkout_processing_timeout"})}async function V(n,e){let t=await n.json().catch(()=>null),r=Ae(t?.error)?t.error:null,s=Se(t,"message")??Se(r,"message")??e,o=B(t,"code")??B(t,"gatewayErrorCode")??B(r,"code")??`http_${n.status}`;return new c.FloPayError(s,"api_error",{code:o,statusCode:n.status})}async function vt(n){if(n.status!==400&&n.status!==422)return;if(n.status===422)return"validation_rejected";let e=await n.clone().json().catch(()=>null);return Ae(e)&&Array.isArray(e.fields)?"validation_rejected":"payment_declined"}function Ee(n){return n===400||n===422}var G=2,Tt=2;async function ie(n,e,t=G,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 he(150*2**o)}}function _t(n){return"now"in n||"onFirstByte"in n||"onSessionCreateFailure"in n||"onRetry"in n}var D=class D{constructor(e,t={}){this.baseUrl=e.replace(/\/+$/,"");let r=_t(t);this.telemetryHooks=r?t:void 0,this.directTelemetry=r||t.telemetry===!1?void 0:new T({billingApiUrl:this.baseUrl,sdkVersion:c.SDK_VERSION})}destroy(){this.directTelemetry?.destroy()}reportDirectFailure(e,t,r,s,o="unknown"){let i=(0,c.classifyTelemetryFailure)(e,t);this.directTelemetry?.error({...i,stage:r,requestCategory:s,paymentMethodCategory:o})}reportAccountSnapshotFailure(e,t){let r=(0,c.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()??w()}catch{return w()}}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={[c.FLO_SDK_VERSION_HEADER]:c.SDK_VERSION};t&&(s["x-checkout-session-token"]=t);try{let o=await ie(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}`,{headers:s},G,d=>{this.telemetryHooks?.onRetry?.("session_read",d),this.directTelemetry?.log({name:"operation.retry",stage:"session_read",requestCategory:"session_read",attempt:d})}),i=Math.max(0,this.telemetryTimestamp()-r);try{this.telemetryHooks?.onFirstByte?.(i)}catch{}let a=`${Math.floor(o.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}),!o.ok)throw await V(o,"Failed to get checkout session");let l=await o.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(o){throw this.directTelemetry?.error({...(0,c.classifyTelemetryFailure)(o,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"}),o}}cacheSessionDisplayData(e,t,r){x(e,t,r)}clearSessionDisplayData(e){oe(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(),ft);this.beginDirectTelemetryCheckout(e);let o=this.telemetryTimestamp();this.directTelemetry?.log({name:"vault.capture.requested",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card"});let i={"Content-Type":"application/json"};t&&(i["x-checkout-session-token"]=t);try{let a=await ie(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/vault/capture`,{method:"POST",headers:i,signal:r.signal},G,d=>{this.telemetryHooks?.onRetry?.("vault_capture",d),this.directTelemetry?.log({name:"operation.retry",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card",attempt:d})});if(!a.ok)throw await V(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()-o),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"2xx"}),this.toVaultBlock(l)}catch(a){let l=r.signal.aborted?new c.FloPayError("Timed out while loading the secure card form. Please try again.","api_error",{code:"vault_capture_timeout"}):a;throw this.reportDirectFailure(l,"VAULT_LOAD_FAILED","vault_request","vault_capture","card"),l}finally{clearTimeout(s)}}async getUnifiedCheckoutSession(e,t){let 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 c.FloPayError("processPayment requires `nonce` \u2014 pass the value returned from session creation.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let s=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.processing.started",stage:"processing",requestCategory:"process_payment"});let{nonce:o,...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":o},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 vt(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,c.telemetryStatusClass)(a.status),failureCategory:a.status>=500?"server_error":void 0}),a}try{let l=await this.resolveProcessResponse(a,t.sessionId,{...r,nonce:o});return this.directTelemetry?.log({name:"payment.processing.completed",stage:"processing",requestCategory:"process_payment",statusClass:(0,c.telemetryStatusClass)(l.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"process_payment",statusClass:(0,c.telemetryStatusClass)(l.status)}),l}catch(l){throw l instanceof c.FloPayError&&l.code==="checkout_processing_timeout"||this.reportDirectFailure(l,"PAYMENT_PROCESSING_FAILED","processing","process_payment"),l}}async patchAccountSnapshot(e,t,r,s){this.beginDirectTelemetryCheckout(e);let o=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.state_transition",stage:"processing",requestCategory:"account_snapshot"});let i=s?.timeoutMs??gt,a=new AbortController,l=()=>a.abort();s?.signal&&(s.signal.aborted?a.abort():s.signal.addEventListener("abort",l,{once:!0}));let d=setTimeout(()=>a.abort(),i);try{let u;try{u=await ie(`${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},G,y=>{this.telemetryHooks?.onRetry?.("account_snapshot",y),this.directTelemetry?.log({name:"operation.retry",stage:"processing",requestCategory:"account_snapshot",attempt:y})})}finally{clearTimeout(d),s?.signal?.removeEventListener("abort",l)}if(!u.ok)throw await V(u,"Failed to persist account snapshot");this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"account_snapshot",statusClass:"2xx"})}catch(u){throw this.reportAccountSnapshotFailure(u,s?.telemetryMode??"blocking"),u}}async createSessionIntent(e,t,r,s){if(!t)throw new c.FloPayError("createSessionIntent requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let o=r,i=o.paymentMethodType,a=typeof i=="string"&&i.trim().toLowerCase()==="card",l=typeof i=="string"&&i.length>0&&!a&&(typeof o.paymentMethodId=="string"||o.paymentMethodId===null),d=o.provider==="stripe"&&(o.paymentMethodCategory==="wallet"||o.paymentMethodCategory==="apm")&&(o.intentKind==="payment"||o.intentKind==="setup"),u=o.provider==="paypal"&&o.paymentMethodCategory==="wallet"&&o.paymentMethodType==="paypal"&&o.paymentMethodId===null&&o.intentKind==="payment";if(!l||!d&&!u)throw new c.FloPayError("Only wallet, APM, and PayPal session intents are supported.","validation_error",{code:"InvalidSessionIntentRequest"});let y=o.authorizationAttemptId;if(y!==void 0&&!(0,c.isUuidV4)(y))throw new c.FloPayError("authorizationAttemptId must be a v4 UUID identifying one buyer authorization attempt.","validation_error",{code:"InvalidAuthorizationAttemptId",param:"authorizationAttemptId"});let P=(0,c.isUuidV4)(y)?y:(0,c.randomUuidV4)();this.beginDirectTelemetryCheckout(e);let f=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.intent.started",stage:"processing",requestCategory:"intent_create"});let b={"Content-Type":"application/json","x-checkout-session-token":t,[c.IDEMPOTENCY_KEY_HEADER]:s?.idempotencyKey||P},M=!1;try{let k=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents`,{method:"POST",headers:b,body:JSON.stringify({...r,authorizationAttemptId:P}),signal:s?.signal});if(!k.ok){M=!0;let U=await V(k,"Failed to create checkout intent"),de=(0,c.classifyTelemetryFailure)(U,"PAYMENT_PROCESSING_FAILED");throw Ee(U.statusCode)?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"intent_create",statusClass:"4xx"}):this.directTelemetry?.error({...de,stage:"processing",requestCategory:"intent_create"}),U}let q=(await k.json()).data;if(!q||typeof q!="object")throw new c.FloPayError("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});let p=q,H=p.paymentMethodType,O=(p.paymentMethodCategory==="wallet"||p.paymentMethodCategory==="apm")&&typeof H=="string"&&H.trim().toLowerCase()!=="card"&&(typeof p.paymentMethodId=="string"||p.paymentMethodId===null)&&typeof p.providerObjectId=="string",E=p.provider==="stripe"&&(p.intentKind==="payment"||p.intentKind==="setup")&&typeof p.clientSecret=="string",$=p.provider==="paypal"&&p.paymentMethodCategory==="wallet"&&p.paymentMethodType==="paypal"&&p.paymentMethodId===null&&p.intentKind==="payment"&&(p.providerObjectType==="order"||p.providerObjectType==="subscription")&&p.clientSecret===null,ce=p.provider===r.provider&&p.paymentMethodCategory===r.paymentMethodCategory&&p.paymentMethodType===r.paymentMethodType&&p.paymentMethodId===r.paymentMethodId&&p.intentKind===r.intentKind;if(!O||!E&&!$||!ce)throw new c.FloPayError("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});return this.directTelemetry?.log({name:"payment.intent.completed",stage:"processing",requestCategory:"intent_create",statusClass:(0,c.telemetryStatusClass)(k.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-f),durationMode:"machine",requestCategory:"intent_create",statusClass:(0,c.telemetryStatusClass)(k.status)}),p}catch(k){throw M||this.reportDirectFailure(k,"PAYMENT_PROCESSING_FAILED","processing","intent_create"),k}}async reportSessionIntentDecline(e,t,r,s){if(!t)throw new c.FloPayError("reportSessionIntentDecline requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let o=r,i=o.providerDeclineReason,a=o.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),d=typeof a=="string"&&a.length>0&&a.trim().toLowerCase()!=="card"&&l,u=o.provider==="stripe"&&(o.paymentMethodCategory==="wallet"||o.paymentMethodCategory==="apm"),y=o.provider==="paypal"&&o.paymentMethodCategory==="wallet"&&o.paymentMethodType==="paypal";if(!d||!u&&!y)throw new c.FloPayError("Invalid non-card decline classification.","validation_error",{code:"InvalidSessionIntentDeclineRequest"});let P=y?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:i}:{provider:"stripe",paymentMethodCategory:o.paymentMethodCategory,paymentMethodType:o.paymentMethodType,providerDeclineReason:i},f=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:s?.signal});if(!f.ok)throw await V(f,"Failed to report checkout decline")}async getPaymentsByEmail(e,t){this.beginDirectTelemetryOperation();let r=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved"});let s=t?.page??1,o=t?.limit??1,i=new URLSearchParams({email:e,page:String(s),limit:String(o),sortField:"createdAt",sortDirection:"DESC"});try{let a=await fetch(`${this.baseUrl}/v1/payments?${i.toString()}`,{method:"GET",signal:t?.signal,keepalive:!0});if(!a.ok)throw new c.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){this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp();this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});try{let r=await this.createAndFetchSessionRequest(e,t);return this.adoptDirectTelemetryCheckout(r.data.session?.id),this.directTelemetry?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_create",statusClass:"2xx"}),this.directTelemetry?.performance({stage:"session_create",durationMs:this.telemetryTimestamp()-t,durationMode:"machine",requestCategory:"session_create",statusClass:"2xx"}),r}catch(r){if(!(r instanceof c.FloPayError&&r.code==="session_auto_completed"))try{this.telemetryHooks?.onSessionCreateFailure?.(r)}catch{}let s=(0,c.classifyTelemetryFailure)(r,"CHECKOUT_SESSION_CREATE_FAILED");throw r instanceof c.FloPayError&&r.type==="validation_error"?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}):r instanceof c.FloPayError&&Ee(r.statusCode)?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create",statusClass:"4xx"}):r instanceof c.FloPayError&&r.code==="session_auto_completed"||this.directTelemetry?.error({...s,stage:"session_create",requestCategory:"session_create"}),r}}async createAndFetchSessionRequest(e,t){let r=e.products??(0,c.foldIntoProducts)(e.items,e.subscriptions),s=(0,c.resolveSessionCurrency)(e.currency,e.items,e.subscriptions,r);if(!s)throw new c.FloPayError("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});let o={clientId:e.clientId,checkoutVersion:c.SDK_VERSION,successUrl:e.successUrl,cancelUrl:e.cancelUrl,currency:s,checkoutMode:e.checkoutMode??"full",products:r.map(f=>(0,c.buildProductPayload)(f,s)),accountData:{userId:e.account.userId,firstName:e.account.firstName??null,lastName:e.account.lastName??null,email:e.account.email,country:e.account.country??null,gender:e.account.gender??null,city:e.account.city??null,state:e.account.state??null,zip:e.account.zip??null,addressLine1:e.account.addressLine1??null,addressLine2:e.account.addressLine2??null},couponCodes:e.couponCodes??[]};e.tokenizedData&&(o.tokenizedData=e.tokenizedData),e.tagsData&&(o.tagsData=e.tagsData),e.utmMetadata?.length&&(o.utmMetadata=e.utmMetadata),e.avsCheck!==void 0&&(o.avsCheck=e.avsCheck),e.checkoutType&&(o.checkoutType=e.checkoutType),e.checkoutLayout&&(o.checkoutLayout=e.checkoutLayout),e.avsConfig&&(o.avsConfig=e.avsConfig);let i={"Content-Type":"application/json",[c.FLO_SDK_VERSION_HEADER]:c.SDK_VERSION},a=(0,c.resolveIdempotencyKey)(e.idempotencyKey);a&&(i[c.IDEMPOTENCY_KEY_HEADER]=a);let l,d=!1;for(let f=0;;f++){if(l=await ie(`${this.baseUrl}/v1/checkouts/sessions?expand=true`,{method:"POST",headers:i,body:JSON.stringify(o)},G,M=>{this.telemetryHooks?.onRetry?.("session_create",M),this.directTelemetry?.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:M})}),!d){d=!0;let M=`${Math.floor(l.status/100)}xx`;this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:M}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:this.telemetryTimestamp()-t,durationMode:"machine",requestCategory:"session_create",statusClass:M})}if(l.status===204)throw new c.FloPayError("Session auto-completed \u2014 payment method already on file","api_error",{code:"session_auto_completed"});if(l.ok)break;let b=await V(l,"Failed to create checkout session");if(b.code===c.IDEMPOTENCY_IN_PROGRESS_CODE&&f<Tt){try{this.telemetryHooks?.onRetry?.("session_create",f+1),this.directTelemetry?.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:f+1})}catch{}await he(150*2**f);continue}throw b}let u=await l.json();if(u.data&&"gateways"in u.data){this.autoCacheDisplayData(u.data.uuid,e);let f=this.mergeCachedDisplayData(u.data),b=this.normalizeRawSession(f);return u.vault&&b.data.session&&(b.data.session.vault=this.toVaultBlock(u.vault)),{...b,autoProcessingError:u.autoProcessingError,autoProcessingAttempted:u.autoProcessingAttempted,autoProcessingPending:u.autoProcessingPending}}let y=u.data?.uuid;if(!y)throw new c.FloPayError("No session ID returned","api_error",{code:"InvalidCheckoutSessionResponse"});return this.autoCacheDisplayData(y,e),this.adoptDirectTelemetryCheckout(y),{...await this.getUnifiedCheckoutSession(y),autoProcessingError:u.autoProcessingError,autoProcessingAttempted:u.autoProcessingAttempted,autoProcessingPending:u.autoProcessingPending}}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??yt,o=Date.now()+s,i=this.clampRetryAfterMs(t?.initialDelayMs??Re),a=0;try{for(;;){let l=o-Date.now();if(l<=0)throw se();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 he(Math.min(i,l)),Date.now()>=o)throw se()}let d=await this.getUnifiedCheckoutSession(e,t?.nonce),u=d.data.session?.status;if(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"}),d;if(Date.now()>=o)throw se();i=this.clampRetryAfterMs(Math.max(i*2,mt))}}catch(l){throw l instanceof c.FloPayError&&l.code==="checkout_processing_timeout"&&this.reportDirectFailure(l,"RECOVERY_FAILED","recovery","session_read","saved"),l}}normalizeRawSession(e){let t=e.gateways??{},r=[],s={session:this.toCheckoutSession(e)},o=t.stripe;if(o?.publishableKey){r.push("stripe");let l=[e.stripeClientSecret,o.stripeClientSecret].find(d=>typeof d=="string"&&d.length>0);s.stripe={clientSecret:l??"",publishableKey:o.publishableKey??void 0,paypalPublishableKey:o.paypalPublishableKey??void 0,environment:o.environment,enabledPaymentMethods:Array.isArray(o.enabledPaymentMethods)?o.enabledPaymentMethods.filter(d=>typeof d=="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((d,u)=>d+(u.overrideAmount??u.totalAmount??0),0),o=r?e.totalAmount:s,i=Math.round(o*100),a=e.currency??t[0]?.currency??"USD",l=t.some(d=>d.type==="subscription")?"subscription":"payment";return{id:e.uuid,clientSecret:e.nonce,mode:l,status:this.toCheckoutSessionStatus(e.status),amount:i,currency:a,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(d=>({...d,totalAmount:typeof d.totalAmount=="number"?d.totalAmount:void 0,overrideAmount:typeof d.overrideAmount=="number"?d.overrideAmount:null,currency:typeof d.currency=="string"?d.currency:void 0,metadata:d.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==="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"});throw i.data.session?.status==="expired"?new c.FloPayError("Checkout session has expired.","api_error",{code:"checkout_session_expired"}):se()}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:B(e,"sessionId")??r,retryAfterMs:this.clampRetryAfterMs(Ct(e,"retryAfterMs")??i??Re),statusUrl:B(e,"statusUrl"),sessionUrl:B(e,"sessionUrl")}}clampRetryAfterMs(e){return Math.max(0,Math.min(e,ht))}autoCacheDisplayData(e,t){if(!e)return;let r=t.products??(0,c.foldIntoProducts)(t.items,t.subscriptions);if(r.length===0&&!t.currency)return;let s=t.products!==void 0,o=(0,c.resolveSessionCurrency)(t.currency,s?void 0:t.items,s?void 0:t.subscriptions,r);x(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=ne(e.uuid),r=new Map,s=i=>i?`code:${i}`:void 0;for(let i of t?.products??[]){let a=s(i.code);a&&r.set(a,i)}let o=(e.products??[]).map(i=>{let a=s(i.code),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:o}}};D.activeVaultCaptureRequests=new Map;var A=D;function Ie(n,e){let t=A;return new t(n,e)}function xe(n){return{payment:"payment",address:"address"}[n]}function Y(n){switch(n){case"night":return"night";case"flat":return"flat";default:return"stripe"}}function qe(n){return{...n,theme:Y(n.theme)}}function ge(n){return n?JSON.stringify(n.map(e=>e.trim().toLowerCase())):null}function De(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 wt(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,Fe.loadStripe)(e.publishableKey,{locale:e.locale??"auto"});if(!t)throw new h.FloPayError("Failed to initialize Stripe. Check your publishable key.","authentication_error");this.stripe=t}getElements(e){if(!this.stripe)throw new h.FloPayError("StripeAdapter not initialized. Call initialize() first.","api_error");let t=e?.appearance?{theme:Y(e.appearance.theme),variables:e.appearance.variables,rules:e.appearance.rules}:void 0,r=t?JSON.stringify(t):null,s=ge(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,a=e?.amount??0,l=(e?.currency??"usd").toLowerCase(),d=e?.paymentMethodCreation??"manual";e?.clientSecret?i={clientSecret:e.clientSecret}:a>0?(i={mode:"payment",amount:a,currency:l,paymentMethodCreation:d},e?.setupFutureUsage&&(i.setupFutureUsage=e.setupFutureUsage)):i={mode:"setup",currency:l,paymentMethodCreation:d},!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 h.FloPayError("StripeAdapter not initialized. Call initialize() first.","api_error");let r,s=!1;if((0,h.isSetupIntentClientSecret)(e)){let{setupIntent:l,error:d}=await this.stripe.retrieveSetupIntent(e);r=l,s=!!d}else{let{paymentIntent:l,error:d}=await this.stripe.retrievePaymentIntent(e);r=l,s=!!d}let o=r?.payment_method_types;if(s||!Array.isArray(o))throw new h.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(o.some(l=>typeof l!="string"||!i.has(l.trim().toLowerCase()))||o.length===0)throw new h.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(d=>d.trim()).filter(d=>d&&d.toLowerCase()!=="card");if(!l?.length)throw new h.FloPayError("At least one supported non-card payment method is required.","validation_error",{param:"paymentMethodTypes"});if(r={...t,paymentMethodTypes:l},r.clientSecret){let d=ge(l);this.elements&&this.appliedClientSecret===r.clientSecret&&this.appliedPaymentMethodTypesKey===d&&this.verifiedClientSecret===r.clientSecret&&this.verifiedPaymentMethodTypesKey===d||await this.assertClientSecretPaymentMethods(r.clientSecret,l)}}let s=this.getElements(r);e==="payment"&&r.clientSecret&&(this.verifiedClientSecret=r.clientSecret,this.verifiedPaymentMethodTypesKey=ge(r.paymentMethodTypes));let o=xe(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=s.create(o,i);return De(a)}getElement(e){if(!this.elements)return null;let t=xe(e),r=this.elements.getElement(t);return r?De(r):null}async submitElements(){if(!this.stripe||!this.elements)return{error:new h.FloPayError("Stripe not initialized","api_error")};let{error:e}=await this.elements.submit();return e?{error:new h.FloPayError(e.message??"Validation failed","validation_error")}:{}}async confirmPayment(e){if(!this.stripe||!this.elements)throw new h.FloPayError("StripeAdapter not initialized or no elements created.","api_error");let t=e.billingDetails,r=t?wt(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 h.FloPayError(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 h.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 h.FloPayError("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 h.FloPayError(o.message??"PayPal payment failed","validation_error",{code:o.code})}}let r;try{let o=await new A(t).createSessionIntent(e.sessionId,e.nonce??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"});if(o.provider!=="stripe")throw new h.FloPayError("Invalid provider returned for PayPal intent","api_error");r=o.clientSecret}catch(o){return{status:"failed",error:o instanceof h.FloPayError?o:new h.FloPayError("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 A(t).reportSessionIntentDecline(e.sessionId,e.nonce,{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:s.code??"provider_declined"})}catch{}return{status:"failed",error:new h.FloPayError(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 h.FloPayError("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 h.FloPayError(i.message??"Failed to retrieve PayPal payment","api_error")};if(o&&(o.status==="requires_capture"||o.status==="succeeded")){let a=typeof o.payment_method=="string"?o.payment_method:o.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:o.status,paymentIntentId:o.id,paymentMethodId:a}}return{status:"failed",error:new h.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:Y(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 g=require("@flopay/shared");var Oe=require("@flopay/shared"),j=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 Oe.FloPayError("At least one supported non-card payment method is required.","validation_error",{param:"paymentMethodTypes"});r.paymentMethodTypes=a}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()}};var v=require("@flopay/shared");var fe="flopay-vault",Ue={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 W(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 ae(n,e){return(0,v.buildTelemetryLogEvent)({eventId:"11111111-1111-4111-8111-111111111111",name:n,stage:e,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}function Le(n){return n?{errorCode:"VAULT_SUBMIT_FAILED",stage:"vault_submit"}:{errorCode:"VAULT_LOAD_FAILED",stage:"vault_mount"}}function Pt(n,e){if(n==="complete"||n==="decline")return(0,v.buildTelemetryTerminalEvent)({eventId:"22222222-2222-4222-8222-222222222222",outcome:n==="complete"?"payment_succeeded":"payment_declined",sequence:0,provider:"pcivault",paymentMethodCategory:"card"});if(n==="error"){let s=Le(e);return(0,v.buildTelemetryErrorEvent)({eventId:"33333333-3333-4333-8333-333333333333",...s,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}let[t,r]=Ue[n];return ae(t,r)}function bt(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===fe&&(e.type==="ready"||e.type==="submitting"||e.type==="blocked"||e.type==="complete"||e.type==="decline"||e.type==="error"||e.type==="action_required")}function Mt(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===fe&&e.type==="validation"&&Array.isArray(e.messages)}function kt(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===fe&&e.type==="resize"&&typeof e.height=="number"&&Number.isFinite(e.height)}var F=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 T({billingApiUrl:(0,v.resolveBillingApiUrl)(),sdkVersion:v.SDK_VERSION}):void 0)}async mount(e,t){if(this.ownsTelemetryReporter&&!this.telemetryReporter&&(this.telemetryReporter=new T({billingApiUrl:(0,v.resolveBillingApiUrl)(),sdkVersion:v.SDK_VERSION})),this.mountStartedAt=this.telemetryReporter?.now?.()??w(),this.vaultReadyReported=!1,this.submissionStarted=!1,this.submissionStartedAt=null,typeof window>"u"||typeof document>"u")throw this.reportVaultLoadFailure(),new v.FloPayError("The vault card form is only available in the browser.","api_error",{code:"card_capture_no_window"});if(!t?.html||!t.html.trim())throw this.reportVaultLoadFailure(),new v.FloPayError("No vault capture widget HTML was provided to mount the secure card form.","api_error",{code:"card_capture_no_widget_html"});this.container=e,this.messageToken=t.messageToken??null,this.expectedOrigin=t.expectedOrigin??this.config.expectedOrigin??null,this.theme=t.theme??null;try{this.attachMessageListener(),this.injectWidget(e,t.html)}catch(r){throw this.reportVaultLoadFailure(),r}this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),W(ae("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(kt(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;this.applyHeight(r.height);return}if(Mt(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;let a=r.messages.filter(l=>typeof l=="string"&&l.trim()).join(" ");this.emit("validation",{sessionId:this.config.sessionId,message:a||void 0});return}if(!bt(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={sessionId:r.sessionId??this.config.sessionId,intentId:r.intentId,declineReason:r.declineReason,message:r.message,nextActionRedirectUrl:r.nextActionRedirectUrl};r.type==="submitting"&&(this.submissionStarted=!0,this.submissionStartedAt=this.telemetryReporter?.now?.()??w()),W(Pt(r.type,this.submissionStarted)),this.reportOutcome(r.type),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(),this.emit(r.type,i)};this.messageHandler=e,window.addEventListener("message",e)}reportOutcome(e){let t=this.telemetryReporter;if(!t)return;if(e==="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"})),e==="complete"||e==="decline"){t.log({name:"vault.terminal",stage:"completion",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:e==="complete"?"payment_succeeded":"payment_declined",provider:"pcivault",paymentMethodCategory:"card"});return}if(e==="error"){let o=Le(this.submissionStarted);t.log({name:"vault.terminal",stage:o.stage,provider:"pcivault",paymentMethodCategory:"card"}),t.error({...o,provider:"pcivault",paymentMethodCategory:"card"});return}if(e==="action_required"){t.log({name:"vault.action.required",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"}),t.log({name:"vault.three_ds.handoff",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"});let o=this.submissionStartedAt;this.submissionStartedAt=null,o!==null&&t.performance({stage:"three_ds_handoff",durationMs:Math.max(0,t.now()-o),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:"action_required",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"});return}let[r,s]=Ue[e];t.log({name:r,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 s=document.createElement("button");s.type="button",s.setAttribute("aria-label","Close card authentication"),s.textContent="\xD7",s.style.cssText=["position:fixed","top:20px","right:20px","width:40px","height:40px","border:0","border-radius:9999px","background:#fff","color:#0f172a","font-size:28px","line-height:40px","cursor:pointer","box-shadow:0 4px 14px rgba(0,0,0,0.25)"].join(";"),s.addEventListener("click",()=>this.abandonActionRequiredOverlay()),t.appendChild(s),t.addEventListener("click",i=>{i.target===t&&this.abandonActionRequiredOverlay()});let o=i=>{if(i.source!==r.contentWindow)return;let a=i.data;if(!a||typeof a!="object")return;let l=a;l.source==="flopay-vault-3ds-return"&&(W(ae("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",o),this.threeDsReturnHandler=o,document.body.appendChild(t),this.actionOverlay=t,W(ae("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,v.buildTelemetryTerminalEvent)({eventId:"77777777-7777-4777-8777-777777777777",outcome:"customer_abandoned",stage:"three_ds_handoff",sequence:0,provider:"pcivault",paymentMethodCategory:"card"});W(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 Ne(n,e){let t=F;return new t(n,{reporter:e})}var Ve=Symbol.for("@flopay/js.telemetry.bridge.v1");function Be(n,e,t){let r=()=>e?.now()??t();Object.defineProperty(n,Ve,{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 Ke(n){return n[Ve]}function z(n){if(!n)return!1;let e=n.code?.toLowerCase()??"";return!!n.declineCode||e.includes("declin")}function Rt(n){return n==="stripe"||n==="paypal"||n==="pcivault"?n:"other"}var J=class{constructor(e,t,r){this.currentElements=null;this.provider=e,this.config=t,this.telemetryReporter=r??new T({billingApiUrl:(0,g.resolveBillingApiUrl)(t.billingApiUrl),sdkVersion:g.SDK_VERSION,enabled:t.telemetry!==!1}),Be(this,this.telemetryReporter,w)}now(){return this.telemetryReporter?.now?.()??w()}elements(e){return this.currentElements&&this.currentElements.destroy(),this.currentElements=new j(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?Ne({sessionId:e?.sessionId},this.telemetryReporter):new F({sessionId:e?.sessionId,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"&&(z(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 g.FloPayError&&z(r))this.telemetryReporter?.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"});else if(r instanceof g.FloPayError&&r.type==="validation_error")this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal"});else{let s=(0,g.classifyTelemetryFailure)(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"}):z(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 g.FloPayError&&z(t))this.telemetryReporter?.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"});else if(t instanceof g.FloPayError&&t.type==="validation_error")this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal"});else{let r=(0,g.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 g.FloPayError("A supported non-card payment method is required.","validation_error",{param:"paymentMethodType"});let t=this.now(),r=Rt(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}):z(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 g.FloPayError&&z(s)?this.telemetryReporter?.terminal({outcome:"payment_declined",provider:r,paymentMethodCategory:e.paymentMethodCategory}):s instanceof g.FloPayError&&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 g.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 g.FloPayError("Session not found","api_error");return r.data.session}async retrieveUnifiedSession(e,t){if(!e)throw new g.FloPayError("sessionId is required.","validation_error",{param:"sessionId"});let r=(0,g.resolveBillingApiUrl)(t??this.config.billingApiUrl),s=this.now();this.telemetryReporter?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let o,i=Ie(r,{now:()=>this.telemetryReporter?.now()??w(),onFirstByte:a=>{o=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 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"}),a}catch(a){let l=(0,g.classifyTelemetryFailure)(a,a instanceof g.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()-s,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=J;return new r(n,e,t)}var ze=new Map;function Ce(n){return Array.isArray(n)?n.map(Ce):n&&typeof n=="object"?Object.fromEntries(Object.entries(n).filter(([,e])=>e!==void 0).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,Ce(t)])):n}function St(n,e){return JSON.stringify([n,(0,S.resolveBillingApiUrl)(e?.billingApiUrl),e?.telemetry!==!1,e?.locale??"auto",e?.apiVersion??null,Ce(e?.appearance??null)])}var le=new Map;async function He(n,e){if(!n){let a=new T({billingApiUrl:(0,S.resolveBillingApiUrl)(e?.billingApiUrl),sdkVersion:S.SDK_VERSION,enabled:e?.telemetry!==!1});throw a.error({errorCode:"CONFIGURATION_INVALID",stage:"sdk_initialize",paymentMethodCategory:"unknown"}),a.flush().catch(()=>{}).finally(()=>a.destroy()),new S.FloPayError("A publishable key is required to initialize FloPay.","validation_error",{param:"publishableKey"})}let t=St(n,e),r=ze.get(t);if(r)return e?.telemetry!==!1&&Ke(r)?.log({name:"sdk.cache.hit",stage:"sdk_initialize"}),r;let s=le.get(t);if(s)return s;let o={...e,publishableKey:n},i=(async()=>{let a=new T({billingApiUrl:(0,S.resolveBillingApiUrl)(o.billingApiUrl),sdkVersion:S.SDK_VERSION,enabled:o.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 d=new K;try{await d.initialize(o)}catch(P){throw a.error({errorCode:"SDK_INITIALIZATION_FAILED",failureCategory:"provider_runtime",stage:"sdk_initialize",provider:"stripe",paymentMethodCategory:"unknown"}),a.destroy(),P}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"});let u=a.now()-l;a.performance({stage:"sdk_initialize",durationMs:u,durationMode:"machine",provider:"stripe"}),a.performance({stage:"provider_ready",durationMs:u,durationMode:"machine",provider:"stripe"});let y=je(d,o,a);return ze.set(t,y),y})();le.set(t,i);try{return await i}finally{le.get(t)===i&&le.delete(t)}}var m=require("@flopay/shared");var ve=5;function Et(n,e){let t=e?.error,r=I(e?.code)??I(t?.code)??`http_${n}`,s=I(e?.message)??I(t?.message)??At(r,n);return new m.FloPayError(s,"api_error",{code:r,statusCode:n})}function At(n,e){switch(n){case"CouponLimitExceeded":return`Too many coupon codes \u2014 a checkout session accepts at most ${ve}.`;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 $e(n,e){let{billingApiUrl:t,checkoutBaseUrl:r,items:s=[],subscriptions:o=[],products:i,account:a,successUrl:l,cancelUrl:d,checkoutMode:u="confirm",couponCodes:y=[],tagsData:P,redirectParams:f={},setCookie:b=!0,timeoutMs:M=12e3,clientId:k,currency:_e,utmMetadata:q,idempotencyKey:p}=n,H=(0,m.resolveIdempotencyKey)(p);if(y.length>ve)throw new m.FloPayError(`Too many coupon codes \u2014 a checkout session accepts at most ${ve}.`,"validation_error",{code:"CouponLimitExceeded",param:"couponCodes"});let O=i??(0,m.foldIntoProducts)(s,o),E=(0,m.resolveSessionCurrency)(_e,s,o,O);if(!E)throw new m.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 $={clientId:k,checkoutVersion:m.SDK_VERSION,successUrl:l,cancelUrl:d,currency:E,checkoutMode:u,products:O.map(R=>(0,m.buildProductPayload)(R,E)),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:y};P&&($.tagsData=P),q?.length&&($.utmMetadata=q);let ce=`${t.replace(/\/+$/,"")}/v1/checkouts/sessions`,U=new AbortController,de=setTimeout(()=>U.abort(),M),we={"Content-Type":"application/json"};H&&(we[m.IDEMPOTENCY_KEY_HEADER]=H);let L,X;try{let R=await fetch(ce,{method:"POST",headers:we,body:JSON.stringify($),signal:U.signal});try{e?.(R.status)}catch{}L=R.status;try{X=await R.json()}catch{}}finally{clearTimeout(de)}if(L>=400)throw Et(L,X);if(L===201){let R=X?.data?.uuid,ue=X?.data?.nonce;if(!R)throw new Error("Checkout session created but no UUID was returned by the billing API");if(!ue)throw new m.FloPayError("Checkout session created but no `nonce` was returned by the billing API. Upgrade the billing service to TeamFloPay/backend#640 or later.","api_error",{code:"MissingCheckoutSessionToken"});(O.length||E)&&x(R,{currency:E,products:O.map(C=>({code:C.code??C.providerItemId??C.providerPlanId,type:C.type,name:C.name??C.itemName??C.providerItemName??C.subscriptionName??C.providerPlanName??null,totalAmount:C.totalAmount,overrideAmount:C.overrideAmount,currency:C.currency??E}))});let Z=new URL(`${r.replace(/\/+$/,"")}/secure`);Z.searchParams.set("id",R);for(let[C,ee]of Object.entries(f))Z.searchParams.set(C,ee);if(b&&typeof window<"u"&&typeof document<"u"){let C=JSON.stringify({origin_url:d}),ee=window.location.hostname.split(".").slice(-2).join(".");document.cookie=`checkout_data=${encodeURIComponent(C)}; domain=.${ee}; path=/; max-age=3600; SameSite=Lax; Secure;`,document.cookie=`flopay_checkout_token=${encodeURIComponent(ue)}; domain=.${ee}; path=/; max-age=3600; SameSite=Lax; Secure;`}return typeof window<"u"&&(window.location.href=Z.toString()),{status:201,redirectUrl:Z.toString(),nonce:ue}}return L===204?(typeof window<"u"&&(window.location.href=l),{status:204}):{status:L}}async function Ge(n){let e=We(n),t=Ye(e);try{let r=await $e(n,t);return Je(e,r),r}catch(r){throw Te(e.reporter,r),r}finally{Q(e.reporter)}}function Ye(n){let e=!1;return t=>{if(e)return;e=!0;let r=`${Math.floor(t/100)}xx`;n.reporter.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:r}),n.reporter.performance({stage:"session_first_byte",durationMs:n.reporter.now()-n.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:r})}}function We(n){let e=new T({billingApiUrl:n.billingApiUrl,sdkVersion:m.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}}function Je(n,e){let t=`${Math.floor(e.status/100)}xx`;n.reporter.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_create",statusClass:t}),n.reporter.performance({stage:"session_complete",durationMs:n.reporter.now()-n.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:t})}function Te(n,e){let t=(0,m.classifyTelemetryFailure)(e,"CHECKOUT_SESSION_CREATE_FAILED");if(e instanceof m.FloPayError&&e.type==="validation_error"){n.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"});return}if(t.statusClass==="4xx"){n.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create",statusClass:"4xx"});return}n.error({...t,stage:"session_create",requestCategory:"session_create"})}function Q(n){n.flush().catch(()=>{}).finally(()=>n.destroy())}async function Qe(n){let{maxRetries:e=3,...t}=n,r=We(n),s=Ye(r);if(!Number.isFinite(e)||!Number.isInteger(e)||e<=0)throw r.reporter.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),Q(r.reporter),new Error("Number of retries must be greater than 0");let o={...t,idempotencyKey:(0,m.resolveIdempotencyKey)(t.idempotencyKey)},i;for(let a=0;a<=e;a++)try{let l=await $e(o,s);return Je(r,l),Q(r.reporter),l}catch(l){i=l;let d=l instanceof Error&&l.name==="AbortError",u=l instanceof m.FloPayError&&l.code===m.IDEMPOTENCY_IN_PROGRESS_CODE;if((d||u)&&a<e){r.reporter.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:a+1}),await new Promise(y=>setTimeout(y,100*Math.pow(2,a)));continue}throw Te(r.reporter,l),Q(r.reporter),l}throw Te(r.reporter,i),Q(r.reporter),i??new Error("Unknown error during checkout session creation")}0&&(module.exports={FloPay,FloPayElements,PaymentAPI,PciVaultCardCapture,StripeAdapter,cacheSessionDisplayData,clearSessionDisplayData,createCheckoutSession,createCheckoutSessionWithRetries,getSessionDisplayData,loadFloPay,toStripeAppearance,toStripeAppearanceTheme});
1
+ "use strict";var pe=Object.defineProperty;var Xe=Object.getOwnPropertyDescriptor;var Ze=Object.getOwnPropertyNames;var et=Object.prototype.hasOwnProperty;var tt=(n,e)=>{for(var t in e)pe(n,t,{get:e[t],enumerable:!0})},rt=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ze(e))!et.call(n,s)&&s!==t&&pe(n,s,{get:()=>e[s],enumerable:!(r=Xe(e,s))||r.enumerable});return n};var nt=n=>rt(pe({},"__esModule",{value:!0}),n);var It={};tt(It,{FloPay:()=>J,FloPayElements:()=>j,PaymentAPI:()=>A,PciVaultCardCapture:()=>F,StripeAdapter:()=>K,cacheSessionDisplayData:()=>x,clearSessionDisplayData:()=>oe,createCheckoutSession:()=>Ge,createCheckoutSessionWithRetries:()=>Qe,getSessionDisplayData:()=>ne,loadFloPay:()=>He,toStripeAppearance:()=>qe,toStripeAppearanceTheme:()=>Y});module.exports=nt(It);var S=require("@flopay/shared");var Fe=require("@stripe/stripe-js"),h=require("@flopay/shared");var c=require("@flopay/shared");function I(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 ot="flopay_session_display:";var te=new Map;function re(n){return`${ot}${n}`}function me(){if(typeof window>"u")return null;try{return window.sessionStorage}catch{return null}}function x(n,e,t){if(!n)return;let r=t?.ttlMs??36e5,s={data:e,expiresAt:Date.now()+r},o=me();if(o)try{o.setItem(re(n),JSON.stringify(s));return}catch{}te.set(n,s)}function ne(n){if(!n)return null;let e=me();if(e)try{let r=e.getItem(re(n));if(r){let s=JSON.parse(r);if(s&&typeof s.expiresAt=="number"&&s.expiresAt>Date.now())return s.data;e.removeItem(re(n))}}catch{}let t=te.get(n);if(t){if(t.expiresAt>Date.now())return t.data;te.delete(n)}return null}function oe(n){if(!n)return;te.delete(n);let e=me();if(e)try{e.removeItem(re(n))}catch{}}var T=require("@flopay/shared"),st="/v1/sdk-telemetry/events",ye=16,it=64,at=1500,be=1e3,lt=64,ct="00000000-0000-4000-8000-000000000000",dt={technical_error:8,lifecycle:32,expected_outcome:32,performance:24};function N(){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 ut(n){try{return new TextEncoder().encode(n).byteLength}catch{return n.length}}function pt(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 w(){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(/\/+$/,"")}${st}`,this.sdkPackage=e.sdkPackage??"@flopay/js",this.sdkVersion=e.sdkVersion,this.correlationId=N(),this.merchantEnabled=e.enabled!==!1,this.clock=e.clock??w,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,T.buildTelemetryLogEvent)({...this.checkoutContext,...e,eventId:N(),sequence:this.sequence++}))}error(e){if(!this.canCollect())return;let t=(0,T.buildTelemetryErrorEvent)({...this.checkoutContext,...e,eventId:ct,sequence:0}),r=pt(t),s=this.now();this.pruneReportedFailures(s);let o=this.reportedFailures.get(r);if(o!==void 0&&s>=o&&s-o<be){this.log({name:"operation.deduplicated",stage:e.stage,provider:e.provider,paymentMethodCategory:e.paymentMethodCategory,attempt:e.attempt});return}this.rememberReportedFailure(r,s),this.enqueue((0,T.buildTelemetryErrorEvent)({...this.checkoutContext,...e,eventId:N(),sequence:this.sequence++}))}performance(e){this.canCollect()&&this.enqueue((0,T.buildTelemetryPerformanceEvent)({...this.checkoutContext,...e,eventId:N(),sequence:this.sequence++}))}terminal(e){if(this.canCollect()&&(this.enqueue((0,T.buildTelemetryTerminalEvent)({...this.checkoutContext,...e,eventId:N(),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 w()}}pruneReportedFailures(e){for(let[t,r]of this.reportedFailures)(e<r||e-r>=be)&&this.reportedFailures.delete(t)}rememberReportedFailure(e,t){for(;this.reportedFailures.size>=lt;){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>=it||this.eventCounts[e.class]>=dt[e.class])){if(this.eventCounts[e.class]+=1,this.queue.push(e),this.queue.length>=ye){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,ye);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,ye);this.sendBatch(e)}}async sendBatch(e){if(!this.browserTransportAvailable||this.ingestionDisabled)return;let t=(0,T.serializeTelemetryBatch)(e,{correlationId:this.correlationId,sdkPackage:this.sdkPackage,sdkVersion:this.sdkVersion,batchId:N()});if(ut(t)>T.TELEMETRY_MAX_BATCH_BYTES)return;let r=typeof AbortController>"u"?null:new AbortController,s=null;try{let o=fetch(this.endpoint,{method:"POST",headers:{"content-type":"text/plain;charset=UTF-8"},body:t,credentials:"omit",keepalive:!0,referrerPolicy:"no-referrer",signal:r?.signal}).then(async l=>l.status!==202?null:(await l.json().catch(()=>null))?.status==="disabled"?"disabled":null).catch(()=>null),i=new Promise(l=>{s=setTimeout(()=>{r?.abort(),l(null)},at)});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)}},Me=Symbol.for("@flopay/js.telemetry.reporter-factory.v1"),ke=globalThis;ke[Me]===void 0&&Object.defineProperty(ke,Me,{configurable:!0,enumerable:!1,writable:!1,value:n=>new _(n)});var Re=1e3,mt=500,yt=15e3,ht=3e3,gt=1e4,ft=1e4;function Ae(n){return typeof n=="object"&&n!==null}function B(n,e){return I(n?.[e])}function Se(n,e){return Pe(n?.[e])}function Ct(n,e){let t=n?.[e];return typeof t=="number"&&Number.isFinite(t)?t:void 0}function he(n){return new Promise(e=>setTimeout(e,n))}function se(){return new c.FloPayError("Checkout is still processing. Please try again shortly.","api_error",{code:"checkout_processing_timeout"})}async function V(n,e){let t=await n.json().catch(()=>null),r=Ae(t?.error)?t.error:null,s=Se(t,"message")??Se(r,"message")??e,o=B(t,"code")??B(t,"gatewayErrorCode")??B(r,"code")??`http_${n.status}`;return new c.FloPayError(s,"api_error",{code:o,statusCode:n.status})}async function vt(n){if(n.status!==400&&n.status!==422)return;if(n.status===422)return"validation_rejected";let e=await n.clone().json().catch(()=>null);return Ae(e)&&Array.isArray(e.fields)?"validation_rejected":"payment_declined"}function Ee(n){return n===400||n===422}var G=2,_t=2;async function ie(n,e,t=G,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 he(150*2**o)}}function Tt(n){return"now"in n||"onFirstByte"in n||"onSessionCreateFailure"in n||"onRetry"in n}var D=class D{constructor(e,t={}){this.baseUrl=e.replace(/\/+$/,"");let r=Tt(t);this.telemetryHooks=r?t:void 0,this.directTelemetry=r||t.telemetry===!1?void 0:new _({billingApiUrl:this.baseUrl,sdkVersion:c.SDK_VERSION})}destroy(){this.directTelemetry?.destroy()}reportDirectFailure(e,t,r,s,o="unknown"){let i=(0,c.classifyTelemetryFailure)(e,t);this.directTelemetry?.error({...i,stage:r,requestCategory:s,paymentMethodCategory:o})}reportAccountSnapshotFailure(e,t){let r=(0,c.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()??w()}catch{return w()}}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={[c.FLO_SDK_VERSION_HEADER]:c.SDK_VERSION};t&&(s["x-checkout-session-token"]=t);try{let o=await ie(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}`,{headers:s},G,d=>{this.telemetryHooks?.onRetry?.("session_read",d),this.directTelemetry?.log({name:"operation.retry",stage:"session_read",requestCategory:"session_read",attempt:d})}),i=Math.max(0,this.telemetryTimestamp()-r);try{this.telemetryHooks?.onFirstByte?.(i)}catch{}let a=`${Math.floor(o.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}),!o.ok)throw await V(o,"Failed to get checkout session");let l=await o.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(o){throw this.directTelemetry?.error({...(0,c.classifyTelemetryFailure)(o,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"}),o}}cacheSessionDisplayData(e,t,r){x(e,t,r)}clearSessionDisplayData(e){oe(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(),ft);this.beginDirectTelemetryCheckout(e);let o=this.telemetryTimestamp();this.directTelemetry?.log({name:"vault.capture.requested",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card"});let i={"Content-Type":"application/json"};t&&(i["x-checkout-session-token"]=t);try{let a=await ie(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/vault/capture`,{method:"POST",headers:i,signal:r.signal},G,d=>{this.telemetryHooks?.onRetry?.("vault_capture",d),this.directTelemetry?.log({name:"operation.retry",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card",attempt:d})});if(!a.ok)throw await V(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()-o),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"2xx"}),this.toVaultBlock(l)}catch(a){let l=r.signal.aborted?new c.FloPayError("Timed out while loading the secure card form. Please try again.","api_error",{code:"vault_capture_timeout"}):a;throw this.reportDirectFailure(l,"VAULT_LOAD_FAILED","vault_request","vault_capture","card"),l}finally{clearTimeout(s)}}async getUnifiedCheckoutSession(e,t){let 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 c.FloPayError("processPayment requires `nonce` \u2014 pass the value returned from session creation.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let s=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.processing.started",stage:"processing",requestCategory:"process_payment"});let{nonce:o,...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":o},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 vt(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,c.telemetryStatusClass)(a.status),failureCategory:a.status>=500?"server_error":void 0}),a}try{let l=await this.resolveProcessResponse(a,t.sessionId,{...r,nonce:o});return this.directTelemetry?.log({name:"payment.processing.completed",stage:"processing",requestCategory:"process_payment",statusClass:(0,c.telemetryStatusClass)(l.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"process_payment",statusClass:(0,c.telemetryStatusClass)(l.status)}),l}catch(l){throw l instanceof c.FloPayError&&l.code==="checkout_processing_timeout"||this.reportDirectFailure(l,"PAYMENT_PROCESSING_FAILED","processing","process_payment"),l}}async patchAccountSnapshot(e,t,r,s){this.beginDirectTelemetryCheckout(e);let o=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.state_transition",stage:"processing",requestCategory:"account_snapshot"});let i=s?.timeoutMs??gt,a=new AbortController,l=()=>a.abort();s?.signal&&(s.signal.aborted?a.abort():s.signal.addEventListener("abort",l,{once:!0}));let d=setTimeout(()=>a.abort(),i);try{let u;try{u=await ie(`${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},G,y=>{this.telemetryHooks?.onRetry?.("account_snapshot",y),this.directTelemetry?.log({name:"operation.retry",stage:"processing",requestCategory:"account_snapshot",attempt:y})})}finally{clearTimeout(d),s?.signal?.removeEventListener("abort",l)}if(!u.ok)throw await V(u,"Failed to persist account snapshot");this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"account_snapshot",statusClass:"2xx"})}catch(u){throw this.reportAccountSnapshotFailure(u,s?.telemetryMode??"blocking"),u}}async createSessionIntent(e,t,r,s){if(!t)throw new c.FloPayError("createSessionIntent requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let o=r,i=o.paymentMethodType,a=typeof i=="string"&&i.trim().toLowerCase()==="card",l=typeof i=="string"&&i.length>0&&!a&&(typeof o.paymentMethodId=="string"||o.paymentMethodId===null),d=o.provider==="stripe"&&(o.paymentMethodCategory==="wallet"||o.paymentMethodCategory==="apm")&&(o.intentKind==="payment"||o.intentKind==="setup"),u=o.provider==="paypal"&&o.paymentMethodCategory==="wallet"&&o.paymentMethodType==="paypal"&&o.paymentMethodId===null&&o.intentKind==="payment";if(!l||!d&&!u)throw new c.FloPayError("Only wallet, APM, and PayPal session intents are supported.","validation_error",{code:"InvalidSessionIntentRequest"});let y=o.authorizationAttemptId;if(y!==void 0&&!(0,c.isUuidV4)(y))throw new c.FloPayError("authorizationAttemptId must be a v4 UUID identifying one buyer authorization attempt.","validation_error",{code:"InvalidAuthorizationAttemptId",param:"authorizationAttemptId"});let P=(0,c.isUuidV4)(y)?y:(0,c.randomUuidV4)();this.beginDirectTelemetryCheckout(e);let f=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.intent.started",stage:"processing",requestCategory:"intent_create"});let b={"Content-Type":"application/json","x-checkout-session-token":t,[c.IDEMPOTENCY_KEY_HEADER]:s?.idempotencyKey||P},M=!1;try{let k=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents`,{method:"POST",headers:b,body:JSON.stringify({...r,authorizationAttemptId:P}),signal:s?.signal});if(!k.ok){M=!0;let U=await V(k,"Failed to create checkout intent"),de=(0,c.classifyTelemetryFailure)(U,"PAYMENT_PROCESSING_FAILED");throw Ee(U.statusCode)?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"intent_create",statusClass:"4xx"}):this.directTelemetry?.error({...de,stage:"processing",requestCategory:"intent_create"}),U}let q=(await k.json()).data;if(!q||typeof q!="object")throw new c.FloPayError("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});let p=q,H=p.paymentMethodType,O=(p.paymentMethodCategory==="wallet"||p.paymentMethodCategory==="apm")&&typeof H=="string"&&H.trim().toLowerCase()!=="card"&&(typeof p.paymentMethodId=="string"||p.paymentMethodId===null)&&typeof p.providerObjectId=="string",E=p.provider==="stripe"&&(p.intentKind==="payment"||p.intentKind==="setup")&&typeof p.clientSecret=="string",$=p.provider==="paypal"&&p.paymentMethodCategory==="wallet"&&p.paymentMethodType==="paypal"&&p.paymentMethodId===null&&p.intentKind==="payment"&&(p.providerObjectType==="order"||p.providerObjectType==="subscription")&&p.clientSecret===null,ce=p.provider===r.provider&&p.paymentMethodCategory===r.paymentMethodCategory&&p.paymentMethodType===r.paymentMethodType&&p.paymentMethodId===r.paymentMethodId&&p.intentKind===r.intentKind;if(!O||!E&&!$||!ce)throw new c.FloPayError("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});return this.directTelemetry?.log({name:"payment.intent.completed",stage:"processing",requestCategory:"intent_create",statusClass:(0,c.telemetryStatusClass)(k.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-f),durationMode:"machine",requestCategory:"intent_create",statusClass:(0,c.telemetryStatusClass)(k.status)}),p}catch(k){throw M||this.reportDirectFailure(k,"PAYMENT_PROCESSING_FAILED","processing","intent_create"),k}}async reportSessionIntentDecline(e,t,r,s){if(!t)throw new c.FloPayError("reportSessionIntentDecline requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let o=r,i=o.providerDeclineReason,a=o.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),d=typeof a=="string"&&a.length>0&&a.trim().toLowerCase()!=="card"&&l,u=o.provider==="stripe"&&(o.paymentMethodCategory==="wallet"||o.paymentMethodCategory==="apm"),y=o.provider==="paypal"&&o.paymentMethodCategory==="wallet"&&o.paymentMethodType==="paypal";if(!d||!u&&!y)throw new c.FloPayError("Invalid non-card decline classification.","validation_error",{code:"InvalidSessionIntentDeclineRequest"});let P=y?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:i}:{provider:"stripe",paymentMethodCategory:o.paymentMethodCategory,paymentMethodType:o.paymentMethodType,providerDeclineReason:i},f=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:s?.signal});if(!f.ok)throw await V(f,"Failed to report checkout decline")}async getPaymentsByEmail(e,t){this.beginDirectTelemetryOperation();let r=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved"});let s=t?.page??1,o=t?.limit??1,i=new URLSearchParams({email:e,page:String(s),limit:String(o),sortField:"createdAt",sortDirection:"DESC"});try{let a=await fetch(`${this.baseUrl}/v1/payments?${i.toString()}`,{method:"GET",signal:t?.signal,keepalive:!0});if(!a.ok)throw new c.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){this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp();this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});try{let r=await this.createAndFetchSessionRequest(e,t);return this.adoptDirectTelemetryCheckout(r.data.session?.id),this.directTelemetry?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_create",statusClass:"2xx"}),this.directTelemetry?.performance({stage:"session_create",durationMs:this.telemetryTimestamp()-t,durationMode:"machine",requestCategory:"session_create",statusClass:"2xx"}),r}catch(r){if(!(r instanceof c.FloPayError&&r.code==="session_auto_completed"))try{this.telemetryHooks?.onSessionCreateFailure?.(r)}catch{}let s=(0,c.classifyTelemetryFailure)(r,"CHECKOUT_SESSION_CREATE_FAILED");throw r instanceof c.FloPayError&&r.type==="validation_error"?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}):r instanceof c.FloPayError&&Ee(r.statusCode)?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create",statusClass:"4xx"}):r instanceof c.FloPayError&&r.code==="session_auto_completed"||this.directTelemetry?.error({...s,stage:"session_create",requestCategory:"session_create"}),r}}async createAndFetchSessionRequest(e,t){let r=e.products??(0,c.foldIntoProducts)(e.items,e.subscriptions),s=(0,c.resolveSessionCurrency)(e.currency,e.items,e.subscriptions,r);if(!s)throw new c.FloPayError("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});let o={clientId:e.clientId,checkoutVersion:c.SDK_VERSION,successUrl:e.successUrl,cancelUrl:e.cancelUrl,currency:s,checkoutMode:e.checkoutMode??"full",products:r.map(f=>(0,c.buildProductPayload)(f,s)),accountData:{userId:e.account.userId,firstName:e.account.firstName??null,lastName:e.account.lastName??null,email:e.account.email,country:e.account.country??null,gender:e.account.gender??null,city:e.account.city??null,state:e.account.state??null,zip:e.account.zip??null,addressLine1:e.account.addressLine1??null,addressLine2:e.account.addressLine2??null},couponCodes:e.couponCodes??[]};e.tokenizedData&&(o.tokenizedData=e.tokenizedData),e.tagsData&&(o.tagsData=e.tagsData),e.utmMetadata?.length&&(o.utmMetadata=e.utmMetadata),e.avsCheck!==void 0&&(o.avsCheck=e.avsCheck),e.checkoutType&&(o.checkoutType=e.checkoutType),e.checkoutLayout&&(o.checkoutLayout=e.checkoutLayout),e.avsConfig&&(o.avsConfig=e.avsConfig);let i={"Content-Type":"application/json",[c.FLO_SDK_VERSION_HEADER]:c.SDK_VERSION},a=(0,c.resolveIdempotencyKey)(e.idempotencyKey);a&&(i[c.IDEMPOTENCY_KEY_HEADER]=a);let l,d=!1;for(let f=0;;f++){if(l=await ie(`${this.baseUrl}/v1/checkouts/sessions?expand=true`,{method:"POST",headers:i,body:JSON.stringify(o)},G,M=>{this.telemetryHooks?.onRetry?.("session_create",M),this.directTelemetry?.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:M})}),!d){d=!0;let M=`${Math.floor(l.status/100)}xx`;this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:M}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:this.telemetryTimestamp()-t,durationMode:"machine",requestCategory:"session_create",statusClass:M})}if(l.status===204)throw new c.FloPayError("Session auto-completed \u2014 payment method already on file","api_error",{code:"session_auto_completed"});if(l.ok)break;let b=await V(l,"Failed to create checkout session");if(b.code===c.IDEMPOTENCY_IN_PROGRESS_CODE&&f<_t){try{this.telemetryHooks?.onRetry?.("session_create",f+1),this.directTelemetry?.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:f+1})}catch{}await he(150*2**f);continue}throw b}let u=await l.json();if(u.data&&"gateways"in u.data){this.autoCacheDisplayData(u.data.uuid,e);let f=this.mergeCachedDisplayData(u.data),b=this.normalizeRawSession(f);return u.vault&&b.data.session&&(b.data.session.vault=this.toVaultBlock(u.vault)),{...b,autoProcessingError:u.autoProcessingError,autoProcessingAttempted:u.autoProcessingAttempted,autoProcessingPending:u.autoProcessingPending}}let y=u.data?.uuid;if(!y)throw new c.FloPayError("No session ID returned","api_error",{code:"InvalidCheckoutSessionResponse"});return this.autoCacheDisplayData(y,e),this.adoptDirectTelemetryCheckout(y),{...await this.getUnifiedCheckoutSession(y),autoProcessingError:u.autoProcessingError,autoProcessingAttempted:u.autoProcessingAttempted,autoProcessingPending:u.autoProcessingPending}}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??yt,o=Date.now()+s,i=this.clampRetryAfterMs(t?.initialDelayMs??Re),a=0;try{for(;;){let l=o-Date.now();if(l<=0)throw se();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 he(Math.min(i,l)),Date.now()>=o)throw se()}let d=await this.getUnifiedCheckoutSession(e,t?.nonce),u=d.data.session?.status;if(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"}),d;if(Date.now()>=o)throw se();i=this.clampRetryAfterMs(Math.max(i*2,mt))}}catch(l){throw l instanceof c.FloPayError&&l.code==="checkout_processing_timeout"&&this.reportDirectFailure(l,"RECOVERY_FAILED","recovery","session_read","saved"),l}}normalizeRawSession(e){let t=e.gateways??{},r=[],s={session:this.toCheckoutSession(e)},o=t.stripe;if(o?.publishableKey){r.push("stripe");let l=[e.stripeClientSecret,o.stripeClientSecret].find(d=>typeof d=="string"&&d.length>0);s.stripe={clientSecret:l??"",publishableKey:o.publishableKey??void 0,paypalPublishableKey:o.paypalPublishableKey??void 0,environment:o.environment,enabledPaymentMethods:Array.isArray(o.enabledPaymentMethods)?o.enabledPaymentMethods.filter(d=>typeof d=="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((d,u)=>d+(u.overrideAmount??u.totalAmount??0),0),o=r?e.totalAmount:s,i=Math.round(o*100),a=e.currency??t[0]?.currency??"USD",l=t.some(d=>d.type==="subscription")?"subscription":"payment";return{id:e.uuid,clientSecret:e.nonce,mode:l,status:this.toCheckoutSessionStatus(e.status),amount:i,currency:a,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(d=>({...d,totalAmount:typeof d.totalAmount=="number"?d.totalAmount:void 0,overrideAmount:typeof d.overrideAmount=="number"?d.overrideAmount:null,currency:typeof d.currency=="string"?d.currency:void 0,metadata:d.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==="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"});throw i.data.session?.status==="expired"?new c.FloPayError("Checkout session has expired.","api_error",{code:"checkout_session_expired"}):se()}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:B(e,"sessionId")??r,retryAfterMs:this.clampRetryAfterMs(Ct(e,"retryAfterMs")??i??Re),statusUrl:B(e,"statusUrl"),sessionUrl:B(e,"sessionUrl")}}clampRetryAfterMs(e){return Math.max(0,Math.min(e,ht))}autoCacheDisplayData(e,t){if(!e)return;let r=t.products??(0,c.foldIntoProducts)(t.items,t.subscriptions);if(r.length===0&&!t.currency)return;let s=t.products!==void 0,o=(0,c.resolveSessionCurrency)(t.currency,s?void 0:t.items,s?void 0:t.subscriptions,r);x(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=ne(e.uuid),r=new Map,s=i=>i?`code:${i}`:void 0;for(let i of t?.products??[]){let a=s(i.code);a&&r.set(a,i)}let o=(e.products??[]).map(i=>{let a=s(i.code),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:o}}};D.activeVaultCaptureRequests=new Map;var A=D;function Ie(n,e){let t=A;return new t(n,e)}function xe(n){return{payment:"payment",address:"address"}[n]}function Y(n){switch(n){case"night":return"night";case"flat":return"flat";default:return"stripe"}}function qe(n){return{...n,theme:Y(n.theme)}}function ge(n){return n?JSON.stringify(n.map(e=>e.trim().toLowerCase())):null}function De(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 wt(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,Fe.loadStripe)(e.publishableKey,{locale:e.locale??"auto"});if(!t)throw new h.FloPayError("Failed to initialize Stripe. Check your publishable key.","authentication_error");this.stripe=t}getElements(e){if(!this.stripe)throw new h.FloPayError("StripeAdapter not initialized. Call initialize() first.","api_error");let t=e?.appearance?{theme:Y(e.appearance.theme),variables:e.appearance.variables,rules:e.appearance.rules}:void 0,r=t?JSON.stringify(t):null,s=ge(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,a=e?.amount??0,l=(e?.currency??"usd").toLowerCase(),d=e?.paymentMethodCreation??"manual";e?.clientSecret?i={clientSecret:e.clientSecret}:a>0?(i={mode:"payment",amount:a,currency:l,paymentMethodCreation:d},e?.setupFutureUsage&&(i.setupFutureUsage=e.setupFutureUsage)):i={mode:"setup",currency:l,paymentMethodCreation:d},!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 h.FloPayError("StripeAdapter not initialized. Call initialize() first.","api_error");let r,s=!1;if((0,h.isSetupIntentClientSecret)(e)){let{setupIntent:l,error:d}=await this.stripe.retrieveSetupIntent(e);r=l,s=!!d}else{let{paymentIntent:l,error:d}=await this.stripe.retrievePaymentIntent(e);r=l,s=!!d}let o=r?.payment_method_types;if(s||!Array.isArray(o))throw new h.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(o.some(l=>typeof l!="string"||!i.has(l.trim().toLowerCase()))||o.length===0)throw new h.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(d=>d.trim()).filter(d=>d&&d.toLowerCase()!=="card");if(!l?.length)throw new h.FloPayError("At least one supported non-card payment method is required.","validation_error",{param:"paymentMethodTypes"});if(r={...t,paymentMethodTypes:l},r.clientSecret){let d=ge(l);this.elements&&this.appliedClientSecret===r.clientSecret&&this.appliedPaymentMethodTypesKey===d&&this.verifiedClientSecret===r.clientSecret&&this.verifiedPaymentMethodTypesKey===d||await this.assertClientSecretPaymentMethods(r.clientSecret,l)}}let s=this.getElements(r);e==="payment"&&r.clientSecret&&(this.verifiedClientSecret=r.clientSecret,this.verifiedPaymentMethodTypesKey=ge(r.paymentMethodTypes));let o=xe(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=s.create(o,i);return De(a)}getElement(e){if(!this.elements)return null;let t=xe(e),r=this.elements.getElement(t);return r?De(r):null}async submitElements(){if(!this.stripe||!this.elements)return{error:new h.FloPayError("Stripe not initialized","api_error")};let{error:e}=await this.elements.submit();return e?{error:new h.FloPayError(e.message??"Validation failed","validation_error")}:{}}async confirmPayment(e){if(!this.stripe||!this.elements)throw new h.FloPayError("StripeAdapter not initialized or no elements created.","api_error");let t=e.billingDetails,r=t?wt(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 h.FloPayError(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 h.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 h.FloPayError("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 h.FloPayError(o.message??"PayPal payment failed","validation_error",{code:o.code})}}let r;try{let o=await new A(t).createSessionIntent(e.sessionId,e.nonce??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"});if(o.provider!=="stripe")throw new h.FloPayError("Invalid provider returned for PayPal intent","api_error");r=o.clientSecret}catch(o){return{status:"failed",error:o instanceof h.FloPayError?o:new h.FloPayError("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 A(t).reportSessionIntentDecline(e.sessionId,e.nonce,{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:s.code??"provider_declined"})}catch{}return{status:"failed",error:new h.FloPayError(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 h.FloPayError("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 h.FloPayError(i.message??"Failed to retrieve PayPal payment","api_error")};if(o&&(o.status==="requires_capture"||o.status==="succeeded")){let a=typeof o.payment_method=="string"?o.payment_method:o.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:o.status,paymentIntentId:o.id,paymentMethodId:a}}return{status:"failed",error:new h.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:Y(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 g=require("@flopay/shared");var Oe=require("@flopay/shared"),j=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 Oe.FloPayError("At least one supported non-card payment method is required.","validation_error",{param:"paymentMethodTypes"});r.paymentMethodTypes=a}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()}};var v=require("@flopay/shared");var fe="flopay-vault",Ue={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 W(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 ae(n,e){return(0,v.buildTelemetryLogEvent)({eventId:"11111111-1111-4111-8111-111111111111",name:n,stage:e,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}function Le(n){return n?{errorCode:"VAULT_SUBMIT_FAILED",stage:"vault_submit",failureCategory:"provider_runtime"}:{errorCode:"VAULT_LOAD_FAILED",stage:"vault_mount",failureCategory:"provider_runtime"}}function Pt(n,e){if(n==="complete"||n==="decline")return(0,v.buildTelemetryTerminalEvent)({eventId:"22222222-2222-4222-8222-222222222222",outcome:n==="complete"?"payment_succeeded":"payment_declined",sequence:0,provider:"pcivault",paymentMethodCategory:"card"});if(n==="error"){let s=Le(e);return(0,v.buildTelemetryErrorEvent)({eventId:"33333333-3333-4333-8333-333333333333",...s,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}let[t,r]=Ue[n];return ae(t,r)}function bt(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===fe&&(e.type==="ready"||e.type==="submitting"||e.type==="blocked"||e.type==="complete"||e.type==="decline"||e.type==="error"||e.type==="action_required")}function Mt(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===fe&&e.type==="validation"&&Array.isArray(e.messages)}function kt(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===fe&&e.type==="resize"&&typeof e.height=="number"&&Number.isFinite(e.height)}var F=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,v.resolveBillingApiUrl)(),sdkVersion:v.SDK_VERSION}):void 0)}async mount(e,t){if(this.ownsTelemetryReporter&&!this.telemetryReporter&&(this.telemetryReporter=new _({billingApiUrl:(0,v.resolveBillingApiUrl)(),sdkVersion:v.SDK_VERSION})),this.mountStartedAt=this.telemetryReporter?.now?.()??w(),this.vaultReadyReported=!1,this.submissionStarted=!1,this.submissionStartedAt=null,typeof window>"u"||typeof document>"u")throw this.reportVaultLoadFailure(),new v.FloPayError("The vault card form is only available in the browser.","api_error",{code:"card_capture_no_window"});if(!t?.html||!t.html.trim())throw this.reportVaultLoadFailure(),new v.FloPayError("No vault capture widget HTML was provided to mount the secure card form.","api_error",{code:"card_capture_no_widget_html"});this.container=e,this.messageToken=t.messageToken??null,this.expectedOrigin=t.expectedOrigin??this.config.expectedOrigin??null,this.theme=t.theme??null;try{this.attachMessageListener(),this.injectWidget(e,t.html)}catch(r){throw this.reportVaultLoadFailure(),r}this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),W(ae("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(kt(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;this.applyHeight(r.height);return}if(Mt(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;let a=r.messages.filter(l=>typeof l=="string"&&l.trim()).join(" ");this.emit("validation",{sessionId:this.config.sessionId,message:a||void 0});return}if(!bt(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={sessionId:r.sessionId??this.config.sessionId,intentId:r.intentId,declineReason:r.declineReason,message:r.message,nextActionRedirectUrl:r.nextActionRedirectUrl};r.type==="submitting"&&(this.submissionStarted=!0,this.submissionStartedAt=this.telemetryReporter?.now?.()??w()),W(Pt(r.type,this.submissionStarted)),this.reportOutcome(r.type),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(),this.emit(r.type,i)};this.messageHandler=e,window.addEventListener("message",e)}reportOutcome(e){let t=this.telemetryReporter;if(!t)return;if(e==="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"})),e==="complete"||e==="decline"){t.log({name:"vault.terminal",stage:"completion",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:e==="complete"?"payment_succeeded":"payment_declined",provider:"pcivault",paymentMethodCategory:"card"});return}if(e==="error"){let o=Le(this.submissionStarted);t.log({name:"vault.terminal",stage:o.stage,provider:"pcivault",paymentMethodCategory:"card"}),t.error({...o,provider:"pcivault",paymentMethodCategory:"card"});return}if(e==="action_required"){t.log({name:"vault.action.required",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"}),t.log({name:"vault.three_ds.handoff",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"});let o=this.submissionStartedAt;this.submissionStartedAt=null,o!==null&&t.performance({stage:"three_ds_handoff",durationMs:Math.max(0,t.now()-o),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:"action_required",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"});return}let[r,s]=Ue[e];t.log({name:r,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 s=document.createElement("button");s.type="button",s.setAttribute("aria-label","Close card authentication"),s.textContent="\xD7",s.style.cssText=["position:fixed","top:20px","right:20px","width:40px","height:40px","border:0","border-radius:9999px","background:#fff","color:#0f172a","font-size:28px","line-height:40px","cursor:pointer","box-shadow:0 4px 14px rgba(0,0,0,0.25)"].join(";"),s.addEventListener("click",()=>this.abandonActionRequiredOverlay()),t.appendChild(s),t.addEventListener("click",i=>{i.target===t&&this.abandonActionRequiredOverlay()});let o=i=>{if(i.source!==r.contentWindow)return;let a=i.data;if(!a||typeof a!="object")return;let l=a;l.source==="flopay-vault-3ds-return"&&(W(ae("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",o),this.threeDsReturnHandler=o,document.body.appendChild(t),this.actionOverlay=t,W(ae("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,v.buildTelemetryTerminalEvent)({eventId:"77777777-7777-4777-8777-777777777777",outcome:"customer_abandoned",stage:"three_ds_handoff",sequence:0,provider:"pcivault",paymentMethodCategory:"card"});W(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 Ne(n,e){let t=F;return new t(n,{reporter:e})}var Ve=Symbol.for("@flopay/js.telemetry.bridge.v1");function Be(n,e,t){let r=()=>e?.now()??t();Object.defineProperty(n,Ve,{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 Ke(n){return n[Ve]}function z(n){if(!n)return!1;let e=n.code?.toLowerCase()??"";return!!n.declineCode||e.includes("declin")}function Rt(n){return n==="stripe"||n==="paypal"||n==="pcivault"?n:"other"}var J=class{constructor(e,t,r){this.currentElements=null;this.provider=e,this.config=t,this.telemetryReporter=r??new _({billingApiUrl:(0,g.resolveBillingApiUrl)(t.billingApiUrl),sdkVersion:g.SDK_VERSION,enabled:t.telemetry!==!1}),Be(this,this.telemetryReporter,w)}now(){return this.telemetryReporter?.now?.()??w()}elements(e){return this.currentElements&&this.currentElements.destroy(),this.currentElements=new j(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?Ne({sessionId:e?.sessionId},this.telemetryReporter):new F({sessionId:e?.sessionId,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"&&(z(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 g.FloPayError&&z(r))this.telemetryReporter?.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"});else if(r instanceof g.FloPayError&&r.type==="validation_error")this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal"});else{let s=(0,g.classifyTelemetryFailure)(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"}):z(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 g.FloPayError&&z(t))this.telemetryReporter?.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"});else if(t instanceof g.FloPayError&&t.type==="validation_error")this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal"});else{let r=(0,g.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 g.FloPayError("A supported non-card payment method is required.","validation_error",{param:"paymentMethodType"});let t=this.now(),r=Rt(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}):z(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 g.FloPayError&&z(s)?this.telemetryReporter?.terminal({outcome:"payment_declined",provider:r,paymentMethodCategory:e.paymentMethodCategory}):s instanceof g.FloPayError&&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 g.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 g.FloPayError("Session not found","api_error");return r.data.session}async retrieveUnifiedSession(e,t){if(!e)throw new g.FloPayError("sessionId is required.","validation_error",{param:"sessionId"});let r=(0,g.resolveBillingApiUrl)(t??this.config.billingApiUrl),s=this.now();this.telemetryReporter?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let o,i=Ie(r,{now:()=>this.telemetryReporter?.now()??w(),onFirstByte:a=>{o=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 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"}),a}catch(a){let l=(0,g.classifyTelemetryFailure)(a,a instanceof g.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()-s,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=J;return new r(n,e,t)}var ze=new Map;function Ce(n){return Array.isArray(n)?n.map(Ce):n&&typeof n=="object"?Object.fromEntries(Object.entries(n).filter(([,e])=>e!==void 0).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,Ce(t)])):n}function St(n,e){return JSON.stringify([n,(0,S.resolveBillingApiUrl)(e?.billingApiUrl),e?.telemetry!==!1,e?.locale??"auto",e?.apiVersion??null,Ce(e?.appearance??null)])}var le=new Map;async function He(n,e){if(!n){let a=new _({billingApiUrl:(0,S.resolveBillingApiUrl)(e?.billingApiUrl),sdkVersion:S.SDK_VERSION,enabled:e?.telemetry!==!1});throw a.error({errorCode:"CONFIGURATION_INVALID",stage:"sdk_initialize",paymentMethodCategory:"unknown"}),a.flush().catch(()=>{}).finally(()=>a.destroy()),new S.FloPayError("A publishable key is required to initialize FloPay.","validation_error",{param:"publishableKey"})}let t=St(n,e),r=ze.get(t);if(r)return e?.telemetry!==!1&&Ke(r)?.log({name:"sdk.cache.hit",stage:"sdk_initialize"}),r;let s=le.get(t);if(s)return s;let o={...e,publishableKey:n},i=(async()=>{let a=new _({billingApiUrl:(0,S.resolveBillingApiUrl)(o.billingApiUrl),sdkVersion:S.SDK_VERSION,enabled:o.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 d=new K;try{await d.initialize(o)}catch(P){throw a.error({errorCode:"SDK_INITIALIZATION_FAILED",failureCategory:"provider_runtime",stage:"sdk_initialize",provider:"stripe",paymentMethodCategory:"unknown"}),a.destroy(),P}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"});let u=a.now()-l;a.performance({stage:"sdk_initialize",durationMs:u,durationMode:"machine",provider:"stripe"}),a.performance({stage:"provider_ready",durationMs:u,durationMode:"machine",provider:"stripe"});let y=je(d,o,a);return ze.set(t,y),y})();le.set(t,i);try{return await i}finally{le.get(t)===i&&le.delete(t)}}var m=require("@flopay/shared");var ve=5;function Et(n,e){let t=e?.error,r=I(e?.code)??I(t?.code)??`http_${n}`,s=I(e?.message)??I(t?.message)??At(r,n);return new m.FloPayError(s,"api_error",{code:r,statusCode:n})}function At(n,e){switch(n){case"CouponLimitExceeded":return`Too many coupon codes \u2014 a checkout session accepts at most ${ve}.`;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 $e(n,e){let{billingApiUrl:t,checkoutBaseUrl:r,items:s=[],subscriptions:o=[],products:i,account:a,successUrl:l,cancelUrl:d,checkoutMode:u="confirm",couponCodes:y=[],tagsData:P,redirectParams:f={},setCookie:b=!0,timeoutMs:M=12e3,clientId:k,currency:Te,utmMetadata:q,idempotencyKey:p}=n,H=(0,m.resolveIdempotencyKey)(p);if(y.length>ve)throw new m.FloPayError(`Too many coupon codes \u2014 a checkout session accepts at most ${ve}.`,"validation_error",{code:"CouponLimitExceeded",param:"couponCodes"});let O=i??(0,m.foldIntoProducts)(s,o),E=(0,m.resolveSessionCurrency)(Te,s,o,O);if(!E)throw new m.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 $={clientId:k,checkoutVersion:m.SDK_VERSION,successUrl:l,cancelUrl:d,currency:E,checkoutMode:u,products:O.map(R=>(0,m.buildProductPayload)(R,E)),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:y};P&&($.tagsData=P),q?.length&&($.utmMetadata=q);let ce=`${t.replace(/\/+$/,"")}/v1/checkouts/sessions`,U=new AbortController,de=setTimeout(()=>U.abort(),M),we={"Content-Type":"application/json"};H&&(we[m.IDEMPOTENCY_KEY_HEADER]=H);let L,X;try{let R=await fetch(ce,{method:"POST",headers:we,body:JSON.stringify($),signal:U.signal});try{e?.(R.status)}catch{}L=R.status;try{X=await R.json()}catch{}}finally{clearTimeout(de)}if(L>=400)throw Et(L,X);if(L===201){let R=X?.data?.uuid,ue=X?.data?.nonce;if(!R)throw new Error("Checkout session created but no UUID was returned by the billing API");if(!ue)throw new m.FloPayError("Checkout session created but no `nonce` was returned by the billing API. Upgrade the billing service to TeamFloPay/backend#640 or later.","api_error",{code:"MissingCheckoutSessionToken"});(O.length||E)&&x(R,{currency:E,products:O.map(C=>({code:C.code??C.providerItemId??C.providerPlanId,type:C.type,name:C.name??C.itemName??C.providerItemName??C.subscriptionName??C.providerPlanName??null,totalAmount:C.totalAmount,overrideAmount:C.overrideAmount,currency:C.currency??E}))});let Z=new URL(`${r.replace(/\/+$/,"")}/secure`);Z.searchParams.set("id",R);for(let[C,ee]of Object.entries(f))Z.searchParams.set(C,ee);if(b&&typeof window<"u"&&typeof document<"u"){let C=JSON.stringify({origin_url:d}),ee=window.location.hostname.split(".").slice(-2).join(".");document.cookie=`checkout_data=${encodeURIComponent(C)}; domain=.${ee}; path=/; max-age=3600; SameSite=Lax; Secure;`,document.cookie=`flopay_checkout_token=${encodeURIComponent(ue)}; domain=.${ee}; path=/; max-age=3600; SameSite=Lax; Secure;`}return typeof window<"u"&&(window.location.href=Z.toString()),{status:201,redirectUrl:Z.toString(),nonce:ue}}return L===204?(typeof window<"u"&&(window.location.href=l),{status:204}):{status:L}}async function Ge(n){let e=We(n),t=Ye(e);try{let r=await $e(n,t);return Je(e,r),r}catch(r){throw _e(e.reporter,r),r}finally{Q(e.reporter)}}function Ye(n){let e=!1;return t=>{if(e)return;e=!0;let r=`${Math.floor(t/100)}xx`;n.reporter.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:r}),n.reporter.performance({stage:"session_first_byte",durationMs:n.reporter.now()-n.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:r})}}function We(n){let e=new _({billingApiUrl:n.billingApiUrl,sdkVersion:m.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}}function Je(n,e){let t=`${Math.floor(e.status/100)}xx`;n.reporter.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_create",statusClass:t}),n.reporter.performance({stage:"session_complete",durationMs:n.reporter.now()-n.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:t})}function _e(n,e){let t=(0,m.classifyTelemetryFailure)(e,"CHECKOUT_SESSION_CREATE_FAILED");if(e instanceof m.FloPayError&&e.type==="validation_error"){n.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"});return}if(t.statusClass==="4xx"){n.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create",statusClass:"4xx"});return}n.error({...t,stage:"session_create",requestCategory:"session_create"})}function Q(n){n.flush().catch(()=>{}).finally(()=>n.destroy())}async function Qe(n){let{maxRetries:e=3,...t}=n,r=We(n),s=Ye(r);if(!Number.isFinite(e)||!Number.isInteger(e)||e<=0)throw r.reporter.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),Q(r.reporter),new Error("Number of retries must be greater than 0");let o={...t,idempotencyKey:(0,m.resolveIdempotencyKey)(t.idempotencyKey)},i;for(let a=0;a<=e;a++)try{let l=await $e(o,s);return Je(r,l),Q(r.reporter),l}catch(l){i=l;let d=l instanceof Error&&l.name==="AbortError",u=l instanceof m.FloPayError&&l.code===m.IDEMPOTENCY_IN_PROGRESS_CODE;if((d||u)&&a<e){r.reporter.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:a+1}),await new Promise(y=>setTimeout(y,100*Math.pow(2,a)));continue}throw _e(r.reporter,l),Q(r.reporter),l}throw _e(r.reporter,i),Q(r.reporter),i??new Error("Unknown error during checkout session creation")}0&&(module.exports={FloPay,FloPayElements,PaymentAPI,PciVaultCardCapture,StripeAdapter,cacheSessionDisplayData,clearSessionDisplayData,createCheckoutSession,createCheckoutSessionWithRetries,getSessionDisplayData,loadFloPay,toStripeAppearance,toStripeAppearanceTheme});
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{FloPayError as Gt,resolveBillingApiUrl as Ce,SDK_VERSION as Ze}from"@flopay/shared";import{loadStripe as Ft}from"@stripe/stripe-js";import{FloPayError as y,isSetupIntentClientSecret as qt}from"@flopay/shared";import{FloPayError as m,SDK_VERSION as ee,FLO_SDK_VERSION_HEADER as Ee,IDEMPOTENCY_KEY_HEADER as Ae,IDEMPOTENCY_IN_PROGRESS_CODE as _t,buildProductPayload as wt,classifyTelemetryFailure as K,foldIntoProducts as Ie,isUuidV4 as xe,randomUuidV4 as Pt,resolveIdempotencyKey as bt,resolveSessionCurrency as De,telemetryStatusClass as j}from"@flopay/shared";function k(n){return typeof n=="string"&&n.trim()?n:void 0}function be(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 at="flopay_session_display:";var X=new Map;function Z(n){return`${at}${n}`}function de(){if(typeof window>"u")return null;try{return window.sessionStorage}catch{return null}}function D(n,e,t){if(!n)return;let r=t?.ttlMs??36e5,s={data:e,expiresAt:Date.now()+r},o=de();if(o)try{o.setItem(Z(n),JSON.stringify(s));return}catch{}X.set(n,s)}function ue(n){if(!n)return null;let e=de();if(e)try{let r=e.getItem(Z(n));if(r){let s=JSON.parse(r);if(s&&typeof s.expiresAt=="number"&&s.expiresAt>Date.now())return s.data;e.removeItem(Z(n))}}catch{}let t=X.get(n);if(t){if(t.expiresAt>Date.now())return t.data;X.delete(n)}return null}function pe(n){if(!n)return;X.delete(n);let e=de();if(e)try{e.removeItem(Z(n))}catch{}}import{buildTelemetryErrorEvent as Me,buildTelemetryLogEvent as lt,buildTelemetryPerformanceEvent as ct,buildTelemetryTerminalEvent as dt,serializeTelemetryBatch as ut,TELEMETRY_MAX_BATCH_BYTES as pt}from"@flopay/shared";var mt="/v1/sdk-telemetry/events",me=16,yt=64,ht=1500,ke=1e3,gt=64,ft="00000000-0000-4000-8000-000000000000",Ct={technical_error:8,lifecycle:32,expected_outcome:32,performance:24};function F(){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 vt(n){try{return new TextEncoder().encode(n).byteLength}catch{return n.length}}function Tt(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 C(){return globalThis.performance?.now()??0}var f=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(/\/+$/,"")}${mt}`,this.sdkPackage=e.sdkPackage??"@flopay/js",this.sdkVersion=e.sdkVersion,this.correlationId=F(),this.merchantEnabled=e.enabled!==!1,this.clock=e.clock??C,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(lt({...this.checkoutContext,...e,eventId:F(),sequence:this.sequence++}))}error(e){if(!this.canCollect())return;let t=Me({...this.checkoutContext,...e,eventId:ft,sequence:0}),r=Tt(t),s=this.now();this.pruneReportedFailures(s);let o=this.reportedFailures.get(r);if(o!==void 0&&s>=o&&s-o<ke){this.log({name:"operation.deduplicated",stage:e.stage,provider:e.provider,paymentMethodCategory:e.paymentMethodCategory,attempt:e.attempt});return}this.rememberReportedFailure(r,s),this.enqueue(Me({...this.checkoutContext,...e,eventId:F(),sequence:this.sequence++}))}performance(e){this.canCollect()&&this.enqueue(ct({...this.checkoutContext,...e,eventId:F(),sequence:this.sequence++}))}terminal(e){if(this.canCollect()&&(this.enqueue(dt({...this.checkoutContext,...e,eventId:F(),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 C()}}pruneReportedFailures(e){for(let[t,r]of this.reportedFailures)(e<r||e-r>=ke)&&this.reportedFailures.delete(t)}rememberReportedFailure(e,t){for(;this.reportedFailures.size>=gt;){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>=yt||this.eventCounts[e.class]>=Ct[e.class])){if(this.eventCounts[e.class]+=1,this.queue.push(e),this.queue.length>=me){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,me);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,me);this.sendBatch(e)}}async sendBatch(e){if(!this.browserTransportAvailable||this.ingestionDisabled)return;let t=ut(e,{correlationId:this.correlationId,sdkPackage:this.sdkPackage,sdkVersion:this.sdkVersion,batchId:F()});if(vt(t)>pt)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 l=>l.status!==202?null:(await l.json().catch(()=>null))?.status==="disabled"?"disabled":null).catch(()=>null),i=new Promise(l=>{s=setTimeout(()=>{r?.abort(),l(null)},ht)});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)}},Re=Symbol.for("@flopay/js.telemetry.reporter-factory.v1"),Se=globalThis;Se[Re]===void 0&&Object.defineProperty(Se,Re,{configurable:!0,enumerable:!1,writable:!1,value:n=>new f(n)});var Fe=1e3,Mt=500,kt=15e3,Rt=3e3,St=1e4,Et=1e4;function Ue(n){return typeof n=="object"&&n!==null}function O(n,e){return k(n?.[e])}function qe(n,e){return be(n?.[e])}function At(n,e){let t=n?.[e];return typeof t=="number"&&Number.isFinite(t)?t:void 0}function ye(n){return new Promise(e=>setTimeout(e,n))}function te(){return new m("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=Ue(t?.error)?t.error:null,s=qe(t,"message")??qe(r,"message")??e,o=O(t,"code")??O(t,"gatewayErrorCode")??O(r,"code")??`http_${n.status}`;return new m(s,"api_error",{code:o,statusCode:n.status})}async function It(n){if(n.status!==400&&n.status!==422)return;if(n.status===422)return"validation_rejected";let e=await n.clone().json().catch(()=>null);return Ue(e)&&Array.isArray(e.fields)?"validation_rejected":"payment_declined"}function Oe(n){return n===400||n===422}var z=2,xt=2;async function re(n,e,t=z,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 ye(150*2**o)}}function Dt(n){return"now"in n||"onFirstByte"in n||"onSessionCreateFailure"in n||"onRetry"in n}var R=class R{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 f({billingApiUrl:this.baseUrl,sdkVersion:ee})}destroy(){this.directTelemetry?.destroy()}reportDirectFailure(e,t,r,s,o="unknown"){let i=K(e,t);this.directTelemetry?.error({...i,stage:r,requestCategory:s,paymentMethodCategory:o})}reportAccountSnapshotFailure(e,t){let r=K(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()??C()}catch{return C()}}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={[Ee]:ee};t&&(s["x-checkout-session-token"]=t);try{let o=await re(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}`,{headers:s},z,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(o.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}),!o.ok)throw await q(o,"Failed to get checkout session");let l=await o.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(o){throw this.directTelemetry?.error({...K(o,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"}),o}}cacheSessionDisplayData(e,t,r){D(e,t,r)}clearSessionDisplayData(e){pe(e)}async getVaultCapture(e,t){let r=`${this.baseUrl}\0${e}\0${t??""}`,s=R.activeVaultCaptureRequests.get(r);if(s)return s;let o=this.requestVaultCapture(e,t);R.activeVaultCaptureRequests.set(r,o);try{return await o}finally{R.activeVaultCaptureRequests.get(r)===o&&R.activeVaultCaptureRequests.delete(r)}}async requestVaultCapture(e,t){let r=new AbortController,s=setTimeout(()=>r.abort(),Et);this.beginDirectTelemetryCheckout(e);let o=this.telemetryTimestamp();this.directTelemetry?.log({name:"vault.capture.requested",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card"});let i={"Content-Type":"application/json"};t&&(i["x-checkout-session-token"]=t);try{let a=await re(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/vault/capture`,{method:"POST",headers:i,signal:r.signal},z,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()-o),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"2xx"}),this.toVaultBlock(l)}catch(a){let l=r.signal.aborted?new m("Timed out while loading the secure card form. Please try again.","api_error",{code:"vault_capture_timeout"}):a;throw this.reportDirectFailure(l,"VAULT_LOAD_FAILED","vault_request","vault_capture","card"),l}finally{clearTimeout(s)}}async getUnifiedCheckoutSession(e,t){let 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 m("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,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":o},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:j(a.status),failureCategory:a.status>=500?"server_error":void 0}),a}try{let l=await this.resolveProcessResponse(a,t.sessionId,{...r,nonce:o});return this.directTelemetry?.log({name:"payment.processing.completed",stage:"processing",requestCategory:"process_payment",statusClass:j(l.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"process_payment",statusClass:j(l.status)}),l}catch(l){throw l instanceof m&&l.code==="checkout_processing_timeout"||this.reportDirectFailure(l,"PAYMENT_PROCESSING_FAILED","processing","process_payment"),l}}async patchAccountSnapshot(e,t,r,s){this.beginDirectTelemetryCheckout(e);let o=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.state_transition",stage:"processing",requestCategory:"account_snapshot"});let i=s?.timeoutMs??St,a=new AbortController,l=()=>a.abort();s?.signal&&(s.signal.aborted?a.abort():s.signal.addEventListener("abort",l,{once:!0}));let c=setTimeout(()=>a.abort(),i);try{let d;try{d=await re(`${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},z,p=>{this.telemetryHooks?.onRetry?.("account_snapshot",p),this.directTelemetry?.log({name:"operation.retry",stage:"processing",requestCategory:"account_snapshot",attempt:p})})}finally{clearTimeout(c),s?.signal?.removeEventListener("abort",l)}if(!d.ok)throw await q(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 m("createSessionIntent requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let o=r,i=o.paymentMethodType,a=typeof i=="string"&&i.trim().toLowerCase()==="card",l=typeof i=="string"&&i.length>0&&!a&&(typeof o.paymentMethodId=="string"||o.paymentMethodId===null),c=o.provider==="stripe"&&(o.paymentMethodCategory==="wallet"||o.paymentMethodCategory==="apm")&&(o.intentKind==="payment"||o.intentKind==="setup"),d=o.provider==="paypal"&&o.paymentMethodCategory==="wallet"&&o.paymentMethodType==="paypal"&&o.paymentMethodId===null&&o.intentKind==="payment";if(!l||!c&&!d)throw new m("Only wallet, APM, and PayPal session intents are supported.","validation_error",{code:"InvalidSessionIntentRequest"});let p=o.authorizationAttemptId;if(p!==void 0&&!xe(p))throw new m("authorizationAttemptId must be a v4 UUID identifying one buyer authorization attempt.","validation_error",{code:"InvalidAuthorizationAttemptId",param:"authorizationAttemptId"});let T=xe(p)?p:Pt();this.beginDirectTelemetryCheckout(e);let h=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.intent.started",stage:"processing",requestCategory:"intent_create"});let _={"Content-Type":"application/json","x-checkout-session-token":t,[Ae]:s?.idempotencyKey||T},w=!1;try{let P=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents`,{method:"POST",headers:_,body:JSON.stringify({...r,authorizationAttemptId:T}),signal:s?.signal});if(!P.ok){w=!0;let I=await q(P,"Failed to create checkout intent"),le=K(I,"PAYMENT_PROCESSING_FAILED");throw Oe(I.statusCode)?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"intent_create",statusClass:"4xx"}):this.directTelemetry?.error({...le,stage:"processing",requestCategory:"intent_create"}),I}let E=(await P.json()).data;if(!E||typeof E!="object")throw new m("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});let u=E,V=u.paymentMethodType,A=(u.paymentMethodCategory==="wallet"||u.paymentMethodCategory==="apm")&&typeof V=="string"&&V.trim().toLowerCase()!=="card"&&(typeof u.paymentMethodId=="string"||u.paymentMethodId===null)&&typeof u.providerObjectId=="string",M=u.provider==="stripe"&&(u.intentKind==="payment"||u.intentKind==="setup")&&typeof u.clientSecret=="string",B=u.provider==="paypal"&&u.paymentMethodCategory==="wallet"&&u.paymentMethodType==="paypal"&&u.paymentMethodId===null&&u.intentKind==="payment"&&(u.providerObjectType==="order"||u.providerObjectType==="subscription")&&u.clientSecret===null,ae=u.provider===r.provider&&u.paymentMethodCategory===r.paymentMethodCategory&&u.paymentMethodType===r.paymentMethodType&&u.paymentMethodId===r.paymentMethodId&&u.intentKind===r.intentKind;if(!A||!M&&!B||!ae)throw new m("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});return this.directTelemetry?.log({name:"payment.intent.completed",stage:"processing",requestCategory:"intent_create",statusClass:j(P.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-h),durationMode:"machine",requestCategory:"intent_create",statusClass:j(P.status)}),u}catch(P){throw w||this.reportDirectFailure(P,"PAYMENT_PROCESSING_FAILED","processing","intent_create"),P}}async reportSessionIntentDecline(e,t,r,s){if(!t)throw new m("reportSessionIntentDecline requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let o=r,i=o.providerDeclineReason,a=o.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=o.provider==="stripe"&&(o.paymentMethodCategory==="wallet"||o.paymentMethodCategory==="apm"),p=o.provider==="paypal"&&o.paymentMethodCategory==="wallet"&&o.paymentMethodType==="paypal";if(!c||!d&&!p)throw new m("Invalid non-card decline classification.","validation_error",{code:"InvalidSessionIntentDeclineRequest"});let T=p?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:i}:{provider:"stripe",paymentMethodCategory:o.paymentMethodCategory,paymentMethodType:o.paymentMethodType,providerDeclineReason:i},h=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents/decline`,{method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":t},body:JSON.stringify(T),signal:s?.signal});if(!h.ok)throw await q(h,"Failed to report checkout decline")}async getPaymentsByEmail(e,t){this.beginDirectTelemetryOperation();let r=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved"});let s=t?.page??1,o=t?.limit??1,i=new URLSearchParams({email:e,page:String(s),limit:String(o),sortField:"createdAt",sortDirection:"DESC"});try{let a=await fetch(`${this.baseUrl}/v1/payments?${i.toString()}`,{method:"GET",signal:t?.signal,keepalive:!0});if(!a.ok)throw new m("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){this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp();this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});try{let r=await this.createAndFetchSessionRequest(e,t);return this.adoptDirectTelemetryCheckout(r.data.session?.id),this.directTelemetry?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_create",statusClass:"2xx"}),this.directTelemetry?.performance({stage:"session_create",durationMs:this.telemetryTimestamp()-t,durationMode:"machine",requestCategory:"session_create",statusClass:"2xx"}),r}catch(r){if(!(r instanceof m&&r.code==="session_auto_completed"))try{this.telemetryHooks?.onSessionCreateFailure?.(r)}catch{}let s=K(r,"CHECKOUT_SESSION_CREATE_FAILED");throw r instanceof m&&r.type==="validation_error"?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}):r instanceof m&&Oe(r.statusCode)?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create",statusClass:"4xx"}):r instanceof m&&r.code==="session_auto_completed"||this.directTelemetry?.error({...s,stage:"session_create",requestCategory:"session_create"}),r}}async createAndFetchSessionRequest(e,t){let r=e.products??Ie(e.items,e.subscriptions),s=De(e.currency,e.items,e.subscriptions,r);if(!s)throw new m("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});let o={clientId:e.clientId,checkoutVersion:ee,successUrl:e.successUrl,cancelUrl:e.cancelUrl,currency:s,checkoutMode:e.checkoutMode??"full",products:r.map(h=>wt(h,s)),accountData:{userId:e.account.userId,firstName:e.account.firstName??null,lastName:e.account.lastName??null,email:e.account.email,country:e.account.country??null,gender:e.account.gender??null,city:e.account.city??null,state:e.account.state??null,zip:e.account.zip??null,addressLine1:e.account.addressLine1??null,addressLine2:e.account.addressLine2??null},couponCodes:e.couponCodes??[]};e.tokenizedData&&(o.tokenizedData=e.tokenizedData),e.tagsData&&(o.tagsData=e.tagsData),e.utmMetadata?.length&&(o.utmMetadata=e.utmMetadata),e.avsCheck!==void 0&&(o.avsCheck=e.avsCheck),e.checkoutType&&(o.checkoutType=e.checkoutType),e.checkoutLayout&&(o.checkoutLayout=e.checkoutLayout),e.avsConfig&&(o.avsConfig=e.avsConfig);let i={"Content-Type":"application/json",[Ee]:ee},a=bt(e.idempotencyKey);a&&(i[Ae]=a);let l,c=!1;for(let h=0;;h++){if(l=await re(`${this.baseUrl}/v1/checkouts/sessions?expand=true`,{method:"POST",headers:i,body:JSON.stringify(o)},z,w=>{this.telemetryHooks?.onRetry?.("session_create",w),this.directTelemetry?.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:w})}),!c){c=!0;let w=`${Math.floor(l.status/100)}xx`;this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:w}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:this.telemetryTimestamp()-t,durationMode:"machine",requestCategory:"session_create",statusClass:w})}if(l.status===204)throw new m("Session auto-completed \u2014 payment method already on file","api_error",{code:"session_auto_completed"});if(l.ok)break;let _=await q(l,"Failed to create checkout session");if(_.code===_t&&h<xt){try{this.telemetryHooks?.onRetry?.("session_create",h+1),this.directTelemetry?.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:h+1})}catch{}await ye(150*2**h);continue}throw _}let d=await l.json();if(d.data&&"gateways"in d.data){this.autoCacheDisplayData(d.data.uuid,e);let h=this.mergeCachedDisplayData(d.data),_=this.normalizeRawSession(h);return d.vault&&_.data.session&&(_.data.session.vault=this.toVaultBlock(d.vault)),{..._,autoProcessingError:d.autoProcessingError,autoProcessingAttempted:d.autoProcessingAttempted,autoProcessingPending:d.autoProcessingPending}}let p=d.data?.uuid;if(!p)throw new m("No session ID returned","api_error",{code:"InvalidCheckoutSessionResponse"});return this.autoCacheDisplayData(p,e),this.adoptDirectTelemetryCheckout(p),{...await this.getUnifiedCheckoutSession(p),autoProcessingError:d.autoProcessingError,autoProcessingAttempted:d.autoProcessingAttempted,autoProcessingPending:d.autoProcessingPending}}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??kt,o=Date.now()+s,i=this.clampRetryAfterMs(t?.initialDelayMs??Fe),a=0;try{for(;;){let l=o-Date.now();if(l<=0)throw te();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 ye(Math.min(i,l)),Date.now()>=o)throw te()}let c=await this.getUnifiedCheckoutSession(e,t?.nonce),d=c.data.session?.status;if(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 te();i=this.clampRetryAfterMs(Math.max(i*2,Mt))}}catch(l){throw l instanceof m&&l.code==="checkout_processing_timeout"&&this.reportDirectFailure(l,"RECOVERY_FAILED","recovery","session_read","saved"),l}}normalizeRawSession(e){let t=e.gateways??{},r=[],s={session:this.toCheckoutSession(e)},o=t.stripe;if(o?.publishableKey){r.push("stripe");let l=[e.stripeClientSecret,o.stripeClientSecret].find(c=>typeof c=="string"&&c.length>0);s.stripe={clientSecret:l??"",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),a=e.currency??t[0]?.currency??"USD",l=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,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==="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"});throw i.data.session?.status==="expired"?new m("Checkout session has expired.","api_error",{code:"checkout_session_expired"}):te()}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:O(e,"sessionId")??r,retryAfterMs:this.clampRetryAfterMs(At(e,"retryAfterMs")??i??Fe),statusUrl:O(e,"statusUrl"),sessionUrl:O(e,"sessionUrl")}}clampRetryAfterMs(e){return Math.max(0,Math.min(e,Rt))}autoCacheDisplayData(e,t){if(!e)return;let r=t.products??Ie(t.items,t.subscriptions);if(r.length===0&&!t.currency)return;let s=t.products!==void 0,o=De(t.currency,s?void 0:t.items,s?void 0:t.subscriptions,r);D(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=ue(e.uuid),r=new Map,s=i=>i?`code:${i}`:void 0;for(let i of t?.products??[]){let a=s(i.code);a&&r.set(a,i)}let o=(e.products??[]).map(i=>{let a=s(i.code),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:o}}};R.activeVaultCaptureRequests=new Map;var S=R;function Le(n,e){let t=S;return new t(n,e)}function Ne(n){return{payment:"payment",address:"address"}[n]}function ne(n){switch(n){case"night":return"night";case"flat":return"flat";default:return"stripe"}}function Ot(n){return{...n,theme:ne(n.theme)}}function he(n){return n?JSON.stringify(n.map(e=>e.trim().toLowerCase())):null}function Ve(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 Ut(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 H=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 Ft(e.publishableKey,{locale:e.locale??"auto"});if(!t)throw new y("Failed to initialize Stripe. Check your publishable key.","authentication_error");this.stripe=t}getElements(e){if(!this.stripe)throw new y("StripeAdapter not initialized. Call initialize() first.","api_error");let t=e?.appearance?{theme:ne(e.appearance.theme),variables:e.appearance.variables,rules:e.appearance.rules}:void 0,r=t?JSON.stringify(t):null,s=he(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,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=s,this.appliedClientSecret=o,this.verifiedClientSecret=null,this.verifiedPaymentMethodTypesKey=null}return this.elements}async assertClientSecretPaymentMethods(e,t){if(!this.stripe)throw new y("StripeAdapter not initialized. Call initialize() first.","api_error");let r,s=!1;if(qt(e)){let{setupIntent:l,error:c}=await this.stripe.retrieveSetupIntent(e);r=l,s=!!c}else{let{paymentIntent:l,error:c}=await this.stripe.retrievePaymentIntent(e);r=l,s=!!c}let o=r?.payment_method_types;if(s||!Array.isArray(o))throw new y("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(o.some(l=>typeof l!="string"||!i.has(l.trim().toLowerCase()))||o.length===0)throw new y("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 y("At least one supported non-card payment method is required.","validation_error",{param:"paymentMethodTypes"});if(r={...t,paymentMethodTypes:l},r.clientSecret){let c=he(l);this.elements&&this.appliedClientSecret===r.clientSecret&&this.appliedPaymentMethodTypesKey===c&&this.verifiedClientSecret===r.clientSecret&&this.verifiedPaymentMethodTypesKey===c||await this.assertClientSecretPaymentMethods(r.clientSecret,l)}}let s=this.getElements(r);e==="payment"&&r.clientSecret&&(this.verifiedClientSecret=r.clientSecret,this.verifiedPaymentMethodTypesKey=he(r.paymentMethodTypes));let o=Ne(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=s.create(o,i);return Ve(a)}getElement(e){if(!this.elements)return null;let t=Ne(e),r=this.elements.getElement(t);return r?Ve(r):null}async submitElements(){if(!this.stripe||!this.elements)return{error:new y("Stripe not initialized","api_error")};let{error:e}=await this.elements.submit();return e?{error:new y(e.message??"Validation failed","validation_error")}:{}}async confirmPayment(e){if(!this.stripe||!this.elements)throw new y("StripeAdapter not initialized or no elements created.","api_error");let t=e.billingDetails,r=t?Ut(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 y(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 y("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 y("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 y(o.message??"PayPal payment failed","validation_error",{code:o.code})}}let r;try{let o=await new S(t).createSessionIntent(e.sessionId,e.nonce??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"});if(o.provider!=="stripe")throw new y("Invalid provider returned for PayPal intent","api_error");r=o.clientSecret}catch(o){return{status:"failed",error:o instanceof y?o:new y("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 S(t).reportSessionIntentDecline(e.sessionId,e.nonce,{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:s.code??"provider_declined"})}catch{}return{status:"failed",error:new y(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 y("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 y(i.message??"Failed to retrieve PayPal payment","api_error")};if(o&&(o.status==="requires_capture"||o.status==="succeeded")){let a=typeof o.payment_method=="string"?o.payment_method:o.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:o.status,paymentIntentId:o.id,paymentMethodId:a}}return{status:"failed",error:new y("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:ne(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 v,classifyTelemetryFailure as fe,resolveBillingApiUrl as Qe,SDK_VERSION as Ht}from"@flopay/shared";import{FloPayError as Lt}from"@flopay/shared";var $=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 Lt("At least one supported non-card payment method is required.","validation_error",{param:"paymentMethodTypes"});r.paymentMethodTypes=a}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 Nt,buildTelemetryLogEvent as Vt,buildTelemetryTerminalEvent as ze,FloPayError as Be,resolveBillingApiUrl as Ke,SDK_VERSION as je}from"@flopay/shared";var ge="flopay-vault",He={ready:["vault.widget.ready","vault_ready"],submitting:["vault.submission.started","vault_submit"],blocked:["operation.state_transition","vault_submit"],action_required:["vault.action.required","three_ds_handoff"]};function G(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 oe(n,e){return Vt({eventId:"11111111-1111-4111-8111-111111111111",name:n,stage:e,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}function $e(n){return n?{errorCode:"VAULT_SUBMIT_FAILED",stage:"vault_submit"}:{errorCode:"VAULT_LOAD_FAILED",stage:"vault_mount"}}function Bt(n,e){if(n==="complete"||n==="decline")return ze({eventId:"22222222-2222-4222-8222-222222222222",outcome:n==="complete"?"payment_succeeded":"payment_declined",sequence:0,provider:"pcivault",paymentMethodCategory:"card"});if(n==="error"){let s=$e(e);return Nt({eventId:"33333333-3333-4333-8333-333333333333",...s,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}let[t,r]=He[n];return oe(t,r)}function Kt(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===ge&&(e.type==="ready"||e.type==="submitting"||e.type==="blocked"||e.type==="complete"||e.type==="decline"||e.type==="error"||e.type==="action_required")}function jt(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===ge&&e.type==="validation"&&Array.isArray(e.messages)}function zt(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===ge&&e.type==="resize"&&typeof e.height=="number"&&Number.isFinite(e.height)}var U=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 f({billingApiUrl:Ke(),sdkVersion:je}):void 0)}async mount(e,t){if(this.ownsTelemetryReporter&&!this.telemetryReporter&&(this.telemetryReporter=new f({billingApiUrl:Ke(),sdkVersion:je})),this.mountStartedAt=this.telemetryReporter?.now?.()??C(),this.vaultReadyReported=!1,this.submissionStarted=!1,this.submissionStartedAt=null,typeof window>"u"||typeof document>"u")throw this.reportVaultLoadFailure(),new Be("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 Be("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(),G(oe("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(zt(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;this.applyHeight(r.height);return}if(jt(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;let a=r.messages.filter(l=>typeof l=="string"&&l.trim()).join(" ");this.emit("validation",{sessionId:this.config.sessionId,message:a||void 0});return}if(!Kt(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={sessionId:r.sessionId??this.config.sessionId,intentId:r.intentId,declineReason:r.declineReason,message:r.message,nextActionRedirectUrl:r.nextActionRedirectUrl};r.type==="submitting"&&(this.submissionStarted=!0,this.submissionStartedAt=this.telemetryReporter?.now?.()??C()),G(Bt(r.type,this.submissionStarted)),this.reportOutcome(r.type),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(),this.emit(r.type,i)};this.messageHandler=e,window.addEventListener("message",e)}reportOutcome(e){let t=this.telemetryReporter;if(!t)return;if(e==="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"})),e==="complete"||e==="decline"){t.log({name:"vault.terminal",stage:"completion",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:e==="complete"?"payment_succeeded":"payment_declined",provider:"pcivault",paymentMethodCategory:"card"});return}if(e==="error"){let o=$e(this.submissionStarted);t.log({name:"vault.terminal",stage:o.stage,provider:"pcivault",paymentMethodCategory:"card"}),t.error({...o,provider:"pcivault",paymentMethodCategory:"card"});return}if(e==="action_required"){t.log({name:"vault.action.required",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"}),t.log({name:"vault.three_ds.handoff",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"});let o=this.submissionStartedAt;this.submissionStartedAt=null,o!==null&&t.performance({stage:"three_ds_handoff",durationMs:Math.max(0,t.now()-o),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:"action_required",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"});return}let[r,s]=He[e];t.log({name:r,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 s=document.createElement("button");s.type="button",s.setAttribute("aria-label","Close card authentication"),s.textContent="\xD7",s.style.cssText=["position:fixed","top:20px","right:20px","width:40px","height:40px","border:0","border-radius:9999px","background:#fff","color:#0f172a","font-size:28px","line-height:40px","cursor:pointer","box-shadow:0 4px 14px rgba(0,0,0,0.25)"].join(";"),s.addEventListener("click",()=>this.abandonActionRequiredOverlay()),t.appendChild(s),t.addEventListener("click",i=>{i.target===t&&this.abandonActionRequiredOverlay()});let o=i=>{if(i.source!==r.contentWindow)return;let a=i.data;if(!a||typeof a!="object")return;let l=a;l.source==="flopay-vault-3ds-return"&&(G(oe("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",o),this.threeDsReturnHandler=o,document.body.appendChild(t),this.actionOverlay=t,G(oe("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"});G(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 Ge(n,e){let t=U;return new t(n,{reporter:e})}var Ye=Symbol.for("@flopay/js.telemetry.bridge.v1");function We(n,e,t){let r=()=>e?.now()??t();Object.defineProperty(n,Ye,{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 Je(n){return n[Ye]}function L(n){if(!n)return!1;let e=n.code?.toLowerCase()??"";return!!n.declineCode||e.includes("declin")}function $t(n){return n==="stripe"||n==="paypal"||n==="pcivault"?n:"other"}var se=class{constructor(e,t,r){this.currentElements=null;this.provider=e,this.config=t,this.telemetryReporter=r??new f({billingApiUrl:Qe(t.billingApiUrl),sdkVersion:Ht,enabled:t.telemetry!==!1}),We(this,this.telemetryReporter,C)}now(){return this.telemetryReporter?.now?.()??C()}elements(e){return this.currentElements&&this.currentElements.destroy(),this.currentElements=new $(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?Ge({sessionId:e?.sessionId},this.telemetryReporter):new U({sessionId:e?.sessionId,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"&&(L(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 v&&L(r))this.telemetryReporter?.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"});else if(r instanceof v&&r.type==="validation_error")this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal"});else{let s=fe(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"}):L(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 v&&L(t))this.telemetryReporter?.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"});else if(t instanceof v&&t.type==="validation_error")this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal"});else{let r=fe(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 v("A supported non-card payment method is required.","validation_error",{param:"paymentMethodType"});let t=this.now(),r=$t(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}):L(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 v&&L(s)?this.telemetryReporter?.terminal({outcome:"payment_declined",provider:r,paymentMethodCategory:e.paymentMethodCategory}):s instanceof v&&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 v("sessionId is required to retrieve a session.","validation_error",{param:"sessionId"});let r=await this.retrieveUnifiedSession(e,t);if(!r.data.session)throw new v("Session not found","api_error");return r.data.session}async retrieveUnifiedSession(e,t){if(!e)throw new v("sessionId is required.","validation_error",{param:"sessionId"});let r=Qe(t??this.config.billingApiUrl),s=this.now();this.telemetryReporter?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let o,i=Le(r,{now:()=>this.telemetryReporter?.now()??C(),onFirstByte:a=>{o=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 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"}),a}catch(a){let l=fe(a,a instanceof v&&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()-s,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 Xe(n,e,t){let r=se;return new r(n,e,t)}var et=new Map;function ve(n){return Array.isArray(n)?n.map(ve):n&&typeof n=="object"?Object.fromEntries(Object.entries(n).filter(([,e])=>e!==void 0).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,ve(t)])):n}function Yt(n,e){return JSON.stringify([n,Ce(e?.billingApiUrl),e?.telemetry!==!1,e?.locale??"auto",e?.apiVersion??null,ve(e?.appearance??null)])}var ie=new Map;async function Wt(n,e){if(!n){let a=new f({billingApiUrl:Ce(e?.billingApiUrl),sdkVersion:Ze,enabled:e?.telemetry!==!1});throw a.error({errorCode:"CONFIGURATION_INVALID",stage:"sdk_initialize",paymentMethodCategory:"unknown"}),a.flush().catch(()=>{}).finally(()=>a.destroy()),new Gt("A publishable key is required to initialize FloPay.","validation_error",{param:"publishableKey"})}let t=Yt(n,e),r=et.get(t);if(r)return e?.telemetry!==!1&&Je(r)?.log({name:"sdk.cache.hit",stage:"sdk_initialize"}),r;let s=ie.get(t);if(s)return s;let o={...e,publishableKey:n},i=(async()=>{let a=new f({billingApiUrl:Ce(o.billingApiUrl),sdkVersion:Ze,enabled:o.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 H;try{await c.initialize(o)}catch(T){throw a.error({errorCode:"SDK_INITIALIZATION_FAILED",failureCategory:"provider_runtime",stage:"sdk_initialize",provider:"stripe",paymentMethodCategory:"unknown"}),a.destroy(),T}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"});let d=a.now()-l;a.performance({stage:"sdk_initialize",durationMs:d,durationMode:"machine",provider:"stripe"}),a.performance({stage:"provider_ready",durationMs:d,durationMode:"machine",provider:"stripe"});let p=Xe(c,o,a);return et.set(t,p),p})();ie.set(t,i);try{return await i}finally{ie.get(t)===i&&ie.delete(t)}}import{FloPayError as N,IDEMPOTENCY_IN_PROGRESS_CODE as Jt,IDEMPOTENCY_KEY_HEADER as Qt,SDK_VERSION as tt,buildProductPayload as Xt,classifyTelemetryFailure as Zt,foldIntoProducts as er,resolveIdempotencyKey as rt,resolveSessionCurrency as tr}from"@flopay/shared";var Te=5;function rr(n,e){let t=e?.error,r=k(e?.code)??k(t?.code)??`http_${n}`,s=k(e?.message)??k(t?.message)??nr(r,n);return new N(s,"api_error",{code:r,statusCode:n})}function nr(n,e){switch(n){case"CouponLimitExceeded":return`Too many coupon codes \u2014 a checkout session accepts at most ${Te}.`;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 nt(n,e){let{billingApiUrl:t,checkoutBaseUrl:r,items:s=[],subscriptions:o=[],products:i,account:a,successUrl:l,cancelUrl:c,checkoutMode:d="confirm",couponCodes:p=[],tagsData:T,redirectParams:h={},setCookie:_=!0,timeoutMs:w=12e3,clientId:P,currency:we,utmMetadata:E,idempotencyKey:u}=n,V=rt(u);if(p.length>Te)throw new N(`Too many coupon codes \u2014 a checkout session accepts at most ${Te}.`,"validation_error",{code:"CouponLimitExceeded",param:"couponCodes"});let A=i??er(s,o),M=tr(we,s,o,A);if(!M)throw new N("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 B={clientId:P,checkoutVersion:tt,successUrl:l,cancelUrl:c,currency:M,checkoutMode:d,products:A.map(b=>Xt(b,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};T&&(B.tagsData=T),E?.length&&(B.utmMetadata=E);let ae=`${t.replace(/\/+$/,"")}/v1/checkouts/sessions`,I=new AbortController,le=setTimeout(()=>I.abort(),w),Pe={"Content-Type":"application/json"};V&&(Pe[Qt]=V);let x,W;try{let b=await fetch(ae,{method:"POST",headers:Pe,body:JSON.stringify(B),signal:I.signal});try{e?.(b.status)}catch{}x=b.status;try{W=await b.json()}catch{}}finally{clearTimeout(le)}if(x>=400)throw rr(x,W);if(x===201){let b=W?.data?.uuid,ce=W?.data?.nonce;if(!b)throw new Error("Checkout session created but no UUID was returned by the billing API");if(!ce)throw new N("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"});(A.length||M)&&D(b,{currency:M,products:A.map(g=>({code:g.code??g.providerItemId??g.providerPlanId,type:g.type,name:g.name??g.itemName??g.providerItemName??g.subscriptionName??g.providerPlanName??null,totalAmount:g.totalAmount,overrideAmount:g.overrideAmount,currency:g.currency??M}))});let J=new URL(`${r.replace(/\/+$/,"")}/secure`);J.searchParams.set("id",b);for(let[g,Q]of Object.entries(h))J.searchParams.set(g,Q);if(_&&typeof window<"u"&&typeof document<"u"){let g=JSON.stringify({origin_url:c}),Q=window.location.hostname.split(".").slice(-2).join(".");document.cookie=`checkout_data=${encodeURIComponent(g)}; domain=.${Q}; path=/; max-age=3600; SameSite=Lax; Secure;`,document.cookie=`flopay_checkout_token=${encodeURIComponent(ce)}; domain=.${Q}; path=/; max-age=3600; SameSite=Lax; Secure;`}return typeof window<"u"&&(window.location.href=J.toString()),{status:201,redirectUrl:J.toString(),nonce:ce}}return x===204?(typeof window<"u"&&(window.location.href=l),{status:204}):{status:x}}async function or(n){let e=st(n),t=ot(e);try{let r=await nt(n,t);return it(e,r),r}catch(r){throw _e(e.reporter,r),r}finally{Y(e.reporter)}}function ot(n){let e=!1;return t=>{if(e)return;e=!0;let r=`${Math.floor(t/100)}xx`;n.reporter.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:r}),n.reporter.performance({stage:"session_first_byte",durationMs:n.reporter.now()-n.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:r})}}function st(n){let e=new f({billingApiUrl:n.billingApiUrl,sdkVersion:tt,enabled:n.telemetry!==!1}),t=e.now();return e.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"}),{reporter:e,startedAt:t}}function it(n,e){let t=`${Math.floor(e.status/100)}xx`;n.reporter.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_create",statusClass:t}),n.reporter.performance({stage:"session_complete",durationMs:n.reporter.now()-n.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:t})}function _e(n,e){let t=Zt(e,"CHECKOUT_SESSION_CREATE_FAILED");if(e instanceof N&&e.type==="validation_error"){n.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"});return}if(t.statusClass==="4xx"){n.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create",statusClass:"4xx"});return}n.error({...t,stage:"session_create",requestCategory:"session_create"})}function Y(n){n.flush().catch(()=>{}).finally(()=>n.destroy())}async function sr(n){let{maxRetries:e=3,...t}=n,r=st(n),s=ot(r);if(!Number.isFinite(e)||!Number.isInteger(e)||e<=0)throw r.reporter.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),Y(r.reporter),new Error("Number of retries must be greater than 0");let o={...t,idempotencyKey:rt(t.idempotencyKey)},i;for(let a=0;a<=e;a++)try{let l=await nt(o,s);return it(r,l),Y(r.reporter),l}catch(l){i=l;let c=l instanceof Error&&l.name==="AbortError",d=l instanceof N&&l.code===Jt;if((c||d)&&a<e){r.reporter.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:a+1}),await new Promise(p=>setTimeout(p,100*Math.pow(2,a)));continue}throw _e(r.reporter,l),Y(r.reporter),l}throw _e(r.reporter,i),Y(r.reporter),i??new Error("Unknown error during checkout session creation")}export{se as FloPay,$ as FloPayElements,S as PaymentAPI,U as PciVaultCardCapture,H as StripeAdapter,D as cacheSessionDisplayData,pe as clearSessionDisplayData,or as createCheckoutSession,sr as createCheckoutSessionWithRetries,ue as getSessionDisplayData,Wt as loadFloPay,Ot as toStripeAppearance,ne as toStripeAppearanceTheme};
1
+ import{FloPayError as Gt,resolveBillingApiUrl as Ce,SDK_VERSION as Ze}from"@flopay/shared";import{loadStripe as Ft}from"@stripe/stripe-js";import{FloPayError as y,isSetupIntentClientSecret as qt}from"@flopay/shared";import{FloPayError as m,SDK_VERSION as ee,FLO_SDK_VERSION_HEADER as Ee,IDEMPOTENCY_KEY_HEADER as Ae,IDEMPOTENCY_IN_PROGRESS_CODE as Tt,buildProductPayload as wt,classifyTelemetryFailure as K,foldIntoProducts as Ie,isUuidV4 as xe,randomUuidV4 as Pt,resolveIdempotencyKey as bt,resolveSessionCurrency as De,telemetryStatusClass as j}from"@flopay/shared";function k(n){return typeof n=="string"&&n.trim()?n:void 0}function be(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 at="flopay_session_display:";var X=new Map;function Z(n){return`${at}${n}`}function de(){if(typeof window>"u")return null;try{return window.sessionStorage}catch{return null}}function D(n,e,t){if(!n)return;let r=t?.ttlMs??36e5,s={data:e,expiresAt:Date.now()+r},o=de();if(o)try{o.setItem(Z(n),JSON.stringify(s));return}catch{}X.set(n,s)}function ue(n){if(!n)return null;let e=de();if(e)try{let r=e.getItem(Z(n));if(r){let s=JSON.parse(r);if(s&&typeof s.expiresAt=="number"&&s.expiresAt>Date.now())return s.data;e.removeItem(Z(n))}}catch{}let t=X.get(n);if(t){if(t.expiresAt>Date.now())return t.data;X.delete(n)}return null}function pe(n){if(!n)return;X.delete(n);let e=de();if(e)try{e.removeItem(Z(n))}catch{}}import{buildTelemetryErrorEvent as Me,buildTelemetryLogEvent as lt,buildTelemetryPerformanceEvent as ct,buildTelemetryTerminalEvent as dt,serializeTelemetryBatch as ut,TELEMETRY_MAX_BATCH_BYTES as pt}from"@flopay/shared";var mt="/v1/sdk-telemetry/events",me=16,yt=64,ht=1500,ke=1e3,gt=64,ft="00000000-0000-4000-8000-000000000000",Ct={technical_error:8,lifecycle:32,expected_outcome:32,performance:24};function F(){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 vt(n){try{return new TextEncoder().encode(n).byteLength}catch{return n.length}}function _t(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 C(){return globalThis.performance?.now()??0}var f=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(/\/+$/,"")}${mt}`,this.sdkPackage=e.sdkPackage??"@flopay/js",this.sdkVersion=e.sdkVersion,this.correlationId=F(),this.merchantEnabled=e.enabled!==!1,this.clock=e.clock??C,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(lt({...this.checkoutContext,...e,eventId:F(),sequence:this.sequence++}))}error(e){if(!this.canCollect())return;let t=Me({...this.checkoutContext,...e,eventId:ft,sequence:0}),r=_t(t),s=this.now();this.pruneReportedFailures(s);let o=this.reportedFailures.get(r);if(o!==void 0&&s>=o&&s-o<ke){this.log({name:"operation.deduplicated",stage:e.stage,provider:e.provider,paymentMethodCategory:e.paymentMethodCategory,attempt:e.attempt});return}this.rememberReportedFailure(r,s),this.enqueue(Me({...this.checkoutContext,...e,eventId:F(),sequence:this.sequence++}))}performance(e){this.canCollect()&&this.enqueue(ct({...this.checkoutContext,...e,eventId:F(),sequence:this.sequence++}))}terminal(e){if(this.canCollect()&&(this.enqueue(dt({...this.checkoutContext,...e,eventId:F(),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 C()}}pruneReportedFailures(e){for(let[t,r]of this.reportedFailures)(e<r||e-r>=ke)&&this.reportedFailures.delete(t)}rememberReportedFailure(e,t){for(;this.reportedFailures.size>=gt;){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>=yt||this.eventCounts[e.class]>=Ct[e.class])){if(this.eventCounts[e.class]+=1,this.queue.push(e),this.queue.length>=me){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,me);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,me);this.sendBatch(e)}}async sendBatch(e){if(!this.browserTransportAvailable||this.ingestionDisabled)return;let t=ut(e,{correlationId:this.correlationId,sdkPackage:this.sdkPackage,sdkVersion:this.sdkVersion,batchId:F()});if(vt(t)>pt)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 l=>l.status!==202?null:(await l.json().catch(()=>null))?.status==="disabled"?"disabled":null).catch(()=>null),i=new Promise(l=>{s=setTimeout(()=>{r?.abort(),l(null)},ht)});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)}},Re=Symbol.for("@flopay/js.telemetry.reporter-factory.v1"),Se=globalThis;Se[Re]===void 0&&Object.defineProperty(Se,Re,{configurable:!0,enumerable:!1,writable:!1,value:n=>new f(n)});var Fe=1e3,Mt=500,kt=15e3,Rt=3e3,St=1e4,Et=1e4;function Ue(n){return typeof n=="object"&&n!==null}function O(n,e){return k(n?.[e])}function qe(n,e){return be(n?.[e])}function At(n,e){let t=n?.[e];return typeof t=="number"&&Number.isFinite(t)?t:void 0}function ye(n){return new Promise(e=>setTimeout(e,n))}function te(){return new m("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=Ue(t?.error)?t.error:null,s=qe(t,"message")??qe(r,"message")??e,o=O(t,"code")??O(t,"gatewayErrorCode")??O(r,"code")??`http_${n.status}`;return new m(s,"api_error",{code:o,statusCode:n.status})}async function It(n){if(n.status!==400&&n.status!==422)return;if(n.status===422)return"validation_rejected";let e=await n.clone().json().catch(()=>null);return Ue(e)&&Array.isArray(e.fields)?"validation_rejected":"payment_declined"}function Oe(n){return n===400||n===422}var z=2,xt=2;async function re(n,e,t=z,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 ye(150*2**o)}}function Dt(n){return"now"in n||"onFirstByte"in n||"onSessionCreateFailure"in n||"onRetry"in n}var R=class R{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 f({billingApiUrl:this.baseUrl,sdkVersion:ee})}destroy(){this.directTelemetry?.destroy()}reportDirectFailure(e,t,r,s,o="unknown"){let i=K(e,t);this.directTelemetry?.error({...i,stage:r,requestCategory:s,paymentMethodCategory:o})}reportAccountSnapshotFailure(e,t){let r=K(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()??C()}catch{return C()}}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={[Ee]:ee};t&&(s["x-checkout-session-token"]=t);try{let o=await re(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}`,{headers:s},z,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(o.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}),!o.ok)throw await q(o,"Failed to get checkout session");let l=await o.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(o){throw this.directTelemetry?.error({...K(o,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"}),o}}cacheSessionDisplayData(e,t,r){D(e,t,r)}clearSessionDisplayData(e){pe(e)}async getVaultCapture(e,t){let r=`${this.baseUrl}\0${e}\0${t??""}`,s=R.activeVaultCaptureRequests.get(r);if(s)return s;let o=this.requestVaultCapture(e,t);R.activeVaultCaptureRequests.set(r,o);try{return await o}finally{R.activeVaultCaptureRequests.get(r)===o&&R.activeVaultCaptureRequests.delete(r)}}async requestVaultCapture(e,t){let r=new AbortController,s=setTimeout(()=>r.abort(),Et);this.beginDirectTelemetryCheckout(e);let o=this.telemetryTimestamp();this.directTelemetry?.log({name:"vault.capture.requested",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card"});let i={"Content-Type":"application/json"};t&&(i["x-checkout-session-token"]=t);try{let a=await re(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/vault/capture`,{method:"POST",headers:i,signal:r.signal},z,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()-o),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"2xx"}),this.toVaultBlock(l)}catch(a){let l=r.signal.aborted?new m("Timed out while loading the secure card form. Please try again.","api_error",{code:"vault_capture_timeout"}):a;throw this.reportDirectFailure(l,"VAULT_LOAD_FAILED","vault_request","vault_capture","card"),l}finally{clearTimeout(s)}}async getUnifiedCheckoutSession(e,t){let 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 m("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,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":o},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:j(a.status),failureCategory:a.status>=500?"server_error":void 0}),a}try{let l=await this.resolveProcessResponse(a,t.sessionId,{...r,nonce:o});return this.directTelemetry?.log({name:"payment.processing.completed",stage:"processing",requestCategory:"process_payment",statusClass:j(l.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"process_payment",statusClass:j(l.status)}),l}catch(l){throw l instanceof m&&l.code==="checkout_processing_timeout"||this.reportDirectFailure(l,"PAYMENT_PROCESSING_FAILED","processing","process_payment"),l}}async patchAccountSnapshot(e,t,r,s){this.beginDirectTelemetryCheckout(e);let o=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.state_transition",stage:"processing",requestCategory:"account_snapshot"});let i=s?.timeoutMs??St,a=new AbortController,l=()=>a.abort();s?.signal&&(s.signal.aborted?a.abort():s.signal.addEventListener("abort",l,{once:!0}));let c=setTimeout(()=>a.abort(),i);try{let d;try{d=await re(`${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},z,p=>{this.telemetryHooks?.onRetry?.("account_snapshot",p),this.directTelemetry?.log({name:"operation.retry",stage:"processing",requestCategory:"account_snapshot",attempt:p})})}finally{clearTimeout(c),s?.signal?.removeEventListener("abort",l)}if(!d.ok)throw await q(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 m("createSessionIntent requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let o=r,i=o.paymentMethodType,a=typeof i=="string"&&i.trim().toLowerCase()==="card",l=typeof i=="string"&&i.length>0&&!a&&(typeof o.paymentMethodId=="string"||o.paymentMethodId===null),c=o.provider==="stripe"&&(o.paymentMethodCategory==="wallet"||o.paymentMethodCategory==="apm")&&(o.intentKind==="payment"||o.intentKind==="setup"),d=o.provider==="paypal"&&o.paymentMethodCategory==="wallet"&&o.paymentMethodType==="paypal"&&o.paymentMethodId===null&&o.intentKind==="payment";if(!l||!c&&!d)throw new m("Only wallet, APM, and PayPal session intents are supported.","validation_error",{code:"InvalidSessionIntentRequest"});let p=o.authorizationAttemptId;if(p!==void 0&&!xe(p))throw new m("authorizationAttemptId must be a v4 UUID identifying one buyer authorization attempt.","validation_error",{code:"InvalidAuthorizationAttemptId",param:"authorizationAttemptId"});let _=xe(p)?p:Pt();this.beginDirectTelemetryCheckout(e);let h=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.intent.started",stage:"processing",requestCategory:"intent_create"});let T={"Content-Type":"application/json","x-checkout-session-token":t,[Ae]:s?.idempotencyKey||_},w=!1;try{let P=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents`,{method:"POST",headers:T,body:JSON.stringify({...r,authorizationAttemptId:_}),signal:s?.signal});if(!P.ok){w=!0;let I=await q(P,"Failed to create checkout intent"),le=K(I,"PAYMENT_PROCESSING_FAILED");throw Oe(I.statusCode)?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"intent_create",statusClass:"4xx"}):this.directTelemetry?.error({...le,stage:"processing",requestCategory:"intent_create"}),I}let E=(await P.json()).data;if(!E||typeof E!="object")throw new m("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});let u=E,V=u.paymentMethodType,A=(u.paymentMethodCategory==="wallet"||u.paymentMethodCategory==="apm")&&typeof V=="string"&&V.trim().toLowerCase()!=="card"&&(typeof u.paymentMethodId=="string"||u.paymentMethodId===null)&&typeof u.providerObjectId=="string",M=u.provider==="stripe"&&(u.intentKind==="payment"||u.intentKind==="setup")&&typeof u.clientSecret=="string",B=u.provider==="paypal"&&u.paymentMethodCategory==="wallet"&&u.paymentMethodType==="paypal"&&u.paymentMethodId===null&&u.intentKind==="payment"&&(u.providerObjectType==="order"||u.providerObjectType==="subscription")&&u.clientSecret===null,ae=u.provider===r.provider&&u.paymentMethodCategory===r.paymentMethodCategory&&u.paymentMethodType===r.paymentMethodType&&u.paymentMethodId===r.paymentMethodId&&u.intentKind===r.intentKind;if(!A||!M&&!B||!ae)throw new m("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});return this.directTelemetry?.log({name:"payment.intent.completed",stage:"processing",requestCategory:"intent_create",statusClass:j(P.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-h),durationMode:"machine",requestCategory:"intent_create",statusClass:j(P.status)}),u}catch(P){throw w||this.reportDirectFailure(P,"PAYMENT_PROCESSING_FAILED","processing","intent_create"),P}}async reportSessionIntentDecline(e,t,r,s){if(!t)throw new m("reportSessionIntentDecline requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let o=r,i=o.providerDeclineReason,a=o.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=o.provider==="stripe"&&(o.paymentMethodCategory==="wallet"||o.paymentMethodCategory==="apm"),p=o.provider==="paypal"&&o.paymentMethodCategory==="wallet"&&o.paymentMethodType==="paypal";if(!c||!d&&!p)throw new m("Invalid non-card decline classification.","validation_error",{code:"InvalidSessionIntentDeclineRequest"});let _=p?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:i}:{provider:"stripe",paymentMethodCategory:o.paymentMethodCategory,paymentMethodType:o.paymentMethodType,providerDeclineReason:i},h=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents/decline`,{method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":t},body:JSON.stringify(_),signal:s?.signal});if(!h.ok)throw await q(h,"Failed to report checkout decline")}async getPaymentsByEmail(e,t){this.beginDirectTelemetryOperation();let r=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved"});let s=t?.page??1,o=t?.limit??1,i=new URLSearchParams({email:e,page:String(s),limit:String(o),sortField:"createdAt",sortDirection:"DESC"});try{let a=await fetch(`${this.baseUrl}/v1/payments?${i.toString()}`,{method:"GET",signal:t?.signal,keepalive:!0});if(!a.ok)throw new m("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){this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp();this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});try{let r=await this.createAndFetchSessionRequest(e,t);return this.adoptDirectTelemetryCheckout(r.data.session?.id),this.directTelemetry?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_create",statusClass:"2xx"}),this.directTelemetry?.performance({stage:"session_create",durationMs:this.telemetryTimestamp()-t,durationMode:"machine",requestCategory:"session_create",statusClass:"2xx"}),r}catch(r){if(!(r instanceof m&&r.code==="session_auto_completed"))try{this.telemetryHooks?.onSessionCreateFailure?.(r)}catch{}let s=K(r,"CHECKOUT_SESSION_CREATE_FAILED");throw r instanceof m&&r.type==="validation_error"?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}):r instanceof m&&Oe(r.statusCode)?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create",statusClass:"4xx"}):r instanceof m&&r.code==="session_auto_completed"||this.directTelemetry?.error({...s,stage:"session_create",requestCategory:"session_create"}),r}}async createAndFetchSessionRequest(e,t){let r=e.products??Ie(e.items,e.subscriptions),s=De(e.currency,e.items,e.subscriptions,r);if(!s)throw new m("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});let o={clientId:e.clientId,checkoutVersion:ee,successUrl:e.successUrl,cancelUrl:e.cancelUrl,currency:s,checkoutMode:e.checkoutMode??"full",products:r.map(h=>wt(h,s)),accountData:{userId:e.account.userId,firstName:e.account.firstName??null,lastName:e.account.lastName??null,email:e.account.email,country:e.account.country??null,gender:e.account.gender??null,city:e.account.city??null,state:e.account.state??null,zip:e.account.zip??null,addressLine1:e.account.addressLine1??null,addressLine2:e.account.addressLine2??null},couponCodes:e.couponCodes??[]};e.tokenizedData&&(o.tokenizedData=e.tokenizedData),e.tagsData&&(o.tagsData=e.tagsData),e.utmMetadata?.length&&(o.utmMetadata=e.utmMetadata),e.avsCheck!==void 0&&(o.avsCheck=e.avsCheck),e.checkoutType&&(o.checkoutType=e.checkoutType),e.checkoutLayout&&(o.checkoutLayout=e.checkoutLayout),e.avsConfig&&(o.avsConfig=e.avsConfig);let i={"Content-Type":"application/json",[Ee]:ee},a=bt(e.idempotencyKey);a&&(i[Ae]=a);let l,c=!1;for(let h=0;;h++){if(l=await re(`${this.baseUrl}/v1/checkouts/sessions?expand=true`,{method:"POST",headers:i,body:JSON.stringify(o)},z,w=>{this.telemetryHooks?.onRetry?.("session_create",w),this.directTelemetry?.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:w})}),!c){c=!0;let w=`${Math.floor(l.status/100)}xx`;this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:w}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:this.telemetryTimestamp()-t,durationMode:"machine",requestCategory:"session_create",statusClass:w})}if(l.status===204)throw new m("Session auto-completed \u2014 payment method already on file","api_error",{code:"session_auto_completed"});if(l.ok)break;let T=await q(l,"Failed to create checkout session");if(T.code===Tt&&h<xt){try{this.telemetryHooks?.onRetry?.("session_create",h+1),this.directTelemetry?.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:h+1})}catch{}await ye(150*2**h);continue}throw T}let d=await l.json();if(d.data&&"gateways"in d.data){this.autoCacheDisplayData(d.data.uuid,e);let h=this.mergeCachedDisplayData(d.data),T=this.normalizeRawSession(h);return d.vault&&T.data.session&&(T.data.session.vault=this.toVaultBlock(d.vault)),{...T,autoProcessingError:d.autoProcessingError,autoProcessingAttempted:d.autoProcessingAttempted,autoProcessingPending:d.autoProcessingPending}}let p=d.data?.uuid;if(!p)throw new m("No session ID returned","api_error",{code:"InvalidCheckoutSessionResponse"});return this.autoCacheDisplayData(p,e),this.adoptDirectTelemetryCheckout(p),{...await this.getUnifiedCheckoutSession(p),autoProcessingError:d.autoProcessingError,autoProcessingAttempted:d.autoProcessingAttempted,autoProcessingPending:d.autoProcessingPending}}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??kt,o=Date.now()+s,i=this.clampRetryAfterMs(t?.initialDelayMs??Fe),a=0;try{for(;;){let l=o-Date.now();if(l<=0)throw te();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 ye(Math.min(i,l)),Date.now()>=o)throw te()}let c=await this.getUnifiedCheckoutSession(e,t?.nonce),d=c.data.session?.status;if(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 te();i=this.clampRetryAfterMs(Math.max(i*2,Mt))}}catch(l){throw l instanceof m&&l.code==="checkout_processing_timeout"&&this.reportDirectFailure(l,"RECOVERY_FAILED","recovery","session_read","saved"),l}}normalizeRawSession(e){let t=e.gateways??{},r=[],s={session:this.toCheckoutSession(e)},o=t.stripe;if(o?.publishableKey){r.push("stripe");let l=[e.stripeClientSecret,o.stripeClientSecret].find(c=>typeof c=="string"&&c.length>0);s.stripe={clientSecret:l??"",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),a=e.currency??t[0]?.currency??"USD",l=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,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==="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"});throw i.data.session?.status==="expired"?new m("Checkout session has expired.","api_error",{code:"checkout_session_expired"}):te()}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:O(e,"sessionId")??r,retryAfterMs:this.clampRetryAfterMs(At(e,"retryAfterMs")??i??Fe),statusUrl:O(e,"statusUrl"),sessionUrl:O(e,"sessionUrl")}}clampRetryAfterMs(e){return Math.max(0,Math.min(e,Rt))}autoCacheDisplayData(e,t){if(!e)return;let r=t.products??Ie(t.items,t.subscriptions);if(r.length===0&&!t.currency)return;let s=t.products!==void 0,o=De(t.currency,s?void 0:t.items,s?void 0:t.subscriptions,r);D(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=ue(e.uuid),r=new Map,s=i=>i?`code:${i}`:void 0;for(let i of t?.products??[]){let a=s(i.code);a&&r.set(a,i)}let o=(e.products??[]).map(i=>{let a=s(i.code),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:o}}};R.activeVaultCaptureRequests=new Map;var S=R;function Le(n,e){let t=S;return new t(n,e)}function Ne(n){return{payment:"payment",address:"address"}[n]}function ne(n){switch(n){case"night":return"night";case"flat":return"flat";default:return"stripe"}}function Ot(n){return{...n,theme:ne(n.theme)}}function he(n){return n?JSON.stringify(n.map(e=>e.trim().toLowerCase())):null}function Ve(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 Ut(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 H=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 Ft(e.publishableKey,{locale:e.locale??"auto"});if(!t)throw new y("Failed to initialize Stripe. Check your publishable key.","authentication_error");this.stripe=t}getElements(e){if(!this.stripe)throw new y("StripeAdapter not initialized. Call initialize() first.","api_error");let t=e?.appearance?{theme:ne(e.appearance.theme),variables:e.appearance.variables,rules:e.appearance.rules}:void 0,r=t?JSON.stringify(t):null,s=he(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,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=s,this.appliedClientSecret=o,this.verifiedClientSecret=null,this.verifiedPaymentMethodTypesKey=null}return this.elements}async assertClientSecretPaymentMethods(e,t){if(!this.stripe)throw new y("StripeAdapter not initialized. Call initialize() first.","api_error");let r,s=!1;if(qt(e)){let{setupIntent:l,error:c}=await this.stripe.retrieveSetupIntent(e);r=l,s=!!c}else{let{paymentIntent:l,error:c}=await this.stripe.retrievePaymentIntent(e);r=l,s=!!c}let o=r?.payment_method_types;if(s||!Array.isArray(o))throw new y("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(o.some(l=>typeof l!="string"||!i.has(l.trim().toLowerCase()))||o.length===0)throw new y("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 y("At least one supported non-card payment method is required.","validation_error",{param:"paymentMethodTypes"});if(r={...t,paymentMethodTypes:l},r.clientSecret){let c=he(l);this.elements&&this.appliedClientSecret===r.clientSecret&&this.appliedPaymentMethodTypesKey===c&&this.verifiedClientSecret===r.clientSecret&&this.verifiedPaymentMethodTypesKey===c||await this.assertClientSecretPaymentMethods(r.clientSecret,l)}}let s=this.getElements(r);e==="payment"&&r.clientSecret&&(this.verifiedClientSecret=r.clientSecret,this.verifiedPaymentMethodTypesKey=he(r.paymentMethodTypes));let o=Ne(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=s.create(o,i);return Ve(a)}getElement(e){if(!this.elements)return null;let t=Ne(e),r=this.elements.getElement(t);return r?Ve(r):null}async submitElements(){if(!this.stripe||!this.elements)return{error:new y("Stripe not initialized","api_error")};let{error:e}=await this.elements.submit();return e?{error:new y(e.message??"Validation failed","validation_error")}:{}}async confirmPayment(e){if(!this.stripe||!this.elements)throw new y("StripeAdapter not initialized or no elements created.","api_error");let t=e.billingDetails,r=t?Ut(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 y(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 y("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 y("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 y(o.message??"PayPal payment failed","validation_error",{code:o.code})}}let r;try{let o=await new S(t).createSessionIntent(e.sessionId,e.nonce??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"});if(o.provider!=="stripe")throw new y("Invalid provider returned for PayPal intent","api_error");r=o.clientSecret}catch(o){return{status:"failed",error:o instanceof y?o:new y("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 S(t).reportSessionIntentDecline(e.sessionId,e.nonce,{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:s.code??"provider_declined"})}catch{}return{status:"failed",error:new y(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 y("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 y(i.message??"Failed to retrieve PayPal payment","api_error")};if(o&&(o.status==="requires_capture"||o.status==="succeeded")){let a=typeof o.payment_method=="string"?o.payment_method:o.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:o.status,paymentIntentId:o.id,paymentMethodId:a}}return{status:"failed",error:new y("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:ne(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 v,classifyTelemetryFailure as fe,resolveBillingApiUrl as Qe,SDK_VERSION as Ht}from"@flopay/shared";import{FloPayError as Lt}from"@flopay/shared";var $=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 Lt("At least one supported non-card payment method is required.","validation_error",{param:"paymentMethodTypes"});r.paymentMethodTypes=a}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 Nt,buildTelemetryLogEvent as Vt,buildTelemetryTerminalEvent as ze,FloPayError as Be,resolveBillingApiUrl as Ke,SDK_VERSION as je}from"@flopay/shared";var ge="flopay-vault",He={ready:["vault.widget.ready","vault_ready"],submitting:["vault.submission.started","vault_submit"],blocked:["operation.state_transition","vault_submit"],action_required:["vault.action.required","three_ds_handoff"]};function G(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 oe(n,e){return Vt({eventId:"11111111-1111-4111-8111-111111111111",name:n,stage:e,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}function $e(n){return n?{errorCode:"VAULT_SUBMIT_FAILED",stage:"vault_submit",failureCategory:"provider_runtime"}:{errorCode:"VAULT_LOAD_FAILED",stage:"vault_mount",failureCategory:"provider_runtime"}}function Bt(n,e){if(n==="complete"||n==="decline")return ze({eventId:"22222222-2222-4222-8222-222222222222",outcome:n==="complete"?"payment_succeeded":"payment_declined",sequence:0,provider:"pcivault",paymentMethodCategory:"card"});if(n==="error"){let s=$e(e);return Nt({eventId:"33333333-3333-4333-8333-333333333333",...s,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}let[t,r]=He[n];return oe(t,r)}function Kt(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===ge&&(e.type==="ready"||e.type==="submitting"||e.type==="blocked"||e.type==="complete"||e.type==="decline"||e.type==="error"||e.type==="action_required")}function jt(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===ge&&e.type==="validation"&&Array.isArray(e.messages)}function zt(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===ge&&e.type==="resize"&&typeof e.height=="number"&&Number.isFinite(e.height)}var U=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 f({billingApiUrl:Ke(),sdkVersion:je}):void 0)}async mount(e,t){if(this.ownsTelemetryReporter&&!this.telemetryReporter&&(this.telemetryReporter=new f({billingApiUrl:Ke(),sdkVersion:je})),this.mountStartedAt=this.telemetryReporter?.now?.()??C(),this.vaultReadyReported=!1,this.submissionStarted=!1,this.submissionStartedAt=null,typeof window>"u"||typeof document>"u")throw this.reportVaultLoadFailure(),new Be("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 Be("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(),G(oe("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(zt(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;this.applyHeight(r.height);return}if(jt(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;let a=r.messages.filter(l=>typeof l=="string"&&l.trim()).join(" ");this.emit("validation",{sessionId:this.config.sessionId,message:a||void 0});return}if(!Kt(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={sessionId:r.sessionId??this.config.sessionId,intentId:r.intentId,declineReason:r.declineReason,message:r.message,nextActionRedirectUrl:r.nextActionRedirectUrl};r.type==="submitting"&&(this.submissionStarted=!0,this.submissionStartedAt=this.telemetryReporter?.now?.()??C()),G(Bt(r.type,this.submissionStarted)),this.reportOutcome(r.type),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(),this.emit(r.type,i)};this.messageHandler=e,window.addEventListener("message",e)}reportOutcome(e){let t=this.telemetryReporter;if(!t)return;if(e==="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"})),e==="complete"||e==="decline"){t.log({name:"vault.terminal",stage:"completion",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:e==="complete"?"payment_succeeded":"payment_declined",provider:"pcivault",paymentMethodCategory:"card"});return}if(e==="error"){let o=$e(this.submissionStarted);t.log({name:"vault.terminal",stage:o.stage,provider:"pcivault",paymentMethodCategory:"card"}),t.error({...o,provider:"pcivault",paymentMethodCategory:"card"});return}if(e==="action_required"){t.log({name:"vault.action.required",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"}),t.log({name:"vault.three_ds.handoff",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"});let o=this.submissionStartedAt;this.submissionStartedAt=null,o!==null&&t.performance({stage:"three_ds_handoff",durationMs:Math.max(0,t.now()-o),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:"action_required",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"});return}let[r,s]=He[e];t.log({name:r,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 s=document.createElement("button");s.type="button",s.setAttribute("aria-label","Close card authentication"),s.textContent="\xD7",s.style.cssText=["position:fixed","top:20px","right:20px","width:40px","height:40px","border:0","border-radius:9999px","background:#fff","color:#0f172a","font-size:28px","line-height:40px","cursor:pointer","box-shadow:0 4px 14px rgba(0,0,0,0.25)"].join(";"),s.addEventListener("click",()=>this.abandonActionRequiredOverlay()),t.appendChild(s),t.addEventListener("click",i=>{i.target===t&&this.abandonActionRequiredOverlay()});let o=i=>{if(i.source!==r.contentWindow)return;let a=i.data;if(!a||typeof a!="object")return;let l=a;l.source==="flopay-vault-3ds-return"&&(G(oe("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",o),this.threeDsReturnHandler=o,document.body.appendChild(t),this.actionOverlay=t,G(oe("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"});G(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 Ge(n,e){let t=U;return new t(n,{reporter:e})}var Ye=Symbol.for("@flopay/js.telemetry.bridge.v1");function We(n,e,t){let r=()=>e?.now()??t();Object.defineProperty(n,Ye,{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 Je(n){return n[Ye]}function L(n){if(!n)return!1;let e=n.code?.toLowerCase()??"";return!!n.declineCode||e.includes("declin")}function $t(n){return n==="stripe"||n==="paypal"||n==="pcivault"?n:"other"}var se=class{constructor(e,t,r){this.currentElements=null;this.provider=e,this.config=t,this.telemetryReporter=r??new f({billingApiUrl:Qe(t.billingApiUrl),sdkVersion:Ht,enabled:t.telemetry!==!1}),We(this,this.telemetryReporter,C)}now(){return this.telemetryReporter?.now?.()??C()}elements(e){return this.currentElements&&this.currentElements.destroy(),this.currentElements=new $(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?Ge({sessionId:e?.sessionId},this.telemetryReporter):new U({sessionId:e?.sessionId,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"&&(L(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 v&&L(r))this.telemetryReporter?.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"});else if(r instanceof v&&r.type==="validation_error")this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal"});else{let s=fe(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"}):L(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 v&&L(t))this.telemetryReporter?.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"});else if(t instanceof v&&t.type==="validation_error")this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal"});else{let r=fe(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 v("A supported non-card payment method is required.","validation_error",{param:"paymentMethodType"});let t=this.now(),r=$t(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}):L(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 v&&L(s)?this.telemetryReporter?.terminal({outcome:"payment_declined",provider:r,paymentMethodCategory:e.paymentMethodCategory}):s instanceof v&&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 v("sessionId is required to retrieve a session.","validation_error",{param:"sessionId"});let r=await this.retrieveUnifiedSession(e,t);if(!r.data.session)throw new v("Session not found","api_error");return r.data.session}async retrieveUnifiedSession(e,t){if(!e)throw new v("sessionId is required.","validation_error",{param:"sessionId"});let r=Qe(t??this.config.billingApiUrl),s=this.now();this.telemetryReporter?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let o,i=Le(r,{now:()=>this.telemetryReporter?.now()??C(),onFirstByte:a=>{o=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 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"}),a}catch(a){let l=fe(a,a instanceof v&&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()-s,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 Xe(n,e,t){let r=se;return new r(n,e,t)}var et=new Map;function ve(n){return Array.isArray(n)?n.map(ve):n&&typeof n=="object"?Object.fromEntries(Object.entries(n).filter(([,e])=>e!==void 0).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,ve(t)])):n}function Yt(n,e){return JSON.stringify([n,Ce(e?.billingApiUrl),e?.telemetry!==!1,e?.locale??"auto",e?.apiVersion??null,ve(e?.appearance??null)])}var ie=new Map;async function Wt(n,e){if(!n){let a=new f({billingApiUrl:Ce(e?.billingApiUrl),sdkVersion:Ze,enabled:e?.telemetry!==!1});throw a.error({errorCode:"CONFIGURATION_INVALID",stage:"sdk_initialize",paymentMethodCategory:"unknown"}),a.flush().catch(()=>{}).finally(()=>a.destroy()),new Gt("A publishable key is required to initialize FloPay.","validation_error",{param:"publishableKey"})}let t=Yt(n,e),r=et.get(t);if(r)return e?.telemetry!==!1&&Je(r)?.log({name:"sdk.cache.hit",stage:"sdk_initialize"}),r;let s=ie.get(t);if(s)return s;let o={...e,publishableKey:n},i=(async()=>{let a=new f({billingApiUrl:Ce(o.billingApiUrl),sdkVersion:Ze,enabled:o.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 H;try{await c.initialize(o)}catch(_){throw a.error({errorCode:"SDK_INITIALIZATION_FAILED",failureCategory:"provider_runtime",stage:"sdk_initialize",provider:"stripe",paymentMethodCategory:"unknown"}),a.destroy(),_}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"});let d=a.now()-l;a.performance({stage:"sdk_initialize",durationMs:d,durationMode:"machine",provider:"stripe"}),a.performance({stage:"provider_ready",durationMs:d,durationMode:"machine",provider:"stripe"});let p=Xe(c,o,a);return et.set(t,p),p})();ie.set(t,i);try{return await i}finally{ie.get(t)===i&&ie.delete(t)}}import{FloPayError as N,IDEMPOTENCY_IN_PROGRESS_CODE as Jt,IDEMPOTENCY_KEY_HEADER as Qt,SDK_VERSION as tt,buildProductPayload as Xt,classifyTelemetryFailure as Zt,foldIntoProducts as er,resolveIdempotencyKey as rt,resolveSessionCurrency as tr}from"@flopay/shared";var _e=5;function rr(n,e){let t=e?.error,r=k(e?.code)??k(t?.code)??`http_${n}`,s=k(e?.message)??k(t?.message)??nr(r,n);return new N(s,"api_error",{code:r,statusCode:n})}function nr(n,e){switch(n){case"CouponLimitExceeded":return`Too many coupon codes \u2014 a checkout session accepts at most ${_e}.`;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 nt(n,e){let{billingApiUrl:t,checkoutBaseUrl:r,items:s=[],subscriptions:o=[],products:i,account:a,successUrl:l,cancelUrl:c,checkoutMode:d="confirm",couponCodes:p=[],tagsData:_,redirectParams:h={},setCookie:T=!0,timeoutMs:w=12e3,clientId:P,currency:we,utmMetadata:E,idempotencyKey:u}=n,V=rt(u);if(p.length>_e)throw new N(`Too many coupon codes \u2014 a checkout session accepts at most ${_e}.`,"validation_error",{code:"CouponLimitExceeded",param:"couponCodes"});let A=i??er(s,o),M=tr(we,s,o,A);if(!M)throw new N("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 B={clientId:P,checkoutVersion:tt,successUrl:l,cancelUrl:c,currency:M,checkoutMode:d,products:A.map(b=>Xt(b,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};_&&(B.tagsData=_),E?.length&&(B.utmMetadata=E);let ae=`${t.replace(/\/+$/,"")}/v1/checkouts/sessions`,I=new AbortController,le=setTimeout(()=>I.abort(),w),Pe={"Content-Type":"application/json"};V&&(Pe[Qt]=V);let x,W;try{let b=await fetch(ae,{method:"POST",headers:Pe,body:JSON.stringify(B),signal:I.signal});try{e?.(b.status)}catch{}x=b.status;try{W=await b.json()}catch{}}finally{clearTimeout(le)}if(x>=400)throw rr(x,W);if(x===201){let b=W?.data?.uuid,ce=W?.data?.nonce;if(!b)throw new Error("Checkout session created but no UUID was returned by the billing API");if(!ce)throw new N("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"});(A.length||M)&&D(b,{currency:M,products:A.map(g=>({code:g.code??g.providerItemId??g.providerPlanId,type:g.type,name:g.name??g.itemName??g.providerItemName??g.subscriptionName??g.providerPlanName??null,totalAmount:g.totalAmount,overrideAmount:g.overrideAmount,currency:g.currency??M}))});let J=new URL(`${r.replace(/\/+$/,"")}/secure`);J.searchParams.set("id",b);for(let[g,Q]of Object.entries(h))J.searchParams.set(g,Q);if(T&&typeof window<"u"&&typeof document<"u"){let g=JSON.stringify({origin_url:c}),Q=window.location.hostname.split(".").slice(-2).join(".");document.cookie=`checkout_data=${encodeURIComponent(g)}; domain=.${Q}; path=/; max-age=3600; SameSite=Lax; Secure;`,document.cookie=`flopay_checkout_token=${encodeURIComponent(ce)}; domain=.${Q}; path=/; max-age=3600; SameSite=Lax; Secure;`}return typeof window<"u"&&(window.location.href=J.toString()),{status:201,redirectUrl:J.toString(),nonce:ce}}return x===204?(typeof window<"u"&&(window.location.href=l),{status:204}):{status:x}}async function or(n){let e=st(n),t=ot(e);try{let r=await nt(n,t);return it(e,r),r}catch(r){throw Te(e.reporter,r),r}finally{Y(e.reporter)}}function ot(n){let e=!1;return t=>{if(e)return;e=!0;let r=`${Math.floor(t/100)}xx`;n.reporter.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:r}),n.reporter.performance({stage:"session_first_byte",durationMs:n.reporter.now()-n.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:r})}}function st(n){let e=new f({billingApiUrl:n.billingApiUrl,sdkVersion:tt,enabled:n.telemetry!==!1}),t=e.now();return e.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"}),{reporter:e,startedAt:t}}function it(n,e){let t=`${Math.floor(e.status/100)}xx`;n.reporter.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_create",statusClass:t}),n.reporter.performance({stage:"session_complete",durationMs:n.reporter.now()-n.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:t})}function Te(n,e){let t=Zt(e,"CHECKOUT_SESSION_CREATE_FAILED");if(e instanceof N&&e.type==="validation_error"){n.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"});return}if(t.statusClass==="4xx"){n.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create",statusClass:"4xx"});return}n.error({...t,stage:"session_create",requestCategory:"session_create"})}function Y(n){n.flush().catch(()=>{}).finally(()=>n.destroy())}async function sr(n){let{maxRetries:e=3,...t}=n,r=st(n),s=ot(r);if(!Number.isFinite(e)||!Number.isInteger(e)||e<=0)throw r.reporter.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),Y(r.reporter),new Error("Number of retries must be greater than 0");let o={...t,idempotencyKey:rt(t.idempotencyKey)},i;for(let a=0;a<=e;a++)try{let l=await nt(o,s);return it(r,l),Y(r.reporter),l}catch(l){i=l;let c=l instanceof Error&&l.name==="AbortError",d=l instanceof N&&l.code===Jt;if((c||d)&&a<e){r.reporter.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:a+1}),await new Promise(p=>setTimeout(p,100*Math.pow(2,a)));continue}throw Te(r.reporter,l),Y(r.reporter),l}throw Te(r.reporter,i),Y(r.reporter),i??new Error("Unknown error during checkout session creation")}export{se as FloPay,$ as FloPayElements,S as PaymentAPI,U as PciVaultCardCapture,H as StripeAdapter,D as cacheSessionDisplayData,pe as clearSessionDisplayData,or as createCheckoutSession,sr as createCheckoutSessionWithRetries,ue as getSessionDisplayData,Wt as loadFloPay,Ot as toStripeAppearance,ne as toStripeAppearanceTheme};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flopay/js",
3
- "version": "1.4.10",
3
+ "version": "1.4.12",
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.10"
30
+ "@flopay/shared": "1.4.12"
31
31
  },
32
32
  "devDependencies": {
33
33
  "jsdom": "^29.1.1",