@flopay/js 1.4.12 → 1.4.13
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 +12 -3
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +6 -3
- package/dist/index.d.ts +6 -3
- package/dist/index.mjs +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -175,7 +175,12 @@ const result = await createCheckoutSession({
|
|
|
175
175
|
// On 204: browser redirects to successUrl (payment method on file)
|
|
176
176
|
```
|
|
177
177
|
|
|
178
|
-
Use `createCheckoutSessionWithRetries` for automatic retry with
|
|
178
|
+
Use `createCheckoutSessionWithRetries` for automatic retry with jittered
|
|
179
|
+
exponential backoff on transient transport, timeout, and idempotency-in-progress
|
|
180
|
+
errors. By default it makes at most two retries (three total attempts). A single
|
|
181
|
+
12-second total deadline (customizable with `timeoutMs`) covers the initial
|
|
182
|
+
request, every retry, and all backoff; all attempts receive the same
|
|
183
|
+
`AbortSignal`.
|
|
179
184
|
|
|
180
185
|
#### Idempotent checkout creation
|
|
181
186
|
|
|
@@ -210,7 +215,11 @@ in-progress reply — replay the same key. A payload-conflict (`409`) is surface
|
|
|
210
215
|
without retrying. The header is optional on the backend: older SDKs and direct
|
|
211
216
|
API clients that omit it keep the legacy, unkeyed path. The same automatic and
|
|
212
217
|
merchant-supplied behavior applies to inline session creation via
|
|
213
|
-
`PaymentAPI.createAndFetchSession` (used by `@flopay/react`).
|
|
218
|
+
`PaymentAPI.createAndFetchSession` (used by `@flopay/react`). Inline creation
|
|
219
|
+
uses the same 12-second total deadline and jitter policy, with one shared
|
|
220
|
+
three-attempt budget across network failures and idempotency-in-progress
|
|
221
|
+
responses. Pass `timeoutMs` in the inline session params to choose a different
|
|
222
|
+
UX ceiling.
|
|
214
223
|
|
|
215
224
|
`@flopay/shared` also exports the primitives directly if you build your own
|
|
216
225
|
create flow: `generateIdempotencyKey()`, `resolveIdempotencyKey(supplied?)`,
|
|
@@ -291,7 +300,7 @@ events remain serializable for backend rollout compatibility.
|
|
|
291
300
|
| `PciVaultCardCapture` | `CardCaptureAdapter` implementation that injects the backend-served hosted vault card widget. See [Vault card capture](#vault-card-capture). |
|
|
292
301
|
| `PaymentAPI` | Billing API client. Includes session retrieval/creation, vault recovery, `/process`, `createSessionIntent()`, `reportSessionIntentDecline()`, completion polling, and saved-payment lookup. |
|
|
293
302
|
| `createCheckoutSession(options)` | Creates a checkout session and redirects. Returns `CheckoutSessionResult`. |
|
|
294
|
-
| `createCheckoutSessionWithRetries(options)` | Same as above with
|
|
303
|
+
| `createCheckoutSessionWithRetries(options)` | Same as above with two retries by default (three total attempts) under one total deadline with jittered exponential backoff. |
|
|
295
304
|
| `toStripeAppearance(appearance)` | Normalizes a `FloPayAppearance` into a `StripeSafeAppearance` by mapping FloPay's public `theme` token (`'default' \| 'flat' \| 'night' \| 'none'`) onto Stripe's accepted set (`'stripe' \| 'flat' \| 'night'`). Use at any site that hands an appearance to `@stripe/react-stripe-js`'s `<Elements>` so `theme: 'default'` never reaches Stripe.js (which would warn and silently fall back). `variables`/`rules` pass through untouched. `StripeAdapter` applies this normalization internally. |
|
|
296
305
|
| `toStripeAppearanceTheme(theme)` | Lower-level helper backing `toStripeAppearance`: maps a single FloPay `theme` token to Stripe's. |
|
|
297
306
|
|
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 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});
|
|
1
|
+
"use strict";var ge=Object.defineProperty;var nt=Object.getOwnPropertyDescriptor;var ot=Object.getOwnPropertyNames;var st=Object.prototype.hasOwnProperty;var it=(n,e)=>{for(var t in e)ge(n,t,{get:e[t],enumerable:!0})},at=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ot(e))!st.call(n,s)&&s!==t&&ge(n,s,{get:()=>e[s],enumerable:!(r=nt(e,s))||r.enumerable});return n};var lt=n=>at(ge({},"__esModule",{value:!0}),n);var Vt={};it(Vt,{FloPay:()=>ee,FloPayElements:()=>$,PaymentAPI:()=>O,PciVaultCardCapture:()=>V,SESSION_CREATE_TELEMETRY:()=>Te,StripeAdapter:()=>H,cacheSessionDisplayData:()=>U,clearSessionDisplayData:()=>le,createCheckoutSession:()=>Qe,createCheckoutSessionWithRetries:()=>tt,getSessionDisplayData:()=>ae,loadFloPay:()=>Ye,toStripeAppearance:()=>Le,toStripeAppearanceTheme:()=>X});module.exports=lt(Vt);var A=require("@flopay/shared");var Ue=require("@stripe/stripe-js"),y=require("@flopay/shared");var d=require("@flopay/shared");function q(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 ct="flopay_session_display:";var se=new Map;function ie(n){return`${ct}${n}`}function fe(){if(typeof window>"u")return null;try{return window.sessionStorage}catch{return null}}function U(n,e,t){if(!n)return;let r=t?.ttlMs??36e5,s={data:e,expiresAt:Date.now()+r},o=fe();if(o)try{o.setItem(ie(n),JSON.stringify(s));return}catch{}se.set(n,s)}function ae(n){if(!n)return null;let e=fe();if(e)try{let r=e.getItem(ie(n));if(r){let s=JSON.parse(r);if(s&&typeof s.expiresAt=="number"&&s.expiresAt>Date.now())return s.data;e.removeItem(ie(n))}}catch{}let t=se.get(n);if(t){if(t.expiresAt>Date.now())return t.data;se.delete(n)}return null}function le(n){if(!n)return;se.delete(n);let e=fe();if(e)try{e.removeItem(ie(n))}catch{}}var P=require("@flopay/shared"),dt="/v1/sdk-telemetry/events",Ce=16,ut=64,pt=1500,Me=1e3,mt=64,yt="00000000-0000-4000-8000-000000000000",ht={technical_error:8,lifecycle:32,expected_outcome:32,performance:24};function j(){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 gt(n){try{return new TextEncoder().encode(n).byteLength}catch{return n.length}}function ft(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 E(){return globalThis.performance?.now()??0}var w=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(/\/+$/,"")}${dt}`,this.sdkPackage=e.sdkPackage??"@flopay/js",this.sdkVersion=e.sdkVersion,this.correlationId=j(),this.merchantEnabled=e.enabled!==!1,this.clock=e.clock??E,this.browserTransportAvailable=typeof window<"u"&&typeof document<"u",this.browserTransportAvailable&&(window.addEventListener("pagehide",this.pageExitHandler),document.addEventListener("visibilitychange",this.visibilityHandler))}log(e){this.canCollect()&&this.enqueue((0,P.buildTelemetryLogEvent)({...this.checkoutContext,...e,eventId:j(),sequence:this.sequence++}))}error(e){if(!this.canCollect())return;let t=(0,P.buildTelemetryErrorEvent)({...this.checkoutContext,...e,eventId:yt,sequence:0}),r=ft(t),s=this.now();this.pruneReportedFailures(s);let o=this.reportedFailures.get(r);if(o!==void 0&&s>=o&&s-o<Me){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,P.buildTelemetryErrorEvent)({...this.checkoutContext,...e,eventId:j(),sequence:this.sequence++}))}performance(e){this.canCollect()&&this.enqueue((0,P.buildTelemetryPerformanceEvent)({...this.checkoutContext,...e,eventId:j(),sequence:this.sequence++}))}terminal(e){if(this.canCollect()&&(this.enqueue((0,P.buildTelemetryTerminalEvent)({...this.checkoutContext,...e,eventId:j(),sequence:this.sequence++})),e.outcome!=="action_required"&&this.checkoutStartedAt!==null)){let t=this.checkoutStartedAt;this.checkoutStartedAt=null,this.performance({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 E()}}pruneReportedFailures(e){for(let[t,r]of this.reportedFailures)(e<r||e-r>=Me)&&this.reportedFailures.delete(t)}rememberReportedFailure(e,t){for(;this.reportedFailures.size>=mt;){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>=ut||this.eventCounts[e.class]>=ht[e.class])){if(this.eventCounts[e.class]+=1,this.queue.push(e),this.queue.length>=Ce){this.flush();return}this.scheduleFlush()}}canCollect(){return this.browserTransportAvailable&&this.merchantEnabled&&!this.ingestionDisabled&&!this.destroyed}async flush(){if(this.flushInFlight)return this.flushInFlight;if(!this.browserTransportAvailable||this.destroyed||this.ingestionDisabled||this.queue.length===0)return;this.clearFlushTimer();let e=this.queue.splice(0,Ce);return this.flushInFlight=this.sendBatch(e).finally(()=>{this.flushInFlight=null,this.queue.length>0&&this.scheduleFlush()}),this.flushInFlight}destroy(){this.destroyed||(this.drainQueue(),this.destroyed=!0,this.clearFlushTimer(),this.browserTransportAvailable&&(window.removeEventListener("pagehide",this.pageExitHandler),document.removeEventListener("visibilitychange",this.visibilityHandler)),this.queue.splice(0),this.reportedFailures.clear())}disable(){this.merchantEnabled=!1,this.queue.splice(0),this.reportedFailures.clear(),this.clearFlushTimer()}drainQueue(){if(!(!this.browserTransportAvailable||this.destroyed||this.ingestionDisabled||this.queue.length===0))for(this.clearFlushTimer();this.queue.length>0;){let e=this.queue.splice(0,Ce);this.sendBatch(e)}}async sendBatch(e){if(!this.browserTransportAvailable||this.ingestionDisabled)return;let t=(0,P.serializeTelemetryBatch)(e,{correlationId:this.correlationId,sdkPackage:this.sdkPackage,sdkVersion:this.sdkVersion,batchId:j()});if(gt(t)>P.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 a=>a.status!==202?null:(await a.json().catch(()=>null))?.status==="disabled"?"disabled":null).catch(()=>null),i=new Promise(a=>{s=setTimeout(()=>{r?.abort(),a(null)},pt)});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)}},Ee=Symbol.for("@flopay/js.telemetry.reporter-factory.v1"),ke=globalThis;ke[Ee]===void 0&&Object.defineProperty(ke,Ee,{configurable:!0,enumerable:!1,writable:!1,value:n=>new w(n)});function J(n=12e3){let e=Number.isFinite(n)&&n>=0?n:12e3,t=new AbortController,r=setTimeout(()=>t.abort(),e);return{signal:t.signal,clear:()=>clearTimeout(r)}}function Ct(){return Object.assign(new Error("The operation was aborted."),{name:"AbortError"})}function Q(n,e){let t=150*2**n,r=Math.round(t*(.75+Math.random()*.5));return new Promise((s,o)=>{let i,l=()=>e.removeEventListener("abort",a),a=()=>{i!==void 0&&clearTimeout(i),l(),o(Ct())};if(e.aborted){a();return}i=setTimeout(()=>{l(),s()},r),e.addEventListener("abort",a,{once:!0})})}var Re=1e3,Tt=500,_t=15e3,wt=3e3,bt=1e4,St=1e4;function De(n){return typeof n=="object"&&n!==null}function z(n,e){return q(n?.[e])}function Ae(n,e){return Pe(n?.[e])}function Pt(n,e){let t=n?.[e];return typeof t=="number"&&Number.isFinite(t)?t:void 0}function xe(n){return new Promise(e=>setTimeout(e,n))}function ce(){return new d.FloPayError("Checkout is still processing. Please try again shortly.","api_error",{code:"checkout_processing_timeout"})}async function K(n,e){let t=await n.json().catch(()=>null),r=De(t?.error)?t.error:null,s=Ae(t,"message")??Ae(r,"message")??e,o=z(t,"code")??z(t,"gatewayErrorCode")??z(r,"code")??`http_${n.status}`;return new d.FloPayError(s,"api_error",{code:o,statusCode:n.status})}async function Mt(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 De(e)&&Array.isArray(e.fields)?"validation_rejected":"payment_declined"}function Ie(n){return n===400||n===422}var de=2;async function ve(n,e,t=de,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 xe(150*2**o)}}var Te=Symbol.for("@flopay/js.session-create.telemetry.v1");function Et(n){return n[Te]}function kt(n){return"now"in n||"onFirstByte"in n||"onSessionCreateFailure"in n||"onRetry"in n}var L=class L{constructor(e,t={}){this.baseUrl=e.replace(/\/+$/,"");let r=kt(t);this.telemetryHooks=r?t:void 0,this.directTelemetry=r||t.telemetry===!1?void 0:new w({billingApiUrl:this.baseUrl,sdkVersion:d.SDK_VERSION})}destroy(){this.directTelemetry?.destroy()}reportDirectFailure(e,t,r,s,o="unknown"){let i=(0,d.classifyTelemetryFailure)(e,t);this.directTelemetry?.error({...i,stage:r,requestCategory:s,paymentMethodCategory:o})}reportAccountSnapshotFailure(e,t){let r=(0,d.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED");if(t==="best_effort"&&r.errorCode==="REQUEST_TIMEOUT"){this.directTelemetry?.log({name:"operation.fallback",stage:"processing",requestCategory:"account_snapshot",statusClass:"timeout"});return}this.directTelemetry?.error({...r,stage:"processing",requestCategory:"account_snapshot",paymentMethodCategory:"unknown"})}telemetryTimestamp(){try{return this.telemetryHooks?.now?.()??this.directTelemetry?.now()??E()}catch{return E()}}beginDirectTelemetryCheckout(e){!this.directTelemetry||this.directTelemetryCheckoutId===e||(this.directTelemetryCheckoutId=e,this.directTelemetry.beginCheckout())}beginDirectTelemetryOperation(){this.directTelemetry&&(this.directTelemetryCheckoutId=void 0,this.directTelemetry.beginCheckout())}adoptDirectTelemetryCheckout(e){e&&(this.directTelemetryCheckoutId=e)}async getCheckoutSession(e,t){this.beginDirectTelemetryCheckout(e);let r=this.telemetryTimestamp();this.directTelemetry?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let s={[d.FLO_SDK_VERSION_HEADER]:d.SDK_VERSION};t&&(s["x-checkout-session-token"]=t);try{let o=await ve(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}`,{headers:s},de,c=>{this.telemetryHooks?.onRetry?.("session_read",c),this.directTelemetry?.log({name:"operation.retry",stage:"session_read",requestCategory:"session_read",attempt:c})}),i=Math.max(0,this.telemetryTimestamp()-r);try{this.telemetryHooks?.onFirstByte?.(i)}catch{}let l=`${Math.floor(o.status/100)}xx`;if(this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:l}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:i,durationMode:"machine",requestCategory:"session_read",statusClass:l}),!o.ok)throw await K(o,"Failed to get checkout session");let a=await o.json();return this.directTelemetry?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:l}),this.directTelemetry?.performance({stage:"session_complete",durationMs:Math.max(0,this.telemetryTimestamp()-r),durationMode:"machine",requestCategory:"session_read",statusClass:l}),{...a,data:this.mergeCachedDisplayData(a.data)}}catch(o){throw this.directTelemetry?.error({...(0,d.classifyTelemetryFailure)(o,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"}),o}}cacheSessionDisplayData(e,t,r){U(e,t,r)}clearSessionDisplayData(e){le(e)}async getVaultCapture(e,t){let r=`${this.baseUrl}\0${e}\0${t??""}`,s=L.activeVaultCaptureRequests.get(r);if(s)return s;let o=this.requestVaultCapture(e,t);L.activeVaultCaptureRequests.set(r,o);try{return await o}finally{L.activeVaultCaptureRequests.get(r)===o&&L.activeVaultCaptureRequests.delete(r)}}async requestVaultCapture(e,t){let r=new AbortController,s=setTimeout(()=>r.abort(),St);this.beginDirectTelemetryCheckout(e);let o=this.telemetryTimestamp();this.directTelemetry?.log({name:"vault.capture.requested",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card"});let i={"Content-Type":"application/json"};t&&(i["x-checkout-session-token"]=t);try{let l=await ve(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/vault/capture`,{method:"POST",headers:i,signal:r.signal},de,c=>{this.telemetryHooks?.onRetry?.("vault_capture",c),this.directTelemetry?.log({name:"operation.retry",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card",attempt:c})});if(!l.ok)throw await K(l,"Failed to load the secure card form");let a=await l.json();return this.directTelemetry?.performance({stage:"vault_request",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"2xx"}),this.toVaultBlock(a)}catch(l){let a=r.signal.aborted?new d.FloPayError("Timed out while loading the secure card form. Please try again.","api_error",{code:"vault_capture_timeout"}):l;throw this.reportDirectFailure(a,"VAULT_LOAD_FAILED","vault_request","vault_capture","card"),a}finally{clearTimeout(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 d.FloPayError("processPayment requires `nonce` \u2014 pass the value returned from session creation.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let s=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.processing.started",stage:"processing",requestCategory:"process_payment"});let{nonce:o,...i}=t,l;try{l=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(t.sessionId)}/process`,{method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":o},body:JSON.stringify(i)})}catch(a){throw this.reportDirectFailure(a,"PAYMENT_PROCESSING_FAILED","processing","process_payment"),a}if(!l.ok&&l.status!==202){let a=await Mt(l);return a?this.directTelemetry?.terminal({outcome:a,stage:"processing",requestCategory:"process_payment",statusClass:"4xx"}):this.directTelemetry?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",requestCategory:"process_payment",statusClass:(0,d.telemetryStatusClass)(l.status),failureCategory:l.status>=500?"server_error":void 0}),l}try{let a=await this.resolveProcessResponse(l,t.sessionId,{...r,nonce:o});return this.directTelemetry?.log({name:"payment.processing.completed",stage:"processing",requestCategory:"process_payment",statusClass:(0,d.telemetryStatusClass)(a.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"process_payment",statusClass:(0,d.telemetryStatusClass)(a.status)}),a}catch(a){throw a instanceof d.FloPayError&&a.code==="checkout_processing_timeout"||this.reportDirectFailure(a,"PAYMENT_PROCESSING_FAILED","processing","process_payment"),a}}async patchAccountSnapshot(e,t,r,s){this.beginDirectTelemetryCheckout(e);let o=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.state_transition",stage:"processing",requestCategory:"account_snapshot"});let i=s?.timeoutMs??bt,l=new AbortController,a=()=>l.abort();s?.signal&&(s.signal.aborted?l.abort():s.signal.addEventListener("abort",a,{once:!0}));let c=setTimeout(()=>l.abort(),i);try{let u;try{u=await ve(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/account`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":t},body:JSON.stringify(r),signal:l.signal},de,f=>{this.telemetryHooks?.onRetry?.("account_snapshot",f),this.directTelemetry?.log({name:"operation.retry",stage:"processing",requestCategory:"account_snapshot",attempt:f})})}finally{clearTimeout(c),s?.signal?.removeEventListener("abort",a)}if(!u.ok)throw await K(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 d.FloPayError("createSessionIntent requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let o=r,i=o.paymentMethodType,l=typeof i=="string"&&i.trim().toLowerCase()==="card",a=typeof i=="string"&&i.length>0&&!l&&(typeof o.paymentMethodId=="string"||o.paymentMethodId===null),c=o.provider==="stripe"&&(o.paymentMethodCategory==="wallet"||o.paymentMethodCategory==="apm")&&(o.intentKind==="payment"||o.intentKind==="setup"),u=o.provider==="paypal"&&o.paymentMethodCategory==="wallet"&&o.paymentMethodType==="paypal"&&o.paymentMethodId===null&&o.intentKind==="payment";if(!a||!c&&!u)throw new d.FloPayError("Only wallet, APM, and PayPal session intents are supported.","validation_error",{code:"InvalidSessionIntentRequest"});let f=o.authorizationAttemptId;if(f!==void 0&&!(0,d.isUuidV4)(f))throw new d.FloPayError("authorizationAttemptId must be a v4 UUID identifying one buyer authorization attempt.","validation_error",{code:"InvalidAuthorizationAttemptId",param:"authorizationAttemptId"});let b=(0,d.isUuidV4)(f)?f:(0,d.randomUuidV4)();this.beginDirectTelemetryCheckout(e);let _=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.intent.started",stage:"processing",requestCategory:"intent_create"});let C={"Content-Type":"application/json","x-checkout-session-token":t,[d.IDEMPOTENCY_KEY_HEADER]:s?.idempotencyKey||b},R=!1;try{let k=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents`,{method:"POST",headers:C,body:JSON.stringify({...r,authorizationAttemptId:b}),signal:s?.signal});if(!k.ok){R=!0;let B=await K(k,"Failed to create checkout intent"),x=(0,d.classifyTelemetryFailure)(B,"PAYMENT_PROCESSING_FAILED");throw Ie(B.statusCode)?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"intent_create",statusClass:"4xx"}):this.directTelemetry?.error({...x,stage:"processing",requestCategory:"intent_create"}),B}let S=(await k.json()).data;if(!S||typeof S!="object")throw new d.FloPayError("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});let p=S,M=p.paymentMethodType,I=(p.paymentMethodCategory==="wallet"||p.paymentMethodCategory==="apm")&&typeof M=="string"&&M.trim().toLowerCase()!=="card"&&(typeof p.paymentMethodId=="string"||p.paymentMethodId===null)&&typeof p.providerObjectId=="string",D=p.provider==="stripe"&&(p.intentKind==="payment"||p.intentKind==="setup")&&typeof p.clientSecret=="string",W=p.provider==="paypal"&&p.paymentMethodCategory==="wallet"&&p.paymentMethodType==="paypal"&&p.paymentMethodId===null&&p.intentKind==="payment"&&(p.providerObjectType==="order"||p.providerObjectType==="subscription")&&p.clientSecret===null,ye=p.provider===r.provider&&p.paymentMethodCategory===r.paymentMethodCategory&&p.paymentMethodType===r.paymentMethodType&&p.paymentMethodId===r.paymentMethodId&&p.intentKind===r.intentKind;if(!I||!D&&!W||!ye)throw new d.FloPayError("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});return this.directTelemetry?.log({name:"payment.intent.completed",stage:"processing",requestCategory:"intent_create",statusClass:(0,d.telemetryStatusClass)(k.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-_),durationMode:"machine",requestCategory:"intent_create",statusClass:(0,d.telemetryStatusClass)(k.status)}),p}catch(k){throw R||this.reportDirectFailure(k,"PAYMENT_PROCESSING_FAILED","processing","intent_create"),k}}async reportSessionIntentDecline(e,t,r,s){if(!t)throw new d.FloPayError("reportSessionIntentDecline requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let o=r,i=o.providerDeclineReason,l=o.paymentMethodType,a=typeof i=="string"&&/^[a-z0-9][a-z0-9_.:-]{0,63}$/i.test(i)&&!/^(?:pm|pi|seti|tok|src|cus|sess|sk|pk)_/i.test(i),c=typeof l=="string"&&l.length>0&&l.trim().toLowerCase()!=="card"&&a,u=o.provider==="stripe"&&(o.paymentMethodCategory==="wallet"||o.paymentMethodCategory==="apm"),f=o.provider==="paypal"&&o.paymentMethodCategory==="wallet"&&o.paymentMethodType==="paypal";if(!c||!u&&!f)throw new d.FloPayError("Invalid non-card decline classification.","validation_error",{code:"InvalidSessionIntentDeclineRequest"});let b=f?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:i}:{provider:"stripe",paymentMethodCategory:o.paymentMethodCategory,paymentMethodType:o.paymentMethodType,providerDeclineReason:i},_=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(b),signal:s?.signal});if(!_.ok)throw await K(_,"Failed to report checkout decline")}async getPaymentsByEmail(e,t){this.beginDirectTelemetryOperation();let r=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved"});let s=t?.page??1,o=t?.limit??1,i=new URLSearchParams({email:e,page:String(s),limit:String(o),sortField:"createdAt",sortDirection:"DESC"});try{let l=await fetch(`${this.baseUrl}/v1/payments?${i.toString()}`,{method:"GET",signal:t?.signal,keepalive:!0});if(!l.ok)throw new d.FloPayError("Failed to fetch payments","api_error",{statusCode:l.status});let a=await l.json();return this.directTelemetry?.log({name:"operation.recovery.completed",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),this.directTelemetry?.performance({stage:"recovery",durationMs:Math.max(0,this.telemetryTimestamp()-r),durationMode:"machine",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),a}catch(l){throw this.reportDirectFailure(l,"RECOVERY_FAILED","recovery","other","saved"),l}}async createAndFetchSession(e){this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp(),r=J(e.timeoutMs??12e3),s={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});try{let o=await this.createAndFetchSessionRequest(e,t,r.signal,s);return this.adoptDirectTelemetryCheckout(o.data.session?.id),this.directTelemetry?.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:s.statusClass}),this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:"session_create",statusClass:s.statusClass,attempt:s.attempt}),o}catch(o){if(!(o instanceof d.FloPayError&&o.code==="session_auto_completed"))try{this.telemetryHooks?.onSessionCreateFailure?.(o)}catch{}let i=(0,d.classifyTelemetryFailure)(o,"CHECKOUT_SESSION_CREATE_FAILED");throw this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:"session_create",statusClass:i.statusClass,attempt:s.attempt}),o instanceof d.FloPayError&&o.type==="validation_error"?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}):o instanceof d.FloPayError&&Ie(o.statusCode)?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create",statusClass:"4xx"}):o instanceof d.FloPayError&&o.code==="session_auto_completed"||this.directTelemetry?.error({...i,stage:"session_create",requestCategory:"session_create"}),o}finally{r.clear()}}async createAndFetchSessionRequest(e,t,r,s){let o=e.products??(0,d.foldIntoProducts)(e.items,e.subscriptions),i=(0,d.resolveSessionCurrency)(e.currency,e.items,e.subscriptions,o);if(!i)throw new d.FloPayError("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});let l={clientId:e.clientId,checkoutVersion:d.SDK_VERSION,successUrl:e.successUrl,cancelUrl:e.cancelUrl,currency:i,checkoutMode:e.checkoutMode??"full",products:o.map(h=>(0,d.buildProductPayload)(h,i)),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&&(l.tokenizedData=e.tokenizedData),e.tagsData&&(l.tagsData=e.tagsData),e.utmMetadata?.length&&(l.utmMetadata=e.utmMetadata),e.avsCheck!==void 0&&(l.avsCheck=e.avsCheck),e.checkoutType&&(l.checkoutType=e.checkoutType),e.checkoutLayout&&(l.checkoutLayout=e.checkoutLayout),e.avsConfig&&(l.avsConfig=e.avsConfig);let a={"Content-Type":"application/json",[d.FLO_SDK_VERSION_HEADER]:d.SDK_VERSION},c=(0,d.resolveIdempotencyKey)(e.idempotencyKey);c&&(a[d.IDEMPOTENCY_KEY_HEADER]=c);let u,f=!1,b=Et(e),_=h=>{try{this.telemetryHooks?.onRetry?.("session_create",h),this.directTelemetry?.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:h})}catch{}};for(let h=0;h<3;h++){s.attempt=h;try{b?.onAttempt?.(h)}catch{}try{u=await fetch(`${this.baseUrl}/v1/checkouts/sessions?expand=true`,{method:"POST",headers:a,body:JSON.stringify(l),signal:r})}catch(M){if(s.statusClass=r.aborted||M instanceof Error&&M.name==="AbortError"?"timeout":"network_error",r.aborted||M instanceof Error&&M.name==="AbortError"||h>=2)throw M;let I=h+1;_(I),await Q(h,r);continue}let S=(0,d.telemetryStatusClass)(u.status);if(s.statusClass=S,f||(f=!0,this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:S,attempt:h}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:"session_create",statusClass:S,attempt:h})),u.status===204)throw new d.FloPayError("Session auto-completed \u2014 payment method already on file","api_error",{code:"session_auto_completed"});if(u.ok)break;let p=await K(u,"Failed to create checkout session");if(p.code===d.IDEMPOTENCY_IN_PROGRESS_CODE&&h<2){_(h+1),await Q(h,r);continue}throw p}if(!u)throw new TypeError("Checkout-session creation exhausted its retry budget.");let C=await u.json();if(C.data&&"gateways"in C.data){this.autoCacheDisplayData(C.data.uuid,e);let h=this.mergeCachedDisplayData(C.data),S=this.normalizeRawSession(h);return C.vault&&S.data.session&&(S.data.session.vault=this.toVaultBlock(C.vault)),{...S,autoProcessingError:C.autoProcessingError,autoProcessingAttempted:C.autoProcessingAttempted,autoProcessingPending:C.autoProcessingPending}}let R=C.data?.uuid;if(!R)throw new d.FloPayError("No session ID returned","api_error",{code:"InvalidCheckoutSessionResponse"});return this.autoCacheDisplayData(R,e),this.adoptDirectTelemetryCheckout(R),{...await this.getUnifiedCheckoutSession(R),autoProcessingError:C.autoProcessingError,autoProcessingAttempted:C.autoProcessingAttempted,autoProcessingPending:C.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??_t,o=Date.now()+s,i=this.clampRetryAfterMs(t?.initialDelayMs??Re),l=0;try{for(;;){let a=o-Date.now();if(a<=0)throw ce();if(i>0){try{l+=1,this.telemetryHooks?.onRetry?.("session_read",l),this.directTelemetry?.log({name:"operation.retry",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:"saved",attempt:l})}catch{}if(await xe(Math.min(i,a)),Date.now()>=o)throw ce()}let c=await this.getUnifiedCheckoutSession(e,t?.nonce),u=c.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"}),c;if(Date.now()>=o)throw ce();i=this.clampRetryAfterMs(Math.max(i*2,Tt))}}catch(a){throw a instanceof d.FloPayError&&a.code==="checkout_processing_timeout"&&this.reportDirectFailure(a,"RECOVERY_FAILED","recovery","session_read","saved"),a}}normalizeRawSession(e){let t=e.gateways??{},r=[],s={session:this.toCheckoutSession(e)},o=t.stripe;if(o?.publishableKey){r.push("stripe");let a=[e.stripeClientSecret,o.stripeClientSecret].find(c=>typeof c=="string"&&c.length>0);s.stripe={clientSecret:a??"",publishableKey:o.publishableKey??void 0,paypalPublishableKey:o.paypalPublishableKey??void 0,environment:o.environment,enabledPaymentMethods:Array.isArray(o.enabledPaymentMethods)?o.enabledPaymentMethods.filter(c=>typeof c=="string"):void 0}}let i=t.paypal;return i?.publishableKey&&(r.push("paypal"),s.paypal={publishableKey:i.publishableKey,environment:i.environment}),{providers:r,mode:"tokenize",data:s,raw:{data:e}}}toCheckoutSession(e){let t=e.products??[],r=typeof e.totalAmount=="number"&&Number.isFinite(e.totalAmount),s=t.reduce((c,u)=>c+(u.overrideAmount??u.totalAmount??0),0),o=r?e.totalAmount:s,i=Math.round(o*100),l=e.currency??t[0]?.currency??"USD",a=t.some(c=>c.type==="subscription")?"subscription":"payment";return{id:e.uuid,clientSecret:e.nonce,mode:a,status:this.toCheckoutSessionStatus(e.status),amount:i,currency:l,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 d.FloPayError("Checkout session has expired.","api_error",{code:"checkout_session_expired"}):ce()}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:z(e,"sessionId")??r,retryAfterMs:this.clampRetryAfterMs(Pt(e,"retryAfterMs")??i??Re),statusUrl:z(e,"statusUrl"),sessionUrl:z(e,"sessionUrl")}}clampRetryAfterMs(e){return Math.max(0,Math.min(e,wt))}autoCacheDisplayData(e,t){if(!e)return;let r=t.products??(0,d.foldIntoProducts)(t.items,t.subscriptions);if(r.length===0&&!t.currency)return;let s=t.products!==void 0,o=(0,d.resolveSessionCurrency)(t.currency,s?void 0:t.items,s?void 0:t.subscriptions,r);U(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=ae(e.uuid),r=new Map,s=i=>i?`code:${i}`:void 0;for(let i of t?.products??[]){let l=s(i.code);l&&r.set(l,i)}let o=(e.products??[]).map(i=>{let l=s(i.code),a=l?r.get(l):void 0;return{...i,name:i.name??a?.name??null,totalAmount:i.totalAmount??a?.totalAmount,overrideAmount:i.overrideAmount??a?.overrideAmount,currency:i.currency??a?.currency}});return{...e,currency:e.currency??t?.currency,products:o}}};L.activeVaultCaptureRequests=new Map;var O=L;function Fe(n,e){let t=O;return new t(n,e)}function Oe(n){return{payment:"payment",address:"address"}[n]}function X(n){switch(n){case"night":return"night";case"flat":return"flat";default:return"stripe"}}function Le(n){return{...n,theme:X(n.theme)}}function _e(n){return n?JSON.stringify(n.map(e=>e.trim().toLowerCase())):null}function qe(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 Rt(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(0,Ue.loadStripe)(e.publishableKey,{locale:e.locale??"auto"});if(!t)throw new y.FloPayError("Failed to initialize Stripe. Check your publishable key.","authentication_error");this.stripe=t}getElements(e){if(!this.stripe)throw new y.FloPayError("StripeAdapter not initialized. Call initialize() first.","api_error");let t=e?.appearance?{theme:X(e.appearance.theme),variables:e.appearance.variables,rules:e.appearance.rules}:void 0,r=t?JSON.stringify(t):null,s=_e(e?.paymentMethodTypes),o=e?.clientSecret??null;if(this.elements&&s&&(s!==this.appliedPaymentMethodTypesKey||o!==this.appliedClientSecret)&&(this.elements=null,this.appliedAppearanceKey=null,this.appliedPaymentMethodTypesKey=null,this.appliedClientSecret=null,this.verifiedClientSecret=null,this.verifiedPaymentMethodTypesKey=null),this.elements)r!==this.appliedAppearanceKey&&(this.elements.update({appearance:t??{}}),this.appliedAppearanceKey=r);else{let i,l=e?.amount??0,a=(e?.currency??"usd").toLowerCase(),c=e?.paymentMethodCreation??"manual";e?.clientSecret?i={clientSecret:e.clientSecret}:l>0?(i={mode:"payment",amount:l,currency:a,paymentMethodCreation:c},e?.setupFutureUsage&&(i.setupFutureUsage=e.setupFutureUsage)):i={mode:"setup",currency:a,paymentMethodCreation:c},!e?.clientSecret&&e?.paymentMethodTypes&&(i.paymentMethodTypes=e.paymentMethodTypes),t&&(i.appearance=t),this.elements=this.stripe.elements(i),this.appliedAppearanceKey=r,this.appliedPaymentMethodTypesKey=s,this.appliedClientSecret=o,this.verifiedClientSecret=null,this.verifiedPaymentMethodTypesKey=null}return this.elements}async assertClientSecretPaymentMethods(e,t){if(!this.stripe)throw new y.FloPayError("StripeAdapter not initialized. Call initialize() first.","api_error");let r,s=!1;if((0,y.isSetupIntentClientSecret)(e)){let{setupIntent:a,error:c}=await this.stripe.retrieveSetupIntent(e);r=a,s=!!c}else{let{paymentIntent:a,error:c}=await this.stripe.retrievePaymentIntent(e);r=a,s=!!c}let o=r?.payment_method_types;if(s||!Array.isArray(o))throw new y.FloPayError("Unable to verify the payment methods configured for this client secret.","api_error",{param:"clientSecret"});let i=new Set(t.map(a=>a.toLowerCase()));if(o.some(a=>typeof a!="string"||!i.has(a.trim().toLowerCase()))||o.length===0)throw new y.FloPayError("The client-secret intent must enable only declared non-card payment methods.","validation_error",{param:"clientSecret"})}async createElement(e,t){let r=t;if(e==="payment"){let a=t.paymentMethodTypes?.map(c=>c.trim()).filter(c=>c&&c.toLowerCase()!=="card");if(!a?.length)throw new y.FloPayError("At least one supported non-card payment method is required.","validation_error",{param:"paymentMethodTypes"});if(r={...t,paymentMethodTypes:a},r.clientSecret){let c=_e(a);this.elements&&this.appliedClientSecret===r.clientSecret&&this.appliedPaymentMethodTypesKey===c&&this.verifiedClientSecret===r.clientSecret&&this.verifiedPaymentMethodTypesKey===c||await this.assertClientSecretPaymentMethods(r.clientSecret,a)}}let s=this.getElements(r);e==="payment"&&r.clientSecret&&(this.verifiedClientSecret=r.clientSecret,this.verifiedPaymentMethodTypesKey=_e(r.paymentMethodTypes));let o=Oe(e),i={};r.layout&&(i.layout=r.layout),r.defaultValues&&(i.defaultValues=r.defaultValues),r.readOnly&&(i.readOnly=r.readOnly),r.mode&&(i.mode=r.mode);let l=s.create(o,i);return qe(l)}getElement(e){if(!this.elements)return null;let t=Oe(e),r=this.elements.getElement(t);return r?qe(r):null}async submitElements(){if(!this.stripe||!this.elements)return{error:new y.FloPayError("Stripe not initialized","api_error")};let{error:e}=await this.elements.submit();return e?{error:new y.FloPayError(e.message??"Validation failed","validation_error")}:{}}async confirmPayment(e){if(!this.stripe||!this.elements)throw new y.FloPayError("StripeAdapter not initialized or no elements created.","api_error");let t=e.billingDetails,r=t?Rt(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.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 y.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 y.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 y.FloPayError(o.message??"PayPal payment failed","validation_error",{code:o.code})}}let r;try{let o=await new O(t).createSessionIntent(e.sessionId,e.nonce??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"});if(o.provider!=="stripe")throw new y.FloPayError("Invalid provider returned for PayPal intent","api_error");r=o.clientSecret}catch(o){return{status:"failed",error:o instanceof y.FloPayError?o:new y.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 O(t).reportSessionIntentDecline(e.sessionId,e.nonce,{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:s.code??"provider_declined"})}catch{}return{status:"failed",error:new y.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 y.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 y.FloPayError(i.message??"Failed to retrieve PayPal payment","api_error")};if(o&&(o.status==="requires_capture"||o.status==="succeeded")){let l=typeof o.payment_method=="string"?o.payment_method:o.payment_method?.id,a=new URL(window.location.href);return a.searchParams.delete("payment_intent"),a.searchParams.delete("payment_intent_client_secret"),a.searchParams.delete("redirect_status"),window.history.replaceState({},"",a.toString()),{status:o.status,paymentIntentId:o.id,paymentMethodId:l}}return{status:"failed",error:new y.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:X(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 Ne=require("@flopay/shared"),$=class{constructor(e,t){this.elementMap=new Map;this.provider=e,this.baseOptions=t??{}}async create(e,t){let r={...this.baseOptions,...t};if(e==="payment"){let l=r.paymentMethodTypes?.map(a=>a.trim()).filter(a=>a&&a.toLowerCase()!=="card");if(!l?.length)throw new Ne.FloPayError("At least one supported non-card payment method is required.","validation_error",{param:"paymentMethodTypes"});r.paymentMethodTypes=l}let s=this.provider.getElement(e);if(s)return this.elementMap.set(e,s),s;let o=this.elementMap.get(e);o&&o.destroy();let i=await this.provider.createElement(e,r);return this.elementMap.set(e,i),i}getElement(e){return this.elementMap.get(e)??null}async submit(){return{}}destroy(){for(let e of this.elementMap.values())e.destroy();this.elementMap.clear()}};var T=require("@flopay/shared");var we="flopay-vault",Ve={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 Z(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 ue(n,e){return(0,T.buildTelemetryLogEvent)({eventId:"11111111-1111-4111-8111-111111111111",name:n,stage:e,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}function Be(n){return n?{errorCode:"VAULT_SUBMIT_FAILED",stage:"vault_submit",failureCategory:"provider_runtime"}:{errorCode:"VAULT_LOAD_FAILED",stage:"vault_mount",failureCategory:"provider_runtime"}}function At(n,e){if(n==="complete"||n==="decline")return(0,T.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=Be(e);return(0,T.buildTelemetryErrorEvent)({eventId:"33333333-3333-4333-8333-333333333333",...s,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}let[t,r]=Ve[n];return ue(t,r)}function It(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===we&&(e.type==="ready"||e.type==="submitting"||e.type==="blocked"||e.type==="complete"||e.type==="decline"||e.type==="error"||e.type==="action_required")}function Dt(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===we&&e.type==="validation"&&Array.isArray(e.messages)}function xt(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===we&&e.type==="resize"&&typeof e.height=="number"&&Number.isFinite(e.height)}var V=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 w({billingApiUrl:(0,T.resolveBillingApiUrl)(),sdkVersion:T.SDK_VERSION}):void 0)}async mount(e,t){if(this.ownsTelemetryReporter&&!this.telemetryReporter&&(this.telemetryReporter=new w({billingApiUrl:(0,T.resolveBillingApiUrl)(),sdkVersion:T.SDK_VERSION})),this.mountStartedAt=this.telemetryReporter?.now?.()??E(),this.vaultReadyReported=!1,this.submissionStarted=!1,this.submissionStartedAt=null,typeof window>"u"||typeof document>"u")throw this.reportVaultLoadFailure(),new T.FloPayError("The vault card form is only available in the browser.","api_error",{code:"card_capture_no_window"});if(!t?.html||!t.html.trim())throw this.reportVaultLoadFailure(),new T.FloPayError("No vault capture widget HTML was provided to mount the secure card form.","api_error",{code:"card_capture_no_widget_html"});this.container=e,this.messageToken=t.messageToken??null,this.expectedOrigin=t.expectedOrigin??this.config.expectedOrigin??null,this.theme=t.theme??null;try{this.attachMessageListener(),this.injectWidget(e,t.html)}catch(r){throw this.reportVaultLoadFailure(),r}this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),Z(ue("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(xt(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;this.applyHeight(r.height);return}if(Dt(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;let l=r.messages.filter(a=>typeof a=="string"&&a.trim()).join(" ");this.emit("validation",{sessionId:this.config.sessionId,message:l||void 0});return}if(!It(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?.()??E()),Z(At(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=Be(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]=Ve[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 l=i.data;if(!l||typeof l!="object")return;let a=l;a.source==="flopay-vault-3ds-return"&&(Z(ue("vault.three_ds.returned","three_ds_return")),this.telemetryReporter?.log({name:"vault.three_ds.returned",stage:"three_ds_return",provider:"pcivault",paymentMethodCategory:"card"}),this.hideActionRequiredOverlay(),this.postActionCompleted(a.status))};window.addEventListener("message",o),this.threeDsReturnHandler=o,document.body.appendChild(t),this.actionOverlay=t,Z(ue("vault.three_ds.handoff","three_ds_handoff"))}postActionCompleted(e){if(!this.container)return;let r=this.container.querySelector("iframe")?.contentWindow;if(r)try{r.postMessage({source:"flopay-vault-host",type:"action_completed",status:typeof e=="string"?e:"unknown"},"*")}catch{}}abandonActionRequiredOverlay(){if(!this.actionOverlay)return;let e=(0,T.buildTelemetryTerminalEvent)({eventId:"77777777-7777-4777-8777-777777777777",outcome:"customer_abandoned",stage:"three_ds_handoff",sequence:0,provider:"pcivault",paymentMethodCategory:"card"});Z(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 je(n,e){let t=V;return new t(n,{reporter:e})}var Ke=Symbol.for("@flopay/js.telemetry.bridge.v1");function ze(n,e,t){let r=()=>e?.now()??t();Object.defineProperty(n,Ke,{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 He(n){return n[Ke]}function G(n){if(!n)return!1;let e=n.code?.toLowerCase()??"";return!!n.declineCode||e.includes("declin")}function Ft(n){return n==="stripe"||n==="paypal"||n==="pcivault"?n:"other"}var ee=class{constructor(e,t,r){this.currentElements=null;this.provider=e,this.config=t,this.telemetryReporter=r??new w({billingApiUrl:(0,g.resolveBillingApiUrl)(t.billingApiUrl),sdkVersion:g.SDK_VERSION,enabled:t.telemetry!==!1}),ze(this,this.telemetryReporter,E)}now(){return this.telemetryReporter?.now?.()??E()}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?je({sessionId:e?.sessionId},this.telemetryReporter):new V({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"&&(G(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&&G(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"}):G(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&&G(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=Ft(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}):G(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&&G(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=Fe(r,{now:()=>this.telemetryReporter?.now()??E(),onFirstByte:l=>{o=l},onRetry:(l,a)=>{this.telemetryReporter?.log({name:"operation.retry",stage:l==="session_read"?"session_read":"processing",requestCategory:l,attempt:a})}});try{let l=await i.getUnifiedCheckoutSession(e);return o!==void 0&&(this.telemetryReporter?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:"2xx"}),this.telemetryReporter?.performance({stage:"session_first_byte",durationMs:o,durationMode:"machine",requestCategory:"session_read",statusClass:"2xx"})),this.telemetryReporter?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:"2xx"}),this.telemetryReporter?.log({name:"checkout.data.ready",stage:"checkout_data_ready"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-s,durationMode:"machine",requestCategory:"session_read",statusClass:"2xx"}),l}catch(l){let a=(0,g.classifyTelemetryFailure)(l,l instanceof g.FloPayError&&l.code==="checkout_processing_timeout"?"REQUEST_TIMEOUT":"NETWORK_REQUEST_FAILED");throw this.telemetryReporter?.error({...a,stage:"session_read",provider:"flo",paymentMethodCategory:"unknown"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-s,durationMode:"machine",requestCategory:"session_read",statusClass:a.statusClass}),l}}getRawProvider(){return this.provider.getRawProvider()}destroy(){this.telemetryReporter?.log({name:"checkout.unmount",stage:"unmount"}),this.telemetryReporter?.destroy(),this.currentElements?.destroy(),this.currentElements=null,this.provider.destroy()}};function $e(n,e,t){let r=ee;return new r(n,e,t)}var Ge=new Map;function be(n){return Array.isArray(n)?n.map(be):n&&typeof n=="object"?Object.fromEntries(Object.entries(n).filter(([,e])=>e!==void 0).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,be(t)])):n}function Ot(n,e){return JSON.stringify([n,(0,A.resolveBillingApiUrl)(e?.billingApiUrl),e?.telemetry!==!1,e?.locale??"auto",e?.apiVersion??null,be(e?.appearance??null)])}var pe=new Map;async function Ye(n,e){if(!n){let l=new w({billingApiUrl:(0,A.resolveBillingApiUrl)(e?.billingApiUrl),sdkVersion:A.SDK_VERSION,enabled:e?.telemetry!==!1});throw l.error({errorCode:"CONFIGURATION_INVALID",stage:"sdk_initialize",paymentMethodCategory:"unknown"}),l.flush().catch(()=>{}).finally(()=>l.destroy()),new A.FloPayError("A publishable key is required to initialize FloPay.","validation_error",{param:"publishableKey"})}let t=Ot(n,e),r=Ge.get(t);if(r)return e?.telemetry!==!1&&He(r)?.log({name:"sdk.cache.hit",stage:"sdk_initialize"}),r;let s=pe.get(t);if(s)return s;let o={...e,publishableKey:n},i=(async()=>{let l=new w({billingApiUrl:(0,A.resolveBillingApiUrl)(o.billingApiUrl),sdkVersion:A.SDK_VERSION,enabled:o.telemetry!==!1}),a=l.now();l.log({name:"sdk.initialize.started",stage:"sdk_initialize"}),l.log({name:"sdk.cache.miss",stage:"sdk_initialize"}),l.log({name:"provider.load.started",stage:"provider_load",provider:"stripe"});let c=new H,u=l.now();try{await c.initialize(o)}catch(_){throw l.error({errorCode:"SDK_INITIALIZATION_FAILED",failureCategory:"provider_runtime",stage:"sdk_initialize",provider:"stripe",paymentMethodCategory:"unknown"}),l.destroy(),_}let f=l.now();l.log({name:"provider.ready",stage:"provider_ready",provider:"stripe"}),l.log({name:"provider.availability.checked",stage:"provider_ready",provider:"stripe"}),l.log({name:"sdk.initialize.ready",stage:"sdk_initialize"}),l.performance({stage:"sdk_initialize",durationMs:f-a,durationMode:"machine",provider:"stripe"}),l.performance({stage:"provider_ready",durationMs:f-u,durationMode:"machine",provider:"stripe"});let b=$e(c,o,l);return Ge.set(t,b),b})();pe.set(t,i);try{return await i}finally{pe.get(t)===i&&pe.delete(t)}}var m=require("@flopay/shared");var Se=5,We=new WeakSet;function qt(n){(typeof n=="object"&&n!==null||typeof n=="function")&&We.add(n)}function Ut(n){return(typeof n=="object"&&n!==null||typeof n=="function")&&We.has(n)}function Lt(n,e){let t=e?.error,r=q(e?.code)??q(t?.code)??`http_${n}`,s=q(e?.message)??q(t?.message)??Nt(r,n);return new m.FloPayError(s,"api_error",{code:r,statusCode:n})}function Nt(n,e){switch(n){case"CouponLimitExceeded":return`Too many coupon codes \u2014 a checkout session accepts at most ${Se}.`;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 Je(n,e,t){let{billingApiUrl:r,checkoutBaseUrl:s,items:o=[],subscriptions:i=[],products:l,account:a,successUrl:c,cancelUrl:u,checkoutMode:f="confirm",couponCodes:b=[],tagsData:_,redirectParams:C={},setCookie:R=!0,clientId:k,currency:h,utmMetadata:S,idempotencyKey:p}=n,M=(0,m.resolveIdempotencyKey)(p);if(b.length>Se)throw new m.FloPayError(`Too many coupon codes \u2014 a checkout session accepts at most ${Se}.`,"validation_error",{code:"CouponLimitExceeded",param:"couponCodes"});let I=l??(0,m.foldIntoProducts)(o,i),D=(0,m.resolveSessionCurrency)(h,o,i,I);if(!D)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 W={clientId:k,checkoutVersion:m.SDK_VERSION,successUrl:c,cancelUrl:u,currency:D,checkoutMode:f,products:I.map(F=>(0,m.buildProductPayload)(F,D)),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:b};_&&(W.tagsData=_),S?.length&&(W.utmMetadata=S);let ye=`${r.replace(/\/+$/,"")}/v1/checkouts/sessions`,B={"Content-Type":"application/json"};M&&(B[m.IDEMPOTENCY_KEY_HEADER]=M);let x,te,rt={method:"POST",headers:B,body:JSON.stringify(W),signal:e},re;try{re=await fetch(ye,rt)}catch(F){throw qt(F),F}try{t?.(re.status)}catch{}x=re.status;try{te=await re.json()}catch{}if(x>=400)throw Lt(x,te);if(x===201){let F=te?.data?.uuid,he=te?.data?.nonce;if(!F)throw new Error("Checkout session created but no UUID was returned by the billing API");if(!he)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"});(I.length||D)&&U(F,{currency:D,products:I.map(v=>({code:v.code??v.providerItemId??v.providerPlanId,type:v.type,name:v.name??v.itemName??v.providerItemName??v.subscriptionName??v.providerPlanName??null,totalAmount:v.totalAmount,overrideAmount:v.overrideAmount,currency:v.currency??D}))});let ne=new URL(`${s.replace(/\/+$/,"")}/secure`);ne.searchParams.set("id",F);for(let[v,oe]of Object.entries(C))ne.searchParams.set(v,oe);if(R&&typeof window<"u"&&typeof document<"u"){let v=JSON.stringify({origin_url:u}),oe=window.location.hostname.split(".").slice(-2).join(".");document.cookie=`checkout_data=${encodeURIComponent(v)}; domain=.${oe}; path=/; max-age=3600; SameSite=Lax; Secure;`,document.cookie=`flopay_checkout_token=${encodeURIComponent(he)}; domain=.${oe}; path=/; max-age=3600; SameSite=Lax; Secure;`}return typeof window<"u"&&(window.location.href=ne.toString()),{status:201,redirectUrl:ne.toString(),nonce:he}}return x===204?(typeof window<"u"&&(window.location.href=c),{status:204}):{status:x}}async function Qe(n){let e=Ze(n),t=Xe(e),r=J(n.timeoutMs);try{let s=await Je(n,r.signal,t);return et(e,s),s}catch(s){throw me(e,s),s}finally{r.clear(),Y(e.reporter)}}function Xe(n){let e=!1;return t=>{if(e)return;e=!0;let r=(0,m.telemetryStatusClass)(t);n.reporter.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:r,attempt:n.attempt}),n.reporter.performance({stage:"session_first_byte",durationMs:n.reporter.now()-n.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:r,attempt:n.attempt})}}function Ze(n){let e=new w({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,attempt:0}}function et(n,e){let t=(0,m.telemetryStatusClass)(e.status);n.reporter.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:t}),n.reporter.performance({stage:"session_create",durationMs:n.reporter.now()-n.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:t,attempt:n.attempt})}function me(n,e){let{reporter:t}=n,r=(0,m.classifyTelemetryFailure)(e,"CHECKOUT_SESSION_CREATE_FAILED");if(t.performance({stage:"session_create",durationMs:t.now()-n.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:r.statusClass,attempt:n.attempt}),e instanceof m.FloPayError&&e.type==="validation_error"){t.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"});return}if(r.statusClass==="4xx"){t.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create",statusClass:"4xx"});return}t.error({...r,stage:"session_create",requestCategory:"session_create"})}function Y(n){n.flush().catch(()=>{}).finally(()=>n.destroy())}async function tt(n){let{maxRetries:e=2,...t}=n,r=Ze(n),s=Xe(r);if(!Number.isFinite(e)||!Number.isInteger(e)||e<0||e>=3)throw r.reporter.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),Y(r.reporter),new Error(`Number of retries must be an integer between 0 and ${2}`);let o={...t,idempotencyKey:(0,m.resolveIdempotencyKey)(t.idempotencyKey)},i=J(t.timeoutMs),l;for(let a=0;a<=e;a++){r.attempt=a;try{let c=await Je(o,i.signal,s);return et(r,c),i.clear(),Y(r.reporter),c}catch(c){l=c;let u=c instanceof Error&&c.name==="AbortError",f=Ut(c),b=c instanceof m.FloPayError&&c.code===m.IDEMPOTENCY_IN_PROGRESS_CODE;if((u||f||b)&&!i.signal.aborted&&a<e){r.reporter.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:a+1});try{await Q(a,i.signal)}catch(_){throw me(r,_),i.clear(),Y(r.reporter),_}continue}throw me(r,c),i.clear(),Y(r.reporter),c}}throw me(r,l),i.clear(),Y(r.reporter),l??new Error("Unknown error during checkout session creation")}0&&(module.exports={FloPay,FloPayElements,PaymentAPI,PciVaultCardCapture,SESSION_CREATE_TELEMETRY,StripeAdapter,cacheSessionDisplayData,clearSessionDisplayData,createCheckoutSession,createCheckoutSessionWithRetries,getSessionDisplayData,loadFloPay,toStripeAppearance,toStripeAppearanceTheme});
|
package/dist/index.d.cts
CHANGED
|
@@ -330,6 +330,7 @@ interface PaymentAPIOptions {
|
|
|
330
330
|
/** Flo-owned privacy-safe telemetry is enabled by default; set false to opt out. */
|
|
331
331
|
telemetry?: boolean;
|
|
332
332
|
}
|
|
333
|
+
declare const SESSION_CREATE_TELEMETRY: unique symbol;
|
|
333
334
|
/**
|
|
334
335
|
* Client-side payment API service.
|
|
335
336
|
*
|
|
@@ -709,9 +710,11 @@ declare class PciVaultCardCapture implements CardCaptureAdapter {
|
|
|
709
710
|
|
|
710
711
|
declare function createCheckoutSession(options: CreateSessionParams): Promise<CheckoutSessionResult>;
|
|
711
712
|
/**
|
|
712
|
-
* Creates a checkout session with automatic retry on
|
|
713
|
+
* Creates a checkout session with automatic retry on transient transport,
|
|
714
|
+
* timeout/abort, and idempotency-in-progress errors.
|
|
713
715
|
*
|
|
714
|
-
* Uses exponential backoff
|
|
716
|
+
* Uses jittered exponential backoff under the same total deadline as a single
|
|
717
|
+
* create (12 seconds by default, configurable with `timeoutMs`).
|
|
715
718
|
*
|
|
716
719
|
* The idempotency key (supplied or generated) is resolved **once**, before the
|
|
717
720
|
* retry loop, and reused for every attempt — so a timeout, a lost response, or
|
|
@@ -724,4 +727,4 @@ declare function createCheckoutSessionWithRetries(options: CreateSessionParams &
|
|
|
724
727
|
maxRetries?: number;
|
|
725
728
|
}): Promise<CheckoutSessionResult>;
|
|
726
729
|
|
|
727
|
-
export { FloPay, FloPayElements, PaymentAPI, PciVaultCardCapture, type PciVaultCardCaptureConfig, type SessionDisplayCacheData, type SessionDisplayProduct, StripeAdapter, type StripeSafeAppearance, cacheSessionDisplayData, clearSessionDisplayData, createCheckoutSession, createCheckoutSessionWithRetries, getSessionDisplayData, loadFloPay, toStripeAppearance, toStripeAppearanceTheme };
|
|
730
|
+
export { FloPay, FloPayElements, PaymentAPI, PciVaultCardCapture, type PciVaultCardCaptureConfig, SESSION_CREATE_TELEMETRY, type SessionDisplayCacheData, type SessionDisplayProduct, StripeAdapter, type StripeSafeAppearance, cacheSessionDisplayData, clearSessionDisplayData, createCheckoutSession, createCheckoutSessionWithRetries, getSessionDisplayData, loadFloPay, toStripeAppearance, toStripeAppearanceTheme };
|
package/dist/index.d.ts
CHANGED
|
@@ -330,6 +330,7 @@ interface PaymentAPIOptions {
|
|
|
330
330
|
/** Flo-owned privacy-safe telemetry is enabled by default; set false to opt out. */
|
|
331
331
|
telemetry?: boolean;
|
|
332
332
|
}
|
|
333
|
+
declare const SESSION_CREATE_TELEMETRY: unique symbol;
|
|
333
334
|
/**
|
|
334
335
|
* Client-side payment API service.
|
|
335
336
|
*
|
|
@@ -709,9 +710,11 @@ declare class PciVaultCardCapture implements CardCaptureAdapter {
|
|
|
709
710
|
|
|
710
711
|
declare function createCheckoutSession(options: CreateSessionParams): Promise<CheckoutSessionResult>;
|
|
711
712
|
/**
|
|
712
|
-
* Creates a checkout session with automatic retry on
|
|
713
|
+
* Creates a checkout session with automatic retry on transient transport,
|
|
714
|
+
* timeout/abort, and idempotency-in-progress errors.
|
|
713
715
|
*
|
|
714
|
-
* Uses exponential backoff
|
|
716
|
+
* Uses jittered exponential backoff under the same total deadline as a single
|
|
717
|
+
* create (12 seconds by default, configurable with `timeoutMs`).
|
|
715
718
|
*
|
|
716
719
|
* The idempotency key (supplied or generated) is resolved **once**, before the
|
|
717
720
|
* retry loop, and reused for every attempt — so a timeout, a lost response, or
|
|
@@ -724,4 +727,4 @@ declare function createCheckoutSessionWithRetries(options: CreateSessionParams &
|
|
|
724
727
|
maxRetries?: number;
|
|
725
728
|
}): Promise<CheckoutSessionResult>;
|
|
726
729
|
|
|
727
|
-
export { FloPay, FloPayElements, PaymentAPI, PciVaultCardCapture, type PciVaultCardCaptureConfig, type SessionDisplayCacheData, type SessionDisplayProduct, StripeAdapter, type StripeSafeAppearance, cacheSessionDisplayData, clearSessionDisplayData, createCheckoutSession, createCheckoutSessionWithRetries, getSessionDisplayData, loadFloPay, toStripeAppearance, toStripeAppearanceTheme };
|
|
730
|
+
export { FloPay, FloPayElements, PaymentAPI, PciVaultCardCapture, type PciVaultCardCaptureConfig, SESSION_CREATE_TELEMETRY, type SessionDisplayCacheData, type SessionDisplayProduct, StripeAdapter, type StripeSafeAppearance, cacheSessionDisplayData, clearSessionDisplayData, createCheckoutSession, createCheckoutSessionWithRetries, getSessionDisplayData, loadFloPay, toStripeAppearance, toStripeAppearanceTheme };
|
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 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};
|
|
1
|
+
import{FloPayError as tr,resolveBillingApiUrl as we,SDK_VERSION as rt}from"@flopay/shared";import{loadStripe as jt}from"@stripe/stripe-js";import{FloPayError as h,isSetupIntentClientSecret as Kt}from"@flopay/shared";import{FloPayError as m,SDK_VERSION as oe,FLO_SDK_VERSION_HEADER as Ae,IDEMPOTENCY_KEY_HEADER as Ie,IDEMPOTENCY_IN_PROGRESS_CODE as Rt,buildProductPayload as At,classifyTelemetryFailure as Y,foldIntoProducts as De,isUuidV4 as xe,randomUuidV4 as It,resolveIdempotencyKey as Dt,resolveSessionCurrency as Fe,telemetryStatusClass as L}from"@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 mt="flopay_session_display:";var re=new Map;function ne(n){return`${mt}${n}`}function ye(){if(typeof window>"u")return null;try{return window.sessionStorage}catch{return null}}function q(n,e,t){if(!n)return;let r=t?.ttlMs??36e5,s={data:e,expiresAt:Date.now()+r},o=ye();if(o)try{o.setItem(ne(n),JSON.stringify(s));return}catch{}re.set(n,s)}function he(n){if(!n)return null;let e=ye();if(e)try{let r=e.getItem(ne(n));if(r){let s=JSON.parse(r);if(s&&typeof s.expiresAt=="number"&&s.expiresAt>Date.now())return s.data;e.removeItem(ne(n))}}catch{}let t=re.get(n);if(t){if(t.expiresAt>Date.now())return t.data;re.delete(n)}return null}function ge(n){if(!n)return;re.delete(n);let e=ye();if(e)try{e.removeItem(ne(n))}catch{}}import{buildTelemetryErrorEvent as Me,buildTelemetryLogEvent as yt,buildTelemetryPerformanceEvent as ht,buildTelemetryTerminalEvent as gt,serializeTelemetryBatch as ft,TELEMETRY_MAX_BATCH_BYTES as Ct}from"@flopay/shared";var vt="/v1/sdk-telemetry/events",fe=16,Tt=64,_t=1500,Ee=1e3,wt=64,bt="00000000-0000-4000-8000-000000000000",St={technical_error:8,lifecycle:32,expected_outcome:32,performance:24};function U(){try{return globalThis.crypto.randomUUID()}catch{let n=new Uint8Array(16);try{globalThis.crypto.getRandomValues(n)}catch{for(let t=0;t<n.length;t+=1)n[t]=Math.floor(Math.random()*256)}n[6]=n[6]&15|64,n[8]=n[8]&63|128;let e=[...n].map(t=>t.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}}function Pt(n){try{return new TextEncoder().encode(n).byteLength}catch{return n.length}}function Mt(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 b(){return globalThis.performance?.now()??0}var v=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(/\/+$/,"")}${vt}`,this.sdkPackage=e.sdkPackage??"@flopay/js",this.sdkVersion=e.sdkVersion,this.correlationId=U(),this.merchantEnabled=e.enabled!==!1,this.clock=e.clock??b,this.browserTransportAvailable=typeof window<"u"&&typeof document<"u",this.browserTransportAvailable&&(window.addEventListener("pagehide",this.pageExitHandler),document.addEventListener("visibilitychange",this.visibilityHandler))}log(e){this.canCollect()&&this.enqueue(yt({...this.checkoutContext,...e,eventId:U(),sequence:this.sequence++}))}error(e){if(!this.canCollect())return;let t=Me({...this.checkoutContext,...e,eventId:bt,sequence:0}),r=Mt(t),s=this.now();this.pruneReportedFailures(s);let o=this.reportedFailures.get(r);if(o!==void 0&&s>=o&&s-o<Ee){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:U(),sequence:this.sequence++}))}performance(e){this.canCollect()&&this.enqueue(ht({...this.checkoutContext,...e,eventId:U(),sequence:this.sequence++}))}terminal(e){if(this.canCollect()&&(this.enqueue(gt({...this.checkoutContext,...e,eventId:U(),sequence:this.sequence++})),e.outcome!=="action_required"&&this.checkoutStartedAt!==null)){let t=this.checkoutStartedAt;this.checkoutStartedAt=null,this.performance({stage:"total_journey",durationMs:Math.max(0,this.now()-t),durationMode:"total",provider:e.provider,paymentMethodCategory:e.paymentMethodCategory})}}now(){try{return this.clock()}catch{return b()}}pruneReportedFailures(e){for(let[t,r]of this.reportedFailures)(e<r||e-r>=Ee)&&this.reportedFailures.delete(t)}rememberReportedFailure(e,t){for(;this.reportedFailures.size>=wt;){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>=Tt||this.eventCounts[e.class]>=St[e.class])){if(this.eventCounts[e.class]+=1,this.queue.push(e),this.queue.length>=fe){this.flush();return}this.scheduleFlush()}}canCollect(){return this.browserTransportAvailable&&this.merchantEnabled&&!this.ingestionDisabled&&!this.destroyed}async flush(){if(this.flushInFlight)return this.flushInFlight;if(!this.browserTransportAvailable||this.destroyed||this.ingestionDisabled||this.queue.length===0)return;this.clearFlushTimer();let e=this.queue.splice(0,fe);return this.flushInFlight=this.sendBatch(e).finally(()=>{this.flushInFlight=null,this.queue.length>0&&this.scheduleFlush()}),this.flushInFlight}destroy(){this.destroyed||(this.drainQueue(),this.destroyed=!0,this.clearFlushTimer(),this.browserTransportAvailable&&(window.removeEventListener("pagehide",this.pageExitHandler),document.removeEventListener("visibilitychange",this.visibilityHandler)),this.queue.splice(0),this.reportedFailures.clear())}disable(){this.merchantEnabled=!1,this.queue.splice(0),this.reportedFailures.clear(),this.clearFlushTimer()}drainQueue(){if(!(!this.browserTransportAvailable||this.destroyed||this.ingestionDisabled||this.queue.length===0))for(this.clearFlushTimer();this.queue.length>0;){let e=this.queue.splice(0,fe);this.sendBatch(e)}}async sendBatch(e){if(!this.browserTransportAvailable||this.ingestionDisabled)return;let t=ft(e,{correlationId:this.correlationId,sdkPackage:this.sdkPackage,sdkVersion:this.sdkVersion,batchId:U()});if(Pt(t)>Ct)return;let r=typeof AbortController>"u"?null:new AbortController,s=null;try{let o=fetch(this.endpoint,{method:"POST",headers:{"content-type":"text/plain;charset=UTF-8"},body:t,credentials:"omit",keepalive:!0,referrerPolicy:"no-referrer",signal:r?.signal}).then(async a=>a.status!==202?null:(await a.json().catch(()=>null))?.status==="disabled"?"disabled":null).catch(()=>null),i=new Promise(a=>{s=setTimeout(()=>{r?.abort(),a(null)},_t)});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)}},ke=Symbol.for("@flopay/js.telemetry.reporter-factory.v1"),Re=globalThis;Re[ke]===void 0&&Object.defineProperty(Re,ke,{configurable:!0,enumerable:!1,writable:!1,value:n=>new v(n)});function $(n=12e3){let e=Number.isFinite(n)&&n>=0?n:12e3,t=new AbortController,r=setTimeout(()=>t.abort(),e);return{signal:t.signal,clear:()=>clearTimeout(r)}}function Et(){return Object.assign(new Error("The operation was aborted."),{name:"AbortError"})}function G(n,e){let t=150*2**n,r=Math.round(t*(.75+Math.random()*.5));return new Promise((s,o)=>{let i,l=()=>e.removeEventListener("abort",a),a=()=>{i!==void 0&&clearTimeout(i),l(),o(Et())};if(e.aborted){a();return}i=setTimeout(()=>{l(),s()},r),e.addEventListener("abort",a,{once:!0})})}var Oe=1e3,xt=500,Ft=15e3,Ot=3e3,qt=1e4,Ut=1e4;function Le(n){return typeof n=="object"&&n!==null}function V(n,e){return I(n?.[e])}function qe(n,e){return Pe(n?.[e])}function Lt(n,e){let t=n?.[e];return typeof t=="number"&&Number.isFinite(t)?t:void 0}function Ne(n){return new Promise(e=>setTimeout(e,n))}function se(){return new m("Checkout is still processing. Please try again shortly.","api_error",{code:"checkout_processing_timeout"})}async function N(n,e){let t=await n.json().catch(()=>null),r=Le(t?.error)?t.error:null,s=qe(t,"message")??qe(r,"message")??e,o=V(t,"code")??V(t,"gatewayErrorCode")??V(r,"code")??`http_${n.status}`;return new m(s,"api_error",{code:o,statusCode:n.status})}async function Nt(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 Le(e)&&Array.isArray(e.fields)?"validation_rejected":"payment_declined"}function Ue(n){return n===400||n===422}var ie=2;async function Ce(n,e,t=ie,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 Ne(150*2**o)}}var Ve=Symbol.for("@flopay/js.session-create.telemetry.v1");function Vt(n){return n[Ve]}function Bt(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=Bt(t);this.telemetryHooks=r?t:void 0,this.directTelemetry=r||t.telemetry===!1?void 0:new v({billingApiUrl:this.baseUrl,sdkVersion:oe})}destroy(){this.directTelemetry?.destroy()}reportDirectFailure(e,t,r,s,o="unknown"){let i=Y(e,t);this.directTelemetry?.error({...i,stage:r,requestCategory:s,paymentMethodCategory:o})}reportAccountSnapshotFailure(e,t){let r=Y(e,"NETWORK_REQUEST_FAILED");if(t==="best_effort"&&r.errorCode==="REQUEST_TIMEOUT"){this.directTelemetry?.log({name:"operation.fallback",stage:"processing",requestCategory:"account_snapshot",statusClass:"timeout"});return}this.directTelemetry?.error({...r,stage:"processing",requestCategory:"account_snapshot",paymentMethodCategory:"unknown"})}telemetryTimestamp(){try{return this.telemetryHooks?.now?.()??this.directTelemetry?.now()??b()}catch{return b()}}beginDirectTelemetryCheckout(e){!this.directTelemetry||this.directTelemetryCheckoutId===e||(this.directTelemetryCheckoutId=e,this.directTelemetry.beginCheckout())}beginDirectTelemetryOperation(){this.directTelemetry&&(this.directTelemetryCheckoutId=void 0,this.directTelemetry.beginCheckout())}adoptDirectTelemetryCheckout(e){e&&(this.directTelemetryCheckoutId=e)}async getCheckoutSession(e,t){this.beginDirectTelemetryCheckout(e);let r=this.telemetryTimestamp();this.directTelemetry?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let s={[Ae]:oe};t&&(s["x-checkout-session-token"]=t);try{let o=await Ce(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}`,{headers:s},ie,c=>{this.telemetryHooks?.onRetry?.("session_read",c),this.directTelemetry?.log({name:"operation.retry",stage:"session_read",requestCategory:"session_read",attempt:c})}),i=Math.max(0,this.telemetryTimestamp()-r);try{this.telemetryHooks?.onFirstByte?.(i)}catch{}let l=`${Math.floor(o.status/100)}xx`;if(this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:l}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:i,durationMode:"machine",requestCategory:"session_read",statusClass:l}),!o.ok)throw await N(o,"Failed to get checkout session");let a=await o.json();return this.directTelemetry?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:l}),this.directTelemetry?.performance({stage:"session_complete",durationMs:Math.max(0,this.telemetryTimestamp()-r),durationMode:"machine",requestCategory:"session_read",statusClass:l}),{...a,data:this.mergeCachedDisplayData(a.data)}}catch(o){throw this.directTelemetry?.error({...Y(o,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"}),o}}cacheSessionDisplayData(e,t,r){q(e,t,r)}clearSessionDisplayData(e){ge(e)}async getVaultCapture(e,t){let r=`${this.baseUrl}\0${e}\0${t??""}`,s=D.activeVaultCaptureRequests.get(r);if(s)return s;let o=this.requestVaultCapture(e,t);D.activeVaultCaptureRequests.set(r,o);try{return await o}finally{D.activeVaultCaptureRequests.get(r)===o&&D.activeVaultCaptureRequests.delete(r)}}async requestVaultCapture(e,t){let r=new AbortController,s=setTimeout(()=>r.abort(),Ut);this.beginDirectTelemetryCheckout(e);let o=this.telemetryTimestamp();this.directTelemetry?.log({name:"vault.capture.requested",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card"});let i={"Content-Type":"application/json"};t&&(i["x-checkout-session-token"]=t);try{let l=await Ce(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/vault/capture`,{method:"POST",headers:i,signal:r.signal},ie,c=>{this.telemetryHooks?.onRetry?.("vault_capture",c),this.directTelemetry?.log({name:"operation.retry",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card",attempt:c})});if(!l.ok)throw await N(l,"Failed to load the secure card form");let a=await l.json();return this.directTelemetry?.performance({stage:"vault_request",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"2xx"}),this.toVaultBlock(a)}catch(l){let a=r.signal.aborted?new m("Timed out while loading the secure card form. Please try again.","api_error",{code:"vault_capture_timeout"}):l;throw this.reportDirectFailure(a,"VAULT_LOAD_FAILED","vault_request","vault_capture","card"),a}finally{clearTimeout(s)}}async getUnifiedCheckoutSession(e,t){let r=await this.getCheckoutSession(e,t),s=this.normalizeRawSession(r.data),o=r.vault;return o&&s.data.session&&(s.data.session.vault=this.toVaultBlock(o)),s}async processPayment(e,t,r){if(this.beginDirectTelemetryCheckout(t.sessionId),!t.nonce)throw this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"process_payment"}),new 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,l;try{l=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(t.sessionId)}/process`,{method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":o},body:JSON.stringify(i)})}catch(a){throw this.reportDirectFailure(a,"PAYMENT_PROCESSING_FAILED","processing","process_payment"),a}if(!l.ok&&l.status!==202){let a=await Nt(l);return a?this.directTelemetry?.terminal({outcome:a,stage:"processing",requestCategory:"process_payment",statusClass:"4xx"}):this.directTelemetry?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",requestCategory:"process_payment",statusClass:L(l.status),failureCategory:l.status>=500?"server_error":void 0}),l}try{let a=await this.resolveProcessResponse(l,t.sessionId,{...r,nonce:o});return this.directTelemetry?.log({name:"payment.processing.completed",stage:"processing",requestCategory:"process_payment",statusClass:L(a.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"process_payment",statusClass:L(a.status)}),a}catch(a){throw a instanceof m&&a.code==="checkout_processing_timeout"||this.reportDirectFailure(a,"PAYMENT_PROCESSING_FAILED","processing","process_payment"),a}}async patchAccountSnapshot(e,t,r,s){this.beginDirectTelemetryCheckout(e);let o=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.state_transition",stage:"processing",requestCategory:"account_snapshot"});let i=s?.timeoutMs??qt,l=new AbortController,a=()=>l.abort();s?.signal&&(s.signal.aborted?l.abort():s.signal.addEventListener("abort",a,{once:!0}));let c=setTimeout(()=>l.abort(),i);try{let d;try{d=await Ce(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/account`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":t},body:JSON.stringify(r),signal:l.signal},ie,y=>{this.telemetryHooks?.onRetry?.("account_snapshot",y),this.directTelemetry?.log({name:"operation.retry",stage:"processing",requestCategory:"account_snapshot",attempt:y})})}finally{clearTimeout(c),s?.signal?.removeEventListener("abort",a)}if(!d.ok)throw await N(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,l=typeof i=="string"&&i.trim().toLowerCase()==="card",a=typeof i=="string"&&i.length>0&&!l&&(typeof o.paymentMethodId=="string"||o.paymentMethodId===null),c=o.provider==="stripe"&&(o.paymentMethodCategory==="wallet"||o.paymentMethodCategory==="apm")&&(o.intentKind==="payment"||o.intentKind==="setup"),d=o.provider==="paypal"&&o.paymentMethodCategory==="wallet"&&o.paymentMethodType==="paypal"&&o.paymentMethodId===null&&o.intentKind==="payment";if(!a||!c&&!d)throw new m("Only wallet, APM, and PayPal session intents are supported.","validation_error",{code:"InvalidSessionIntentRequest"});let y=o.authorizationAttemptId;if(y!==void 0&&!xe(y))throw new m("authorizationAttemptId must be a v4 UUID identifying one buyer authorization attempt.","validation_error",{code:"InvalidAuthorizationAttemptId",param:"authorizationAttemptId"});let T=xe(y)?y:It();this.beginDirectTelemetryCheckout(e);let C=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.intent.started",stage:"processing",requestCategory:"intent_create"});let g={"Content-Type":"application/json","x-checkout-session-token":t,[Ie]:s?.idempotencyKey||T},M=!1;try{let S=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents`,{method:"POST",headers:g,body:JSON.stringify({...r,authorizationAttemptId:T}),signal:s?.signal});if(!S.ok){M=!0;let O=await N(S,"Failed to create checkout intent"),R=Y(O,"PAYMENT_PROCESSING_FAILED");throw Ue(O.statusCode)?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"intent_create",statusClass:"4xx"}):this.directTelemetry?.error({...R,stage:"processing",requestCategory:"intent_create"}),O}let _=(await S.json()).data;if(!_||typeof _!="object")throw new m("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});let u=_,w=u.paymentMethodType,E=(u.paymentMethodCategory==="wallet"||u.paymentMethodCategory==="apm")&&typeof w=="string"&&w.trim().toLowerCase()!=="card"&&(typeof u.paymentMethodId=="string"||u.paymentMethodId===null)&&typeof u.providerObjectId=="string",k=u.provider==="stripe"&&(u.intentKind==="payment"||u.intentKind==="setup")&&typeof u.clientSecret=="string",H=u.provider==="paypal"&&u.paymentMethodCategory==="wallet"&&u.paymentMethodType==="paypal"&&u.paymentMethodId===null&&u.intentKind==="payment"&&(u.providerObjectType==="order"||u.providerObjectType==="subscription")&&u.clientSecret===null,pe=u.provider===r.provider&&u.paymentMethodCategory===r.paymentMethodCategory&&u.paymentMethodType===r.paymentMethodType&&u.paymentMethodId===r.paymentMethodId&&u.intentKind===r.intentKind;if(!E||!k&&!H||!pe)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:L(S.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-C),durationMode:"machine",requestCategory:"intent_create",statusClass:L(S.status)}),u}catch(S){throw M||this.reportDirectFailure(S,"PAYMENT_PROCESSING_FAILED","processing","intent_create"),S}}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,l=o.paymentMethodType,a=typeof i=="string"&&/^[a-z0-9][a-z0-9_.:-]{0,63}$/i.test(i)&&!/^(?:pm|pi|seti|tok|src|cus|sess|sk|pk)_/i.test(i),c=typeof l=="string"&&l.length>0&&l.trim().toLowerCase()!=="card"&&a,d=o.provider==="stripe"&&(o.paymentMethodCategory==="wallet"||o.paymentMethodCategory==="apm"),y=o.provider==="paypal"&&o.paymentMethodCategory==="wallet"&&o.paymentMethodType==="paypal";if(!c||!d&&!y)throw new m("Invalid non-card decline classification.","validation_error",{code:"InvalidSessionIntentDeclineRequest"});let T=y?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:i}:{provider:"stripe",paymentMethodCategory:o.paymentMethodCategory,paymentMethodType:o.paymentMethodType,providerDeclineReason:i},C=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(!C.ok)throw await N(C,"Failed to report checkout decline")}async getPaymentsByEmail(e,t){this.beginDirectTelemetryOperation();let r=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved"});let s=t?.page??1,o=t?.limit??1,i=new URLSearchParams({email:e,page:String(s),limit:String(o),sortField:"createdAt",sortDirection:"DESC"});try{let l=await fetch(`${this.baseUrl}/v1/payments?${i.toString()}`,{method:"GET",signal:t?.signal,keepalive:!0});if(!l.ok)throw new m("Failed to fetch payments","api_error",{statusCode:l.status});let a=await l.json();return this.directTelemetry?.log({name:"operation.recovery.completed",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),this.directTelemetry?.performance({stage:"recovery",durationMs:Math.max(0,this.telemetryTimestamp()-r),durationMode:"machine",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),a}catch(l){throw this.reportDirectFailure(l,"RECOVERY_FAILED","recovery","other","saved"),l}}async createAndFetchSession(e){this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp(),r=$(e.timeoutMs??12e3),s={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});try{let o=await this.createAndFetchSessionRequest(e,t,r.signal,s);return this.adoptDirectTelemetryCheckout(o.data.session?.id),this.directTelemetry?.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:s.statusClass}),this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:"session_create",statusClass:s.statusClass,attempt:s.attempt}),o}catch(o){if(!(o instanceof m&&o.code==="session_auto_completed"))try{this.telemetryHooks?.onSessionCreateFailure?.(o)}catch{}let i=Y(o,"CHECKOUT_SESSION_CREATE_FAILED");throw this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:"session_create",statusClass:i.statusClass,attempt:s.attempt}),o instanceof m&&o.type==="validation_error"?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}):o instanceof m&&Ue(o.statusCode)?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create",statusClass:"4xx"}):o instanceof m&&o.code==="session_auto_completed"||this.directTelemetry?.error({...i,stage:"session_create",requestCategory:"session_create"}),o}finally{r.clear()}}async createAndFetchSessionRequest(e,t,r,s){let o=e.products??De(e.items,e.subscriptions),i=Fe(e.currency,e.items,e.subscriptions,o);if(!i)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 l={clientId:e.clientId,checkoutVersion:oe,successUrl:e.successUrl,cancelUrl:e.cancelUrl,currency:i,checkoutMode:e.checkoutMode??"full",products:o.map(p=>At(p,i)),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&&(l.tokenizedData=e.tokenizedData),e.tagsData&&(l.tagsData=e.tagsData),e.utmMetadata?.length&&(l.utmMetadata=e.utmMetadata),e.avsCheck!==void 0&&(l.avsCheck=e.avsCheck),e.checkoutType&&(l.checkoutType=e.checkoutType),e.checkoutLayout&&(l.checkoutLayout=e.checkoutLayout),e.avsConfig&&(l.avsConfig=e.avsConfig);let a={"Content-Type":"application/json",[Ae]:oe},c=Dt(e.idempotencyKey);c&&(a[Ie]=c);let d,y=!1,T=Vt(e),C=p=>{try{this.telemetryHooks?.onRetry?.("session_create",p),this.directTelemetry?.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:p})}catch{}};for(let p=0;p<3;p++){s.attempt=p;try{T?.onAttempt?.(p)}catch{}try{d=await fetch(`${this.baseUrl}/v1/checkouts/sessions?expand=true`,{method:"POST",headers:a,body:JSON.stringify(l),signal:r})}catch(w){if(s.statusClass=r.aborted||w instanceof Error&&w.name==="AbortError"?"timeout":"network_error",r.aborted||w instanceof Error&&w.name==="AbortError"||p>=2)throw w;let E=p+1;C(E),await G(p,r);continue}let _=L(d.status);if(s.statusClass=_,y||(y=!0,this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:_,attempt:p}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:"session_create",statusClass:_,attempt:p})),d.status===204)throw new m("Session auto-completed \u2014 payment method already on file","api_error",{code:"session_auto_completed"});if(d.ok)break;let u=await N(d,"Failed to create checkout session");if(u.code===Rt&&p<2){C(p+1),await G(p,r);continue}throw u}if(!d)throw new TypeError("Checkout-session creation exhausted its retry budget.");let g=await d.json();if(g.data&&"gateways"in g.data){this.autoCacheDisplayData(g.data.uuid,e);let p=this.mergeCachedDisplayData(g.data),_=this.normalizeRawSession(p);return g.vault&&_.data.session&&(_.data.session.vault=this.toVaultBlock(g.vault)),{..._,autoProcessingError:g.autoProcessingError,autoProcessingAttempted:g.autoProcessingAttempted,autoProcessingPending:g.autoProcessingPending}}let M=g.data?.uuid;if(!M)throw new m("No session ID returned","api_error",{code:"InvalidCheckoutSessionResponse"});return this.autoCacheDisplayData(M,e),this.adoptDirectTelemetryCheckout(M),{...await this.getUnifiedCheckoutSession(M),autoProcessingError:g.autoProcessingError,autoProcessingAttempted:g.autoProcessingAttempted,autoProcessingPending:g.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??Ft,o=Date.now()+s,i=this.clampRetryAfterMs(t?.initialDelayMs??Oe),l=0;try{for(;;){let a=o-Date.now();if(a<=0)throw se();if(i>0){try{l+=1,this.telemetryHooks?.onRetry?.("session_read",l),this.directTelemetry?.log({name:"operation.retry",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:"saved",attempt:l})}catch{}if(await Ne(Math.min(i,a)),Date.now()>=o)throw se()}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 se();i=this.clampRetryAfterMs(Math.max(i*2,xt))}}catch(a){throw a instanceof m&&a.code==="checkout_processing_timeout"&&this.reportDirectFailure(a,"RECOVERY_FAILED","recovery","session_read","saved"),a}}normalizeRawSession(e){let t=e.gateways??{},r=[],s={session:this.toCheckoutSession(e)},o=t.stripe;if(o?.publishableKey){r.push("stripe");let a=[e.stripeClientSecret,o.stripeClientSecret].find(c=>typeof c=="string"&&c.length>0);s.stripe={clientSecret:a??"",publishableKey:o.publishableKey??void 0,paypalPublishableKey:o.paypalPublishableKey??void 0,environment:o.environment,enabledPaymentMethods:Array.isArray(o.enabledPaymentMethods)?o.enabledPaymentMethods.filter(c=>typeof c=="string"):void 0}}let i=t.paypal;return i?.publishableKey&&(r.push("paypal"),s.paypal={publishableKey:i.publishableKey,environment:i.environment}),{providers:r,mode:"tokenize",data:s,raw:{data:e}}}toCheckoutSession(e){let t=e.products??[],r=typeof e.totalAmount=="number"&&Number.isFinite(e.totalAmount),s=t.reduce((c,d)=>c+(d.overrideAmount??d.totalAmount??0),0),o=r?e.totalAmount:s,i=Math.round(o*100),l=e.currency??t[0]?.currency??"USD",a=t.some(c=>c.type==="subscription")?"subscription":"payment";return{id:e.uuid,clientSecret:e.nonce,mode:a,status:this.toCheckoutSessionStatus(e.status),amount:i,currency:l,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"}):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:V(e,"sessionId")??r,retryAfterMs:this.clampRetryAfterMs(Lt(e,"retryAfterMs")??i??Oe),statusUrl:V(e,"statusUrl"),sessionUrl:V(e,"sessionUrl")}}clampRetryAfterMs(e){return Math.max(0,Math.min(e,Ot))}autoCacheDisplayData(e,t){if(!e)return;let r=t.products??De(t.items,t.subscriptions);if(r.length===0&&!t.currency)return;let s=t.products!==void 0,o=Fe(t.currency,s?void 0:t.items,s?void 0:t.subscriptions,r);q(e,{currency:o??void 0,products:r.map(i=>({code:i.code??i.providerItemId??i.providerPlanId,type:i.type,name:i.name??i.itemName??i.providerItemName??i.subscriptionName??i.providerPlanName??null,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency??o??void 0}))})}mergeCachedDisplayData(e){let t=he(e.uuid),r=new Map,s=i=>i?`code:${i}`:void 0;for(let i of t?.products??[]){let l=s(i.code);l&&r.set(l,i)}let o=(e.products??[]).map(i=>{let l=s(i.code),a=l?r.get(l):void 0;return{...i,name:i.name??a?.name??null,totalAmount:i.totalAmount??a?.totalAmount,overrideAmount:i.overrideAmount??a?.overrideAmount,currency:i.currency??a?.currency}});return{...e,currency:e.currency??t?.currency,products:o}}};D.activeVaultCaptureRequests=new Map;var F=D;function Be(n,e){let t=F;return new t(n,e)}function je(n){return{payment:"payment",address:"address"}[n]}function ae(n){switch(n){case"night":return"night";case"flat":return"flat";default:return"stripe"}}function zt(n){return{...n,theme:ae(n.theme)}}function ve(n){return n?JSON.stringify(n.map(e=>e.trim().toLowerCase())):null}function Ke(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 Ht(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 W=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 jt(e.publishableKey,{locale:e.locale??"auto"});if(!t)throw new h("Failed to initialize Stripe. Check your publishable key.","authentication_error");this.stripe=t}getElements(e){if(!this.stripe)throw new h("StripeAdapter not initialized. Call initialize() first.","api_error");let t=e?.appearance?{theme:ae(e.appearance.theme),variables:e.appearance.variables,rules:e.appearance.rules}:void 0,r=t?JSON.stringify(t):null,s=ve(e?.paymentMethodTypes),o=e?.clientSecret??null;if(this.elements&&s&&(s!==this.appliedPaymentMethodTypesKey||o!==this.appliedClientSecret)&&(this.elements=null,this.appliedAppearanceKey=null,this.appliedPaymentMethodTypesKey=null,this.appliedClientSecret=null,this.verifiedClientSecret=null,this.verifiedPaymentMethodTypesKey=null),this.elements)r!==this.appliedAppearanceKey&&(this.elements.update({appearance:t??{}}),this.appliedAppearanceKey=r);else{let i,l=e?.amount??0,a=(e?.currency??"usd").toLowerCase(),c=e?.paymentMethodCreation??"manual";e?.clientSecret?i={clientSecret:e.clientSecret}:l>0?(i={mode:"payment",amount:l,currency:a,paymentMethodCreation:c},e?.setupFutureUsage&&(i.setupFutureUsage=e.setupFutureUsage)):i={mode:"setup",currency:a,paymentMethodCreation:c},!e?.clientSecret&&e?.paymentMethodTypes&&(i.paymentMethodTypes=e.paymentMethodTypes),t&&(i.appearance=t),this.elements=this.stripe.elements(i),this.appliedAppearanceKey=r,this.appliedPaymentMethodTypesKey=s,this.appliedClientSecret=o,this.verifiedClientSecret=null,this.verifiedPaymentMethodTypesKey=null}return this.elements}async assertClientSecretPaymentMethods(e,t){if(!this.stripe)throw new h("StripeAdapter not initialized. Call initialize() first.","api_error");let r,s=!1;if(Kt(e)){let{setupIntent:a,error:c}=await this.stripe.retrieveSetupIntent(e);r=a,s=!!c}else{let{paymentIntent:a,error:c}=await this.stripe.retrievePaymentIntent(e);r=a,s=!!c}let o=r?.payment_method_types;if(s||!Array.isArray(o))throw new h("Unable to verify the payment methods configured for this client secret.","api_error",{param:"clientSecret"});let i=new Set(t.map(a=>a.toLowerCase()));if(o.some(a=>typeof a!="string"||!i.has(a.trim().toLowerCase()))||o.length===0)throw new h("The client-secret intent must enable only declared non-card payment methods.","validation_error",{param:"clientSecret"})}async createElement(e,t){let r=t;if(e==="payment"){let a=t.paymentMethodTypes?.map(c=>c.trim()).filter(c=>c&&c.toLowerCase()!=="card");if(!a?.length)throw new h("At least one supported non-card payment method is required.","validation_error",{param:"paymentMethodTypes"});if(r={...t,paymentMethodTypes:a},r.clientSecret){let c=ve(a);this.elements&&this.appliedClientSecret===r.clientSecret&&this.appliedPaymentMethodTypesKey===c&&this.verifiedClientSecret===r.clientSecret&&this.verifiedPaymentMethodTypesKey===c||await this.assertClientSecretPaymentMethods(r.clientSecret,a)}}let s=this.getElements(r);e==="payment"&&r.clientSecret&&(this.verifiedClientSecret=r.clientSecret,this.verifiedPaymentMethodTypesKey=ve(r.paymentMethodTypes));let o=je(e),i={};r.layout&&(i.layout=r.layout),r.defaultValues&&(i.defaultValues=r.defaultValues),r.readOnly&&(i.readOnly=r.readOnly),r.mode&&(i.mode=r.mode);let l=s.create(o,i);return Ke(l)}getElement(e){if(!this.elements)return null;let t=je(e),r=this.elements.getElement(t);return r?Ke(r):null}async submitElements(){if(!this.stripe||!this.elements)return{error:new h("Stripe not initialized","api_error")};let{error:e}=await this.elements.submit();return e?{error:new h(e.message??"Validation failed","validation_error")}:{}}async confirmPayment(e){if(!this.stripe||!this.elements)throw new h("StripeAdapter not initialized or no elements created.","api_error");let t=e.billingDetails,r=t?Ht(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(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("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("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(o.message??"PayPal payment failed","validation_error",{code:o.code})}}let r;try{let o=await new F(t).createSessionIntent(e.sessionId,e.nonce??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"});if(o.provider!=="stripe")throw new h("Invalid provider returned for PayPal intent","api_error");r=o.clientSecret}catch(o){return{status:"failed",error:o instanceof h?o:new h("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 F(t).reportSessionIntentDecline(e.sessionId,e.nonce,{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:s.code??"provider_declined"})}catch{}return{status:"failed",error:new h(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("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(i.message??"Failed to retrieve PayPal payment","api_error")};if(o&&(o.status==="requires_capture"||o.status==="succeeded")){let l=typeof o.payment_method=="string"?o.payment_method:o.payment_method?.id,a=new URL(window.location.href);return a.searchParams.delete("payment_intent"),a.searchParams.delete("payment_intent_client_secret"),a.searchParams.delete("redirect_status"),window.history.replaceState({},"",a.toString()),{status:o.status,paymentIntentId:o.id,paymentMethodId:l}}return{status:"failed",error:new h("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:ae(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 P,classifyTelemetryFailure as _e,resolveBillingApiUrl as et,SDK_VERSION as Zt}from"@flopay/shared";import{FloPayError as $t}from"@flopay/shared";var 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 l=r.paymentMethodTypes?.map(a=>a.trim()).filter(a=>a&&a.toLowerCase()!=="card");if(!l?.length)throw new $t("At least one supported non-card payment method is required.","validation_error",{param:"paymentMethodTypes"});r.paymentMethodTypes=l}let s=this.provider.getElement(e);if(s)return this.elementMap.set(e,s),s;let o=this.elementMap.get(e);o&&o.destroy();let i=await this.provider.createElement(e,r);return this.elementMap.set(e,i),i}getElement(e){return this.elementMap.get(e)??null}async submit(){return{}}destroy(){for(let e of this.elementMap.values())e.destroy();this.elementMap.clear()}};import{buildTelemetryErrorEvent as Gt,buildTelemetryLogEvent as Yt,buildTelemetryTerminalEvent as Ge,FloPayError as ze,resolveBillingApiUrl as He,SDK_VERSION as $e}from"@flopay/shared";var Te="flopay-vault",Ye={ready:["vault.widget.ready","vault_ready"],submitting:["vault.submission.started","vault_submit"],blocked:["operation.state_transition","vault_submit"],action_required:["vault.action.required","three_ds_handoff"]};function Q(n){let e={class:n.class,stage:n.stage};"code"in n&&(e.code=n.code),"provider"in n&&n.provider&&(e.provider=n.provider),"paymentMethodCategory"in n&&n.paymentMethodCategory&&(e.paymentMethodCategory=n.paymentMethodCategory),"outcome"in n&&(e.outcome=n.outcome),"durationMs"in n&&n.durationMs!==void 0&&(e.durationMs=n.durationMs),"durationMode"in n&&n.durationMode&&(e.durationMode=n.durationMode);try{globalThis.Sentry?.addBreadcrumb?.({category:"flopay.telemetry",level:n.class==="technical_error"?"error":"info",message:n.class==="lifecycle"?n.name:n.class==="technical_error"?n.code:n.class==="expected_outcome"?n.outcome:"sdk.performance",data:e})}catch{}}function le(n,e){return Yt({eventId:"11111111-1111-4111-8111-111111111111",name:n,stage:e,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}function We(n){return n?{errorCode:"VAULT_SUBMIT_FAILED",stage:"vault_submit",failureCategory:"provider_runtime"}:{errorCode:"VAULT_LOAD_FAILED",stage:"vault_mount",failureCategory:"provider_runtime"}}function Wt(n,e){if(n==="complete"||n==="decline")return Ge({eventId:"22222222-2222-4222-8222-222222222222",outcome:n==="complete"?"payment_succeeded":"payment_declined",sequence:0,provider:"pcivault",paymentMethodCategory:"card"});if(n==="error"){let s=We(e);return Gt({eventId:"33333333-3333-4333-8333-333333333333",...s,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}let[t,r]=Ye[n];return le(t,r)}function Jt(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===Te&&(e.type==="ready"||e.type==="submitting"||e.type==="blocked"||e.type==="complete"||e.type==="decline"||e.type==="error"||e.type==="action_required")}function Qt(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===Te&&e.type==="validation"&&Array.isArray(e.messages)}function Xt(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===Te&&e.type==="resize"&&typeof e.height=="number"&&Number.isFinite(e.height)}var B=class{constructor(e={},t){this.provider="pcivault";this.container=null;this.messageHandler=null;this.actionOverlay=null;this.threeDsReturnHandler=null;this.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 v({billingApiUrl:He(),sdkVersion:$e}):void 0)}async mount(e,t){if(this.ownsTelemetryReporter&&!this.telemetryReporter&&(this.telemetryReporter=new v({billingApiUrl:He(),sdkVersion:$e})),this.mountStartedAt=this.telemetryReporter?.now?.()??b(),this.vaultReadyReported=!1,this.submissionStarted=!1,this.submissionStartedAt=null,typeof window>"u"||typeof document>"u")throw this.reportVaultLoadFailure(),new ze("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 ze("No vault capture widget HTML was provided to mount the secure card form.","api_error",{code:"card_capture_no_widget_html"});this.container=e,this.messageToken=t.messageToken??null,this.expectedOrigin=t.expectedOrigin??this.config.expectedOrigin??null,this.theme=t.theme??null;try{this.attachMessageListener(),this.injectWidget(e,t.html)}catch(r){throw this.reportVaultLoadFailure(),r}this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),Q(le("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(Xt(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;this.applyHeight(r.height);return}if(Qt(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;let l=r.messages.filter(a=>typeof a=="string"&&a.trim()).join(" ");this.emit("validation",{sessionId:this.config.sessionId,message:l||void 0});return}if(!Jt(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?.()??b()),Q(Wt(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=We(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]=Ye[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 l=i.data;if(!l||typeof l!="object")return;let a=l;a.source==="flopay-vault-3ds-return"&&(Q(le("vault.three_ds.returned","three_ds_return")),this.telemetryReporter?.log({name:"vault.three_ds.returned",stage:"three_ds_return",provider:"pcivault",paymentMethodCategory:"card"}),this.hideActionRequiredOverlay(),this.postActionCompleted(a.status))};window.addEventListener("message",o),this.threeDsReturnHandler=o,document.body.appendChild(t),this.actionOverlay=t,Q(le("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=Ge({eventId:"77777777-7777-4777-8777-777777777777",outcome:"customer_abandoned",stage:"three_ds_handoff",sequence:0,provider:"pcivault",paymentMethodCategory:"card"});Q(e),this.telemetryReporter?.terminal({outcome:"customer_abandoned",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"}),this.hideActionRequiredOverlay(),this.postActionCompleted("abandoned")}hideActionRequiredOverlay(){this.threeDsReturnHandler&&(window.removeEventListener("message",this.threeDsReturnHandler),this.threeDsReturnHandler=null),this.actionOverlay&&(this.actionOverlay.parentNode?.removeChild(this.actionOverlay),this.actionOverlay=null)}applyHeight(e){let t=this.container?.querySelector("iframe");if(!t)return;let r=Math.max(0,Math.min(Math.ceil(e),2e3));t.style.height=`${r}px`}};function Je(n,e){let t=B;return new t(n,{reporter:e})}var Qe=Symbol.for("@flopay/js.telemetry.bridge.v1");function Xe(n,e,t){let r=()=>e?.now()??t();Object.defineProperty(n,Qe,{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 Ze(n){return n[Qe]}function j(n){if(!n)return!1;let e=n.code?.toLowerCase()??"";return!!n.declineCode||e.includes("declin")}function er(n){return n==="stripe"||n==="paypal"||n==="pcivault"?n:"other"}var ce=class{constructor(e,t,r){this.currentElements=null;this.provider=e,this.config=t,this.telemetryReporter=r??new v({billingApiUrl:et(t.billingApiUrl),sdkVersion:Zt,enabled:t.telemetry!==!1}),Xe(this,this.telemetryReporter,b)}now(){return this.telemetryReporter?.now?.()??b()}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?Je({sessionId:e?.sessionId},this.telemetryReporter):new B({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"&&(j(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 P&&j(r))this.telemetryReporter?.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"});else if(r instanceof P&&r.type==="validation_error")this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal"});else{let s=_e(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"}):j(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 P&&j(t))this.telemetryReporter?.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"});else if(t instanceof P&&t.type==="validation_error")this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal"});else{let r=_e(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 P("A supported non-card payment method is required.","validation_error",{param:"paymentMethodType"});let t=this.now(),r=er(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}):j(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 P&&j(s)?this.telemetryReporter?.terminal({outcome:"payment_declined",provider:r,paymentMethodCategory:e.paymentMethodCategory}):s instanceof P&&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 P("sessionId is required to retrieve a session.","validation_error",{param:"sessionId"});let r=await this.retrieveUnifiedSession(e,t);if(!r.data.session)throw new P("Session not found","api_error");return r.data.session}async retrieveUnifiedSession(e,t){if(!e)throw new P("sessionId is required.","validation_error",{param:"sessionId"});let r=et(t??this.config.billingApiUrl),s=this.now();this.telemetryReporter?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let o,i=Be(r,{now:()=>this.telemetryReporter?.now()??b(),onFirstByte:l=>{o=l},onRetry:(l,a)=>{this.telemetryReporter?.log({name:"operation.retry",stage:l==="session_read"?"session_read":"processing",requestCategory:l,attempt:a})}});try{let l=await i.getUnifiedCheckoutSession(e);return o!==void 0&&(this.telemetryReporter?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:"2xx"}),this.telemetryReporter?.performance({stage:"session_first_byte",durationMs:o,durationMode:"machine",requestCategory:"session_read",statusClass:"2xx"})),this.telemetryReporter?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:"2xx"}),this.telemetryReporter?.log({name:"checkout.data.ready",stage:"checkout_data_ready"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-s,durationMode:"machine",requestCategory:"session_read",statusClass:"2xx"}),l}catch(l){let a=_e(l,l instanceof P&&l.code==="checkout_processing_timeout"?"REQUEST_TIMEOUT":"NETWORK_REQUEST_FAILED");throw this.telemetryReporter?.error({...a,stage:"session_read",provider:"flo",paymentMethodCategory:"unknown"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-s,durationMode:"machine",requestCategory:"session_read",statusClass:a.statusClass}),l}}getRawProvider(){return this.provider.getRawProvider()}destroy(){this.telemetryReporter?.log({name:"checkout.unmount",stage:"unmount"}),this.telemetryReporter?.destroy(),this.currentElements?.destroy(),this.currentElements=null,this.provider.destroy()}};function tt(n,e,t){let r=ce;return new r(n,e,t)}var nt=new Map;function be(n){return Array.isArray(n)?n.map(be):n&&typeof n=="object"?Object.fromEntries(Object.entries(n).filter(([,e])=>e!==void 0).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,be(t)])):n}function rr(n,e){return JSON.stringify([n,we(e?.billingApiUrl),e?.telemetry!==!1,e?.locale??"auto",e?.apiVersion??null,be(e?.appearance??null)])}var de=new Map;async function nr(n,e){if(!n){let l=new v({billingApiUrl:we(e?.billingApiUrl),sdkVersion:rt,enabled:e?.telemetry!==!1});throw l.error({errorCode:"CONFIGURATION_INVALID",stage:"sdk_initialize",paymentMethodCategory:"unknown"}),l.flush().catch(()=>{}).finally(()=>l.destroy()),new tr("A publishable key is required to initialize FloPay.","validation_error",{param:"publishableKey"})}let t=rr(n,e),r=nt.get(t);if(r)return e?.telemetry!==!1&&Ze(r)?.log({name:"sdk.cache.hit",stage:"sdk_initialize"}),r;let s=de.get(t);if(s)return s;let o={...e,publishableKey:n},i=(async()=>{let l=new v({billingApiUrl:we(o.billingApiUrl),sdkVersion:rt,enabled:o.telemetry!==!1}),a=l.now();l.log({name:"sdk.initialize.started",stage:"sdk_initialize"}),l.log({name:"sdk.cache.miss",stage:"sdk_initialize"}),l.log({name:"provider.load.started",stage:"provider_load",provider:"stripe"});let c=new W,d=l.now();try{await c.initialize(o)}catch(C){throw l.error({errorCode:"SDK_INITIALIZATION_FAILED",failureCategory:"provider_runtime",stage:"sdk_initialize",provider:"stripe",paymentMethodCategory:"unknown"}),l.destroy(),C}let y=l.now();l.log({name:"provider.ready",stage:"provider_ready",provider:"stripe"}),l.log({name:"provider.availability.checked",stage:"provider_ready",provider:"stripe"}),l.log({name:"sdk.initialize.ready",stage:"sdk_initialize"}),l.performance({stage:"sdk_initialize",durationMs:y-a,durationMode:"machine",provider:"stripe"}),l.performance({stage:"provider_ready",durationMs:y-d,durationMode:"machine",provider:"stripe"});let T=tt(c,o,l);return nt.set(t,T),T})();de.set(t,i);try{return await i}finally{de.get(t)===i&&de.delete(t)}}import{FloPayError as z,IDEMPOTENCY_IN_PROGRESS_CODE as or,IDEMPOTENCY_KEY_HEADER as sr,SDK_VERSION as ot,buildProductPayload as ir,classifyTelemetryFailure as ar,foldIntoProducts as lr,resolveIdempotencyKey as st,resolveSessionCurrency as cr,telemetryStatusClass as it}from"@flopay/shared";var Se=5,at=new WeakSet;function dr(n){(typeof n=="object"&&n!==null||typeof n=="function")&&at.add(n)}function ur(n){return(typeof n=="object"&&n!==null||typeof n=="function")&&at.has(n)}function pr(n,e){let t=e?.error,r=I(e?.code)??I(t?.code)??`http_${n}`,s=I(e?.message)??I(t?.message)??mr(r,n);return new z(s,"api_error",{code:r,statusCode:n})}function mr(n,e){switch(n){case"CouponLimitExceeded":return`Too many coupon codes \u2014 a checkout session accepts at most ${Se}.`;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 lt(n,e,t){let{billingApiUrl:r,checkoutBaseUrl:s,items:o=[],subscriptions:i=[],products:l,account:a,successUrl:c,cancelUrl:d,checkoutMode:y="confirm",couponCodes:T=[],tagsData:C,redirectParams:g={},setCookie:M=!0,clientId:S,currency:p,utmMetadata:_,idempotencyKey:u}=n,w=st(u);if(T.length>Se)throw new z(`Too many coupon codes \u2014 a checkout session accepts at most ${Se}.`,"validation_error",{code:"CouponLimitExceeded",param:"couponCodes"});let E=l??lr(o,i),k=cr(p,o,i,E);if(!k)throw new z("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 H={clientId:S,checkoutVersion:ot,successUrl:c,cancelUrl:d,currency:k,checkoutMode:y,products:E.map(A=>ir(A,k)),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:T};C&&(H.tagsData=C),_?.length&&(H.utmMetadata=_);let pe=`${r.replace(/\/+$/,"")}/v1/checkouts/sessions`,O={"Content-Type":"application/json"};w&&(O[sr]=w);let R,X,pt={method:"POST",headers:O,body:JSON.stringify(H),signal:e},Z;try{Z=await fetch(pe,pt)}catch(A){throw dr(A),A}try{t?.(Z.status)}catch{}R=Z.status;try{X=await Z.json()}catch{}if(R>=400)throw pr(R,X);if(R===201){let A=X?.data?.uuid,me=X?.data?.nonce;if(!A)throw new Error("Checkout session created but no UUID was returned by the billing API");if(!me)throw new z("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"});(E.length||k)&&q(A,{currency:k,products:E.map(f=>({code:f.code??f.providerItemId??f.providerPlanId,type:f.type,name:f.name??f.itemName??f.providerItemName??f.subscriptionName??f.providerPlanName??null,totalAmount:f.totalAmount,overrideAmount:f.overrideAmount,currency:f.currency??k}))});let ee=new URL(`${s.replace(/\/+$/,"")}/secure`);ee.searchParams.set("id",A);for(let[f,te]of Object.entries(g))ee.searchParams.set(f,te);if(M&&typeof window<"u"&&typeof document<"u"){let f=JSON.stringify({origin_url:d}),te=window.location.hostname.split(".").slice(-2).join(".");document.cookie=`checkout_data=${encodeURIComponent(f)}; domain=.${te}; path=/; max-age=3600; SameSite=Lax; Secure;`,document.cookie=`flopay_checkout_token=${encodeURIComponent(me)}; domain=.${te}; path=/; max-age=3600; SameSite=Lax; Secure;`}return typeof window<"u"&&(window.location.href=ee.toString()),{status:201,redirectUrl:ee.toString(),nonce:me}}return R===204?(typeof window<"u"&&(window.location.href=c),{status:204}):{status:R}}async function yr(n){let e=dt(n),t=ct(e),r=$(n.timeoutMs);try{let s=await lt(n,r.signal,t);return ut(e,s),s}catch(s){throw ue(e,s),s}finally{r.clear(),K(e.reporter)}}function ct(n){let e=!1;return t=>{if(e)return;e=!0;let r=it(t);n.reporter.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:r,attempt:n.attempt}),n.reporter.performance({stage:"session_first_byte",durationMs:n.reporter.now()-n.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:r,attempt:n.attempt})}}function dt(n){let e=new v({billingApiUrl:n.billingApiUrl,sdkVersion:ot,enabled:n.telemetry!==!1}),t=e.now();return e.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"}),{reporter:e,startedAt:t,attempt:0}}function ut(n,e){let t=it(e.status);n.reporter.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:t}),n.reporter.performance({stage:"session_create",durationMs:n.reporter.now()-n.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:t,attempt:n.attempt})}function ue(n,e){let{reporter:t}=n,r=ar(e,"CHECKOUT_SESSION_CREATE_FAILED");if(t.performance({stage:"session_create",durationMs:t.now()-n.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:r.statusClass,attempt:n.attempt}),e instanceof z&&e.type==="validation_error"){t.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"});return}if(r.statusClass==="4xx"){t.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create",statusClass:"4xx"});return}t.error({...r,stage:"session_create",requestCategory:"session_create"})}function K(n){n.flush().catch(()=>{}).finally(()=>n.destroy())}async function hr(n){let{maxRetries:e=2,...t}=n,r=dt(n),s=ct(r);if(!Number.isFinite(e)||!Number.isInteger(e)||e<0||e>=3)throw r.reporter.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),K(r.reporter),new Error(`Number of retries must be an integer between 0 and ${2}`);let o={...t,idempotencyKey:st(t.idempotencyKey)},i=$(t.timeoutMs),l;for(let a=0;a<=e;a++){r.attempt=a;try{let c=await lt(o,i.signal,s);return ut(r,c),i.clear(),K(r.reporter),c}catch(c){l=c;let d=c instanceof Error&&c.name==="AbortError",y=ur(c),T=c instanceof z&&c.code===or;if((d||y||T)&&!i.signal.aborted&&a<e){r.reporter.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:a+1});try{await G(a,i.signal)}catch(C){throw ue(r,C),i.clear(),K(r.reporter),C}continue}throw ue(r,c),i.clear(),K(r.reporter),c}}throw ue(r,l),i.clear(),K(r.reporter),l??new Error("Unknown error during checkout session creation")}export{ce as FloPay,J as FloPayElements,F as PaymentAPI,B as PciVaultCardCapture,Ve as SESSION_CREATE_TELEMETRY,W as StripeAdapter,q as cacheSessionDisplayData,ge as clearSessionDisplayData,yr as createCheckoutSession,hr as createCheckoutSessionWithRetries,he as getSessionDisplayData,nr as loadFloPay,zt as toStripeAppearance,ae as toStripeAppearanceTheme};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@flopay/js",
|
|
3
|
-
"version": "1.4.
|
|
3
|
+
"version": "1.4.13",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"sideEffects": false,
|
|
6
6
|
"publishConfig": {
|
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
],
|
|
28
28
|
"dependencies": {
|
|
29
29
|
"@stripe/stripe-js": "^9.8.0",
|
|
30
|
-
"@flopay/shared": "1.4.
|
|
30
|
+
"@flopay/shared": "1.4.13"
|
|
31
31
|
},
|
|
32
32
|
"devDependencies": {
|
|
33
33
|
"jsdom": "^29.1.1",
|