@flopay/js 1.4.22 → 1.4.24

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/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{FloPayError as mr,resolveBillingApiUrl as ke,SDK_VERSION as ct}from"@flopay/shared";import{loadStripe as Xt}from"@stripe/stripe-js";import{FloPayError as g,isMoneySettledOutcome as Zt,isSetupIntentClientSecret as er}from"@flopay/shared";import{FloPayError as h,SDK_VERSION as N,FLO_SDK_VERSION_HEADER as ve,IDEMPOTENCY_KEY_HEADER as Oe,IDEMPOTENCY_IN_PROGRESS_CODE as Ot,assertCaptureMethodEligible as qe,buildProductPayload as Be,classifyPaymentRejection as qt,classifyTelemetryFailure as G,foldIntoProducts as Te,isDetachedSessionEligible as Ut,isUuidV4 as Ue,normalizeCheckoutFailureOutcome as Le,randomUuidV4 as Lt,resolveIdempotencyKey as Nt,resolveSessionCurrency as _e,telemetryStatusClass as A}from"@flopay/shared";function E(n){return typeof n=="string"&&n.trim()?n:void 0}function Ae(n){if(typeof n=="string")return n.trim()?n:void 0;if(Array.isArray(n))return n.filter(t=>typeof t=="string"&&t.trim().length>0).join("; ")||void 0}var Tt="flopay_session_display:";var oe=new Map;function se(n){return`${Tt}${n}`}function ye(){if(typeof window>"u")return null;try{return window.sessionStorage}catch{return null}}function q(n,e,t){if(!n)return;let r=t?.ttlMs??36e5,o={data:e,expiresAt:Date.now()+r},s=ye();if(s)try{s.setItem(se(n),JSON.stringify(o));return}catch{}oe.set(n,o)}function he(n){if(!n)return null;let e=ye();if(e)try{let r=e.getItem(se(n));if(r){let o=JSON.parse(r);if(o&&typeof o.expiresAt=="number"&&o.expiresAt>Date.now())return o.data;e.removeItem(se(n))}}catch{}let t=oe.get(n);if(t){if(t.expiresAt>Date.now())return t.data;oe.delete(n)}return null}function ge(n){if(!n)return;oe.delete(n);let e=ye();if(e)try{e.removeItem(se(n))}catch{}}import{buildTelemetryErrorEvent as Ie,buildTelemetryLogEvent as _t,buildTelemetryPerformanceEvent as wt,buildTelemetryTerminalEvent as St,serializeTelemetryBatch as bt,TELEMETRY_MAX_BATCH_BYTES as Mt}from"@flopay/shared";var kt="/v1/sdk-telemetry/events",fe=16,Pt=64,Et=1500,xe=1e3,Rt=64,At="00000000-0000-4000-8000-000000000000",It={technical_error:8,lifecycle:32,expected_outcome:32,performance:24};function U(){try{return globalThis.crypto.randomUUID()}catch{let n=new Uint8Array(16);try{globalThis.crypto.getRandomValues(n)}catch{for(let t=0;t<n.length;t+=1)n[t]=Math.floor(Math.random()*256)}n[6]=n[6]&15|64,n[8]=n[8]&63|128;let e=[...n].map(t=>t.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}}function xt(n){try{return new TextEncoder().encode(n).byteLength}catch{return n.length}}function Dt(n){return JSON.stringify([n.code,n.failureCategory,n.stage,n.provider,n.attempt,n.statusClass,n.requestCategory,n.paymentMethodCategory,n.checkoutMode,n.layout])}function _(){return globalThis.performance?.now()??0}var C=class{constructor(e){this.ingestionDisabled=!1;this.queue=[];this.sequence=0;this.flushTimer=null;this.flushInFlight=null;this.reportedFailures=new Map;this.checkoutContext={};this.checkoutStartedAt=null;this.destroyed=!1;this.pageExitHandler=()=>{this.drainQueue()};this.visibilityHandler=()=>{document.visibilityState==="hidden"&&this.flush()};this.eventCounts={technical_error:0,lifecycle:0,expected_outcome:0,performance:0};this.endpoint=`${e.billingApiUrl.replace(/\/+$/,"")}${kt}`,this.sdkPackage=e.sdkPackage??"@flopay/js",this.sdkVersion=e.sdkVersion,this.correlationId=U(),this.merchantEnabled=e.enabled!==!1,this.clock=e.clock??_,this.browserTransportAvailable=typeof window<"u"&&typeof document<"u",this.browserTransportAvailable&&(window.addEventListener("pagehide",this.pageExitHandler),document.addEventListener("visibilitychange",this.visibilityHandler))}log(e){this.canCollect()&&this.enqueue(_t({...this.checkoutContext,...e,eventId:U(),sequence:this.sequence++}))}error(e){if(!this.canCollect())return;let t=Ie({...this.checkoutContext,...e,eventId:At,sequence:0}),r=Dt(t),o=this.now();this.pruneReportedFailures(o);let s=this.reportedFailures.get(r);if(s!==void 0&&o>=s&&o-s<xe){this.log({name:"operation.deduplicated",stage:e.stage,provider:e.provider,paymentMethodCategory:e.paymentMethodCategory,attempt:e.attempt});return}this.rememberReportedFailure(r,o),this.enqueue(Ie({...this.checkoutContext,...e,eventId:U(),sequence:this.sequence++}))}performance(e){this.canCollect()&&this.enqueue(wt({...this.checkoutContext,...e,eventId:U(),sequence:this.sequence++}))}terminal(e){if(this.canCollect()&&(this.enqueue(St({...this.checkoutContext,...e,eventId:U(),sequence:this.sequence++})),e.outcome!=="action_required"&&this.checkoutStartedAt!==null)){let t=this.checkoutStartedAt;this.checkoutStartedAt=null,this.performance({stage:"total_journey",durationMs:Math.max(0,this.now()-t),durationMode:"total",provider:e.provider,paymentMethodCategory:e.paymentMethodCategory})}}now(){try{return this.clock()}catch{return _()}}pruneReportedFailures(e){for(let[t,r]of this.reportedFailures)(e<r||e-r>=xe)&&this.reportedFailures.delete(t)}rememberReportedFailure(e,t){for(;this.reportedFailures.size>=Rt;){let r=this.reportedFailures.keys().next();if(r.done)break;this.reportedFailures.delete(r.value)}this.reportedFailures.set(e,t)}setCheckoutContext(e){this.checkoutContext={checkoutMode:e.checkoutMode,layout:e.layout}}beginCheckout(e={}){return this.canCollect()?(this.drainQueue(),this.setCheckoutContext(e),this.sequence=0,this.reportedFailures.clear(),this.eventCounts={technical_error:0,lifecycle:0,expected_outcome:0,performance:0},this.checkoutStartedAt=this.now(),this.checkoutStartedAt):0}enqueue(e){if(this.canCollect()&&!(this.queue.length>=Pt||this.eventCounts[e.class]>=It[e.class])){if(this.eventCounts[e.class]+=1,this.queue.push(e),this.queue.length>=fe){this.flush();return}this.scheduleFlush()}}canCollect(){return this.browserTransportAvailable&&this.merchantEnabled&&!this.ingestionDisabled&&!this.destroyed}async flush(){if(this.flushInFlight)return this.flushInFlight;if(!this.browserTransportAvailable||this.destroyed||this.ingestionDisabled||this.queue.length===0)return;this.clearFlushTimer();let e=this.queue.splice(0,fe);return this.flushInFlight=this.sendBatch(e).finally(()=>{this.flushInFlight=null,this.queue.length>0&&this.scheduleFlush()}),this.flushInFlight}destroy(){this.destroyed||(this.drainQueue(),this.destroyed=!0,this.clearFlushTimer(),this.browserTransportAvailable&&(window.removeEventListener("pagehide",this.pageExitHandler),document.removeEventListener("visibilitychange",this.visibilityHandler)),this.queue.splice(0),this.reportedFailures.clear())}disable(){this.merchantEnabled=!1,this.queue.splice(0),this.reportedFailures.clear(),this.clearFlushTimer()}drainQueue(){if(!(!this.browserTransportAvailable||this.destroyed||this.ingestionDisabled||this.queue.length===0))for(this.clearFlushTimer();this.queue.length>0;){let e=this.queue.splice(0,fe);this.sendBatch(e)}}async sendBatch(e){if(!this.browserTransportAvailable||this.ingestionDisabled)return;let t=bt(e,{correlationId:this.correlationId,sdkPackage:this.sdkPackage,sdkVersion:this.sdkVersion,batchId:U()});if(xt(t)>Mt)return;let r=typeof AbortController>"u"?null:new AbortController,o=null;try{let s=fetch(this.endpoint,{method:"POST",headers:{"content-type":"text/plain;charset=UTF-8"},body:t,credentials:"omit",keepalive:!0,referrerPolicy:"no-referrer",signal:r?.signal}).then(async l=>l.status!==202?null:(await l.json().catch(()=>null))?.status==="disabled"?"disabled":null).catch(()=>null),i=new Promise(l=>{o=setTimeout(()=>{r?.abort(),l(null)},Et)});await Promise.race([s,i])==="disabled"&&this.disableFromIngestion()}catch{}finally{o&&clearTimeout(o)}}disableFromIngestion(){this.ingestionDisabled=!0,this.queue.splice(0),this.reportedFailures.clear(),this.clearFlushTimer()}scheduleFlush(){this.flushTimer||this.destroyed||this.ingestionDisabled||(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush()},0))}clearFlushTimer(){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null)}},De=Symbol.for("@flopay/js.telemetry.reporter-factory.v1"),Fe=globalThis;Fe[De]===void 0&&Object.defineProperty(Fe,De,{configurable:!0,enumerable:!1,writable:!1,value:n=>new C(n)});function R(n=12e3){let e=Number.isFinite(n)&&n>=0?n:12e3,t=new AbortController,r=setTimeout(()=>t.abort(),e);return{signal:t.signal,clear:()=>clearTimeout(r)}}function Ft(){return Object.assign(new Error("The operation was aborted."),{name:"AbortError"})}function L(n,e){let t=150*2**n,r=Math.round(t*(.75+Math.random()*.5));return new Promise((o,s)=>{let i,a=()=>e.removeEventListener("abort",l),l=()=>{i!==void 0&&clearTimeout(i),a(),s(Ft())};if(e.aborted){l();return}i=setTimeout(()=>{a(),o()},r),e.addEventListener("abort",l,{once:!0})})}var Ne=1e3,Vt=500,zt=15e3,Bt=3e3,jt=1e4,Kt=1e4;function Ht(n){return typeof n=="object"&&n!==null}function V(n,e){return E(n?.[e])}function Ve(n,e){return Ae(n?.[e])}function $t(n,e){let t=n?.[e];return typeof t=="number"&&Number.isFinite(t)?t:void 0}function je(n){return new Promise(e=>setTimeout(e,n))}function ie(){return new h("Checkout is still processing. Please try again shortly.","api_error",{code:"checkout_processing_timeout"})}async function I(n,e){let t=await n.json().catch(()=>null),r=Ht(t?.error)?t.error:null,o=Ve(t,"message")??Ve(r,"message")??e,s=V(t,"code")??V(t,"gatewayErrorCode")??V(r,"code")??`http_${n.status}`;return new h(o,"api_error",{code:s,statusCode:n.status})}async function Gt(n){let e=n.status===400?await n.clone().json().catch(()=>null):null;return qt(n.status,e)}function ze(n){return n===400||n===422}var ae=2;async function we(n,e,t=ae,r){let o;for(let s=0;;s++)try{return await fetch(n,e)}catch(i){if(e?.signal?.aborted||i instanceof Error&&i.name==="AbortError")throw i;if(o=i,s>=t)throw o;try{r?.(s+1)}catch{}await je(150*2**s)}}var Ke=Symbol.for("@flopay/js.session-create.telemetry.v1");function Yt(n){return n[Ke]}function Wt(n){return"now"in n||"onFirstByte"in n||"onSessionCreateFailure"in n||"onRetry"in n}function He(n){return{userId:n.userId,firstName:n.firstName??null,lastName:n.lastName??null,email:n.email,country:n.country??null,gender:n.gender??null,city:n.city??null,state:n.state??null,zip:n.zip??null,addressLine1:n.addressLine1??null,addressLine2:n.addressLine2??null}}function $e(n,e){e.tagsData&&(n.tagsData=e.tagsData),e.utmMetadata?.length&&(n.utmMetadata=e.utmMetadata),e.avsCheck!==void 0&&(n.avsCheck=e.avsCheck),e.checkoutType&&(n.checkoutType=e.checkoutType),e.checkoutLayout&&(n.checkoutLayout=e.checkoutLayout),e.avsConfig&&(n.avsConfig=e.avsConfig)}function Jt(n,e){let t={clientId:n.clientId,checkoutVersion:N,successUrl:n.successUrl,cancelUrl:n.cancelUrl,currency:e,checkoutMode:"full",deferDataAttachment:!0};return n.captureMethod==="manual"&&(t.captureMethod=n.captureMethod),n.account.country&&(t.accountData={country:n.account.country}),$e(t,n),t}function Qt(n,e,t){return{currency:e,products:t.map(r=>Be(r,e)),couponCodes:n.couponCodes??[],accountData:He(n.account)}}var x=class x{constructor(e,t={}){this.baseUrl=e.replace(/\/+$/,"");let r=Wt(t);this.telemetryHooks=r?t:void 0,this.directTelemetry=r||t.telemetry===!1?void 0:new C({billingApiUrl:this.baseUrl,sdkVersion:N})}destroy(){this.directTelemetry?.destroy()}reportDirectFailure(e,t,r,o,s="unknown"){let i=G(e,t);this.directTelemetry?.error({...i,stage:r,requestCategory:o,paymentMethodCategory:s})}reportAccountSnapshotFailure(e,t){let r=G(e,"NETWORK_REQUEST_FAILED");if(t==="best_effort"&&r.errorCode==="REQUEST_TIMEOUT"){this.directTelemetry?.log({name:"operation.fallback",stage:"processing",requestCategory:"account_snapshot",statusClass:"timeout"});return}this.directTelemetry?.error({...r,stage:"processing",requestCategory:"account_snapshot",paymentMethodCategory:"unknown"})}telemetryTimestamp(){try{return this.telemetryHooks?.now?.()??this.directTelemetry?.now()??_()}catch{return _()}}beginDirectTelemetryCheckout(e){!this.directTelemetry||this.directTelemetryCheckoutId===e||(this.directTelemetryCheckoutId=e,this.directTelemetry.beginCheckout())}beginDirectTelemetryOperation(){this.directTelemetry&&(this.directTelemetryCheckoutId=void 0,this.directTelemetry.beginCheckout())}adoptDirectTelemetryCheckout(e){e&&(this.directTelemetryCheckoutId=e)}async getCheckoutSession(e,t){this.beginDirectTelemetryCheckout(e);let r=this.telemetryTimestamp();this.directTelemetry?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let o={[ve]:N};t&&(o["x-checkout-session-token"]=t);try{let s=await we(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}`,{headers:o},ae,c=>{this.telemetryHooks?.onRetry?.("session_read",c),this.directTelemetry?.log({name:"operation.retry",stage:"session_read",requestCategory:"session_read",attempt:c})}),i=Math.max(0,this.telemetryTimestamp()-r);try{this.telemetryHooks?.onFirstByte?.(i)}catch{}let a=`${Math.floor(s.status/100)}xx`;if(this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:a}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:i,durationMode:"machine",requestCategory:"session_read",statusClass:a}),!s.ok)throw await I(s,"Failed to get checkout session");let l=await s.json();return this.directTelemetry?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:a}),this.directTelemetry?.performance({stage:"session_complete",durationMs:Math.max(0,this.telemetryTimestamp()-r),durationMode:"machine",requestCategory:"session_read",statusClass:a}),{...l,data:this.mergeCachedDisplayData(l.data)}}catch(s){throw this.directTelemetry?.error({...G(s,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"}),s}}cacheSessionDisplayData(e,t,r){q(e,t,r)}clearSessionDisplayData(e){ge(e)}async getVaultCapture(e,t){let r=`${this.baseUrl}\0${e}\0${t??""}`,o=x.activeVaultCaptureRequests.get(r);if(o)return o;let s=this.requestVaultCapture(e,t);x.activeVaultCaptureRequests.set(r,s);try{return await s}finally{x.activeVaultCaptureRequests.get(r)===s&&x.activeVaultCaptureRequests.delete(r)}}async requestVaultCapture(e,t){let r=new AbortController,o=setTimeout(()=>r.abort(),Kt);this.beginDirectTelemetryCheckout(e);let s=this.telemetryTimestamp();this.directTelemetry?.log({name:"vault.capture.requested",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card"});let i={"Content-Type":"application/json"};t&&(i["x-checkout-session-token"]=t);try{let a=await we(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/vault/capture`,{method:"POST",headers:i,signal:r.signal},ae,c=>{this.telemetryHooks?.onRetry?.("vault_capture",c),this.directTelemetry?.log({name:"operation.retry",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card",attempt:c})});if(!a.ok)throw await I(a,"Failed to load the secure card form");let l=await a.json();return this.directTelemetry?.performance({stage:"vault_request",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"2xx"}),this.toVaultBlock(l)}catch(a){let l=r.signal.aborted?new h("Timed out while loading the secure card form. Please try again.","api_error",{code:"vault_capture_timeout"}):a;throw this.reportDirectFailure(l,"VAULT_LOAD_FAILED","vault_request","vault_capture","card"),l}finally{clearTimeout(o)}}async getUnifiedCheckoutSession(e,t){let r=await this.getCheckoutSession(e,t),o=this.normalizeRawSession(r.data),s=r.vault;return s&&o.data.session&&(o.data.session.vault=this.toVaultBlock(s)),o}async processPayment(e,t,r){if(this.beginDirectTelemetryCheckout(t.sessionId),!t.nonce)throw this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"process_payment"}),new h("processPayment requires `nonce` \u2014 pass the value returned from session creation.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let o=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.processing.started",stage:"processing",requestCategory:"process_payment"});let{nonce:s,...i}=t,a;try{a=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(t.sessionId)}/process`,{method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":s},body:JSON.stringify(i)})}catch(l){throw this.reportDirectFailure(l,"PAYMENT_PROCESSING_FAILED","processing","process_payment"),l}if(!a.ok&&a.status!==202){let l=await Gt(a);return l?this.directTelemetry?.terminal({outcome:l,stage:"processing",requestCategory:"process_payment",statusClass:"4xx"}):this.directTelemetry?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",requestCategory:"process_payment",statusClass:A(a.status),failureCategory:a.status>=500?"server_error":void 0}),a}try{let l=await this.resolveProcessResponse(a,t.sessionId,{...r,nonce:s});return this.directTelemetry?.log({name:"payment.processing.completed",stage:"processing",requestCategory:"process_payment",statusClass:A(l.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"process_payment",statusClass:A(l.status)}),l}catch(l){throw l instanceof h&&l.code==="checkout_processing_timeout"||this.reportDirectFailure(l,"PAYMENT_PROCESSING_FAILED","processing","process_payment"),l}}async patchAccountSnapshot(e,t,r,o){this.beginDirectTelemetryCheckout(e);let s=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.state_transition",stage:"processing",requestCategory:"account_snapshot"});let i=o?.timeoutMs??jt,a=new AbortController,l=()=>a.abort();o?.signal&&(o.signal.aborted?a.abort():o.signal.addEventListener("abort",l,{once:!0}));let c=setTimeout(()=>a.abort(),i);try{let d;try{d=await we(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/account`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":t},body:JSON.stringify(r),signal:a.signal},ae,m=>{this.telemetryHooks?.onRetry?.("account_snapshot",m),this.directTelemetry?.log({name:"operation.retry",stage:"processing",requestCategory:"account_snapshot",attempt:m})})}finally{clearTimeout(c),o?.signal?.removeEventListener("abort",l)}if(!d.ok)throw await I(d,"Failed to persist account snapshot");this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"account_snapshot",statusClass:"2xx"})}catch(d){throw this.reportAccountSnapshotFailure(d,o?.telemetryMode??"blocking"),d}}async createSessionIntent(e,t,r,o){if(!t)throw new h("createSessionIntent requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let s=r,i=s.paymentMethodType,a=typeof i=="string"&&i.trim().toLowerCase()==="card",l=typeof i=="string"&&i.length>0&&!a&&(typeof s.paymentMethodId=="string"||s.paymentMethodId===null),c=s.provider==="stripe"&&(s.paymentMethodCategory==="wallet"||s.paymentMethodCategory==="apm")&&(s.intentKind==="payment"||s.intentKind==="setup"),d=s.provider==="paypal"&&s.paymentMethodCategory==="wallet"&&s.paymentMethodType==="paypal"&&s.paymentMethodId===null&&s.intentKind==="payment";if(!l||!c&&!d)throw new h("Only wallet, APM, and PayPal session intents are supported.","validation_error",{code:"InvalidSessionIntentRequest"});let m=s.authorizationAttemptId;if(m!==void 0&&!Ue(m))throw new h("authorizationAttemptId must be a v4 UUID identifying one buyer authorization attempt.","validation_error",{code:"InvalidAuthorizationAttemptId",param:"authorizationAttemptId"});let u=Ue(m)?m:Lt();this.beginDirectTelemetryCheckout(e);let p=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.intent.started",stage:"processing",requestCategory:"intent_create"});let w={"Content-Type":"application/json","x-checkout-session-token":t,[Oe]:o?.idempotencyKey||u},v=!1;try{let T=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents`,{method:"POST",headers:w,body:JSON.stringify({...r,authorizationAttemptId:u}),signal:o?.signal});if(!T.ok){v=!0;let $=await I(T,"Failed to create checkout intent"),Z=G($,"PAYMENT_PROCESSING_FAILED");throw ze($.statusCode)?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"intent_create",statusClass:"4xx"}):this.directTelemetry?.error({...Z,stage:"processing",requestCategory:"intent_create"}),$}let H=(await T.json()).data;if(!H||typeof H!="object")throw new h("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});let y=H,Q=y.paymentMethodType,X=(y.paymentMethodCategory==="wallet"||y.paymentMethodCategory==="apm")&&typeof Q=="string"&&Q.trim().toLowerCase()!=="card"&&(typeof y.paymentMethodId=="string"||y.paymentMethodId===null)&&typeof y.providerObjectId=="string",P=y.provider==="stripe"&&(y.intentKind==="payment"||y.intentKind==="setup")&&typeof y.clientSecret=="string",M=y.provider==="paypal"&&y.paymentMethodCategory==="wallet"&&y.paymentMethodType==="paypal"&&y.paymentMethodId===null&&y.intentKind==="payment"&&(y.providerObjectType==="order"||y.providerObjectType==="subscription")&&y.clientSecret===null,F=y.provider===r.provider&&y.paymentMethodCategory===r.paymentMethodCategory&&y.paymentMethodType===r.paymentMethodType&&y.paymentMethodId===r.paymentMethodId&&y.intentKind===r.intentKind;if(!X||!P&&!M||!F)throw new h("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});return this.directTelemetry?.log({name:"payment.intent.completed",stage:"processing",requestCategory:"intent_create",statusClass:A(T.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-p),durationMode:"machine",requestCategory:"intent_create",statusClass:A(T.status)}),y}catch(T){throw v||this.reportDirectFailure(T,"PAYMENT_PROCESSING_FAILED","processing","intent_create"),T}}async reportSessionIntentDecline(e,t,r,o){if(!t)throw new h("reportSessionIntentDecline requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let s=r,i=s.providerDeclineReason,a=s.paymentMethodType,l=typeof i=="string"&&/^[a-z0-9][a-z0-9_.:-]{0,63}$/i.test(i)&&!/^(?:pm|pi|seti|tok|src|cus|sess|sk|pk)_/i.test(i),c=typeof a=="string"&&a.length>0&&a.trim().toLowerCase()!=="card"&&l,d=s.provider==="stripe"&&(s.paymentMethodCategory==="wallet"||s.paymentMethodCategory==="apm"),m=s.provider==="paypal"&&s.paymentMethodCategory==="wallet"&&s.paymentMethodType==="paypal";if(!c||!d&&!m)throw new h("Invalid non-card decline classification.","validation_error",{code:"InvalidSessionIntentDeclineRequest"});let u=m?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:i}:{provider:"stripe",paymentMethodCategory:s.paymentMethodCategory,paymentMethodType:s.paymentMethodType,providerDeclineReason:i},p=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents/decline`,{method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":t},body:JSON.stringify(u),signal:o?.signal});if(!p.ok)throw await I(p,"Failed to report checkout decline")}async getPaymentsByEmail(e,t){this.beginDirectTelemetryOperation();let r=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved"});let o=t?.page??1,s=t?.limit??1,i=new URLSearchParams({email:e,page:String(o),limit:String(s),sortField:"createdAt",sortDirection:"DESC"});try{let a=await fetch(`${this.baseUrl}/v1/payments?${i.toString()}`,{method:"GET",signal:t?.signal,keepalive:!0});if(!a.ok)throw new h("Failed to fetch payments","api_error",{statusCode:a.status});let l=await a.json();return this.directTelemetry?.log({name:"operation.recovery.completed",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),this.directTelemetry?.performance({stage:"recovery",durationMs:Math.max(0,this.telemetryTimestamp()-r),durationMode:"machine",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),l}catch(a){throw this.reportDirectFailure(a,"RECOVERY_FAILED","recovery","other","saved"),a}}async createAndFetchSession(e){if(Ut(e))return(await this.createDetachedSession(e)).claimed;this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp(),r=R(e.timeoutMs??12e3),o={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});try{let s=await this.createAndFetchSessionRequest(e,t,r.signal,o);return this.adoptDirectTelemetryCheckout(s.data.session?.id),this.directTelemetry?.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:o.statusClass}),this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:"session_create",statusClass:o.statusClass,attempt:o.attempt}),s}catch(s){throw this.reportSessionCreateFailure(s,t,o),s}finally{r.clear()}}async createAndFetchSessionRequest(e,t,r,o){let s=e.products??Te(e.items,e.subscriptions);qe({captureMethod:e.captureMethod,products:s});let i=_e(e.currency,e.items,e.subscriptions,s);if(!i)throw new h("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});let a={clientId:e.clientId,checkoutVersion:N,successUrl:e.successUrl,cancelUrl:e.cancelUrl,currency:i,checkoutMode:e.checkoutMode??"full",products:s.map(u=>Be(u,i)),accountData:He(e.account),couponCodes:e.couponCodes??[]};e.captureMethod==="manual"&&(a.captureMethod=e.captureMethod),e.tokenizedData&&(a.tokenizedData=e.tokenizedData),$e(a,e);let c=await(await this.postCheckoutSessionCreate(a,e,t,r,o)).json();if(c.data&&"gateways"in c.data){this.autoCacheDisplayData(c.data.uuid,e);let u=this.mergeCachedDisplayData(c.data),p=this.normalizeRawSession(u);return c.vault&&p.data.session&&(p.data.session.vault=this.toVaultBlock(c.vault)),{...p,autoProcessingError:c.autoProcessingError,autoProcessingAttempted:c.autoProcessingAttempted,autoProcessingPending:c.autoProcessingPending}}let d=c.data?.uuid;if(!d)throw new h("No session ID returned","api_error",{code:"InvalidCheckoutSessionResponse"});return this.autoCacheDisplayData(d,e),this.adoptDirectTelemetryCheckout(d),{...await this.getUnifiedCheckoutSession(d),autoProcessingError:c.autoProcessingError,autoProcessingAttempted:c.autoProcessingAttempted,autoProcessingPending:c.autoProcessingPending}}async postCheckoutSessionCreate(e,t,r,o,s){let i={"Content-Type":"application/json",[ve]:N},a=Nt(t.idempotencyKey);a&&(i[Oe]=a);let l,c=!1,d=Yt(t),m=u=>{try{this.telemetryHooks?.onRetry?.("session_create",u),this.directTelemetry?.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:u})}catch{}};for(let u=0;u<3;u++){s.attempt=u;try{d?.onAttempt?.(u)}catch{}try{l=await fetch(`${this.baseUrl}/v1/checkouts/sessions?expand=true`,{method:"POST",headers:i,body:JSON.stringify(e),signal:o})}catch(v){if(s.statusClass=o.aborted||v instanceof Error&&v.name==="AbortError"?"timeout":"network_error",o.aborted||v instanceof Error&&v.name==="AbortError"||u>=2)throw v;let T=u+1;m(T),await L(u,o);continue}let p=A(l.status);if(s.statusClass=p,c||(c=!0,this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:p,attempt:u}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:Math.max(0,this.telemetryTimestamp()-r),durationMode:"machine",requestCategory:"session_create",statusClass:p,attempt:u})),l.status===204)throw new h("Session auto-completed \u2014 payment method already on file","api_error",{code:"session_auto_completed"});if(l.ok)break;let w=await I(l,"Failed to create checkout session");if(w.code===Ot&&u<2){m(u+1),await L(u,o);continue}throw w}if(!l)throw new TypeError("Checkout-session creation exhausted its retry budget.");return l}async createDetachedSession(e){this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp(),r=R(e.timeoutMs??12e3),o={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let s=e.products??Te(e.items,e.subscriptions);try{qe({captureMethod:e.captureMethod,products:s})}catch(p){throw r.clear(),this.reportSessionCreateFailure(p,t,o),p}let i=_e(e.currency,e.items,e.subscriptions,s);if(!i)throw r.clear(),this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),new h("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});let a;try{a=Qt(e,i,s)}catch(p){throw r.clear(),this.reportSessionCreateFailure(p,t,o),p}let l,c;try{if(c=await(await this.postCheckoutSessionCreate(Jt(e,i),e,t,r.signal,o)).json(),!c.data||!("gateways"in c.data))throw new h("The billing API returned no session shell for a detached create. It must support `deferDataAttachment` (TeamFloPay/backend#1099).","api_error",{code:"InvalidCheckoutSessionResponse"});l=this.normalizeRawSession(this.mergeCachedDisplayData(c.data)),c.vault&&l.data.session&&(l.data.session.vault=this.toVaultBlock(c.vault))}catch(p){throw r.clear(),this.reportSessionCreateFailure(p,t,o),p}let d=l.data.session?.id??c.data.uuid??"",m=l.data.session?.clientSecret??c.data.nonce??"";if(!d||!m){r.clear();let p=new h("Checkout session shell was created without a session id or nonce.","api_error",{code:"InvalidCheckoutSessionResponse"});throw this.reportSessionCreateFailure(p,t,o),p}this.adoptDirectTelemetryCheckout(d),this.directTelemetry?.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",statusClass:o.statusClass,paymentMethodCategory:"card"}),this.directTelemetry?.performance({stage:"session_shell",durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:"session_create",statusClass:o.statusClass,attempt:o.attempt,paymentMethodCategory:"card"});let u=this.claimCheckoutSession(d,m,a,{params:e,startedAt:t,deadline:r,createAttempt:o.attempt});return u.catch(()=>{}),{shell:l,sessionId:d,nonce:m,claimed:u}}async claimCheckoutSession(e,t,r,o){let s=o?.startedAt??this.telemetryTimestamp(),i=this.telemetryTimestamp(),a=o?.deadline??R(12e3),l=JSON.stringify(r),c="unknown",d=0;this.directTelemetry?.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"});try{let m;for(d=0;d<3;d++){try{m=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/claim`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":t,[ve]:N},body:l,signal:a.signal})}catch(w){let v=a.signal.aborted||w instanceof Error&&w.name==="AbortError";if(c=v?"timeout":"network_error",v||d>=2)throw w;try{this.telemetryHooks?.onRetry?.("session_claim",d+1),this.directTelemetry?.log({name:"operation.retry",stage:"session_claim",requestCategory:"session_claim",attempt:d+1})}catch{}await L(d,a.signal);continue}if(c=A(m.status),m.ok)break;throw await I(m,"Failed to attach checkout session data")}if(!m)throw new TypeError("Checkout-session claim exhausted its retry budget.");let u=await m.json();if(!u.data||!u.data.gateways)throw new h("The billing API returned no checkout session with gateways after claiming it.","api_error",{code:"InvalidCheckoutSessionResponse"});o?.params&&this.autoCacheDisplayData(u.data.uuid??e,o.params);let p=this.normalizeRawSession(this.mergeCachedDisplayData(u.data));return u.vault&&p.data.session&&(p.data.session.vault=this.toVaultBlock(u.vault)),this.directTelemetry?.log({name:"session.claim.completed",stage:"session_claim",requestCategory:"session_claim",statusClass:c}),this.directTelemetry?.performance({stage:"session_claim",durationMs:Math.max(0,this.telemetryTimestamp()-i),durationMode:"machine",requestCategory:"session_claim",statusClass:c,attempt:d}),this.directTelemetry?.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:c}),this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"session_create",statusClass:c,attempt:o?.createAttempt??d}),p}catch(m){throw this.reportSessionCreateFailure(m,s,{attempt:d,statusClass:c},"session_claim"),m}finally{a.clear()}}reportSessionCreateFailure(e,t,r,o="session_create"){if(!(e instanceof h&&e.code==="session_auto_completed"))try{this.telemetryHooks?.onSessionCreateFailure?.(e)}catch{}let s=G(e,"CHECKOUT_SESSION_CREATE_FAILED");if(this.directTelemetry?.performance({stage:o,durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:o==="session_claim"?"session_claim":"session_create",statusClass:s.statusClass,attempt:r.attempt}),e instanceof h&&e.type==="validation_error"||e instanceof h&&ze(e.statusCode)){this.directTelemetry?.terminal({outcome:"validation_rejected",stage:o,requestCategory:o==="session_claim"?"session_claim":"session_create",...e.type==="validation_error"?{}:{statusClass:"4xx"}});return}e instanceof h&&e.code==="session_auto_completed"||this.directTelemetry?.error({...s,stage:o,requestCategory:o==="session_claim"?"session_claim":"session_create"})}async waitForCheckoutSessionCompletion(e,t){this.beginDirectTelemetryCheckout(e);let r=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:"saved"});let o=t?.timeoutMs??zt,s=Date.now()+o,i=this.clampRetryAfterMs(t?.initialDelayMs??Ne),a=0;try{for(;;){let l=s-Date.now();if(l<=0)throw ie();if(i>0){try{a+=1,this.telemetryHooks?.onRetry?.("session_read",a),this.directTelemetry?.log({name:"operation.retry",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:"saved",attempt:a})}catch{}if(await je(Math.min(i,l)),Date.now()>=s)throw ie()}let c=await this.getUnifiedCheckoutSession(e,t?.nonce),d=c.data.session?.status;if(d==="authorized"||d==="complete"||d==="expired")return this.directTelemetry?.log({name:"operation.recovery.completed",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:"saved"}),this.directTelemetry?.performance({stage:"recovery",durationMs:Math.max(0,this.telemetryTimestamp()-r),durationMode:"machine",requestCategory:"session_read",paymentMethodCategory:"saved"}),c;if(Date.now()>=s)throw ie();i=this.clampRetryAfterMs(Math.max(i*2,Vt))}}catch(l){throw l instanceof h&&l.code==="checkout_processing_timeout"&&this.reportDirectFailure(l,"RECOVERY_FAILED","recovery","session_read","saved"),l}}normalizeRawSession(e){let t=e.gateways??{},r=[],o={session:this.toCheckoutSession(e)},s=t.stripe;if(s?.publishableKey){r.push("stripe");let l=[e.stripeClientSecret,s.stripeClientSecret].find(c=>typeof c=="string"&&c.length>0);o.stripe={clientSecret:l??"",publishableKey:s.publishableKey??void 0,paypalPublishableKey:s.paypalPublishableKey??void 0,environment:s.environment,enabledPaymentMethods:Array.isArray(s.enabledPaymentMethods)?s.enabledPaymentMethods.filter(c=>typeof c=="string"):void 0}}let i=t.paypal;return i?.publishableKey&&(r.push("paypal"),o.paypal={publishableKey:i.publishableKey,environment:i.environment}),{providers:r,mode:"tokenize",data:o,raw:{data:e}}}toCheckoutSession(e){let t=e.products??[],r=typeof e.totalAmount=="number"&&Number.isFinite(e.totalAmount),o=t.reduce((c,d)=>c+(d.overrideAmount??d.totalAmount??0),0),s=r?e.totalAmount:o,i=Math.round(s*100),a=e.currency??t[0]?.currency??"USD",l=e.checkoutMode==="setup"?"setup":t.some(c=>c.type==="subscription")?"subscription":"payment";return{id:e.uuid,clientSecret:e.nonce,mode:l,status:this.toCheckoutSessionStatus(e.status),amount:i,currency:a,captureMethod:e.captureMethod,paymentId:e.paymentId,authorizationExpiresAt:e.authorizationExpiresAt,failureOutcome:Le(e.outcome)??Le(e.failureReason)??(e.status==="expired"&&e.captureMethod==="manual"?"authorization_expired":void 0),customer:{id:e.accountData.userId,email:e.accountData.email,firstName:e.accountData.firstName,lastName:e.accountData.lastName,country:e.accountData.country??void 0,city:e.accountData.city??void 0,state:e.accountData.state??void 0,zip:e.accountData.zip??void 0,gender:e.accountData.gender??void 0,line1:e.accountData.addressLine1??void 0,line2:e.accountData.addressLine2??void 0},metadata:{},checkoutMode:e.checkoutMode,providerPaymentMethodId:typeof e.providerPaymentMethodId=="string"?e.providerPaymentMethodId:null,products:t.map(c=>({...c,totalAmount:typeof c.totalAmount=="number"?c.totalAmount:void 0,overrideAmount:typeof c.overrideAmount=="number"?c.overrideAmount:null,currency:typeof c.currency=="string"?c.currency:void 0,metadata:c.metadata??null})),successUrl:e.successUrl,cancelUrl:e.cancelUrl,coupons:e.coupons,subtotalAmount:e.subtotalAmount,discountAmount:e.discountAmount,totalAmount:e.totalAmount,createdAt:e.createdAt,gateways:e.gateways,accountData:e.accountData,tagsData:e.tagsData}}toVaultBlock(e){return{html:typeof e.html=="string"?e.html:void 0,url:typeof e.url=="string"?e.url:void 0,messageToken:typeof e.messageToken=="string"?e.messageToken:void 0,expectedOrigin:typeof e.expectedOrigin=="string"?e.expectedOrigin:void 0}}toCheckoutSessionStatus(e){return e==="completed"?"complete":e==="authorized"?"authorized":e==="expired"?"expired":"open"}async resolveProcessResponse(e,t,r){if(e.status!==202)return e;let o=await e.json().catch(()=>null),s=this.toCheckoutProcessingPending(o,e,t),i=await this.waitForCheckoutSessionCompletion(s.sessionId,{initialDelayMs:s.retryAfterMs,timeoutMs:r?.pollTimeoutMs,nonce:r?.nonce});if(i.data.session?.status==="complete")return new Response(null,{status:204,statusText:"No Content"});if(i.data.session?.status==="authorized"){let a=i.data.session;return new Response(JSON.stringify({status:"authorized",paymentId:a.paymentId,sessionId:a.id||t,authorizationExpiresAt:a.authorizationExpiresAt}),{status:200,headers:{"Content-Type":"application/json"}})}if(i.data.session?.status==="expired"){let a=i.data.session.failureOutcome==="authorization_expired"||i.data.session.captureMethod==="manual";throw new h(a?"Authorization has expired.":"Checkout session has expired.","api_error",{code:a?"authorization_expired":"checkout_session_expired"})}throw ie()}toCheckoutProcessingPending(e,t,r){let o=t.headers.get("Retry-After"),s=o===null||o.trim()===""?void 0:Number(o),i=s!==void 0&&Number.isFinite(s)?s*1e3:void 0;return{type:"checkout_processing",sessionId:V(e,"sessionId")??r,retryAfterMs:this.clampRetryAfterMs($t(e,"retryAfterMs")??i??Ne),statusUrl:V(e,"statusUrl"),sessionUrl:V(e,"sessionUrl")}}clampRetryAfterMs(e){return Math.max(0,Math.min(e,Bt))}autoCacheDisplayData(e,t){if(!e)return;let r=t.products??Te(t.items,t.subscriptions);if(r.length===0&&!t.currency)return;let o=t.products!==void 0,s=_e(t.currency,o?void 0:t.items,o?void 0:t.subscriptions,r);q(e,{currency:s??void 0,products:r.map(i=>({code:i.code??i.providerItemId??i.providerPlanId,type:i.type,name:i.name??i.itemName??i.providerItemName??i.subscriptionName??i.providerPlanName??null,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency??s??void 0}))})}mergeCachedDisplayData(e){let t=he(e.uuid),r=new Map,o=i=>i?`code:${i}`:void 0;for(let i of t?.products??[]){let a=o(i.code);a&&r.set(a,i)}let s=(e.products??[]).map(i=>{let a=o(i.code),l=a?r.get(a):void 0;return{...i,name:i.name??l?.name??null,totalAmount:i.totalAmount??l?.totalAmount,overrideAmount:i.overrideAmount??l?.overrideAmount,currency:i.currency??l?.currency}});return{...e,currency:e.currency??t?.currency,products:s}}};x.activeVaultCaptureRequests=new Map;var D=x;function Ge(n,e){let t=D;return new t(n,e)}function Ye(n){return{payment:"payment",address:"address"}[n]}function le(n){switch(n){case"night":return"night";case"flat":return"flat";default:return"stripe"}}function tr(n){return{...n,theme:le(n.theme)}}function Se(n){return n?JSON.stringify(n.map(e=>e.trim().toLowerCase())):null}function We(n){let e=n;return{mount(t){e.mount(t)},unmount(){e.unmount()},update(t){e.update(t)},on(t,r){e.on?.(t,r)},off(t,r){e.off?.(t,r)},destroy(){e.destroy()}}}function rr(n){return{billing_details:{...n.email?{email:n.email}:{},...n.name?{name:n.name}:{},...n.address?{address:{...n.address.country?{country:n.address.country}:{},...n.address.postal_code?{postal_code:n.address.postal_code}:{},...n.address.city?{city:n.address.city}:{},...n.address.line1?{line1:n.address.line1}:{},...n.address.line2?{line2:n.address.line2}:{},...n.address.state?{state:n.address.state}:{}}}:{}}}}var Y=class{constructor(){this.name="stripe";this.stripe=null;this.elements=null;this.appliedAppearanceKey=null;this.appliedPaymentMethodTypesKey=null;this.appliedClientSecret=null;this.verifiedClientSecret=null;this.verifiedPaymentMethodTypesKey=null}async initialize(e){if(typeof window>"u")return;let t=await Xt(e.publishableKey,{locale:e.locale??"auto"});if(!t)throw new g("Failed to initialize Stripe. Check your publishable key.","authentication_error");this.stripe=t}getElements(e){if(!this.stripe)throw new g("StripeAdapter not initialized. Call initialize() first.","api_error");let t=e?.appearance?{theme:le(e.appearance.theme),variables:e.appearance.variables,rules:e.appearance.rules}:void 0,r=t?JSON.stringify(t):null,o=Se(e?.paymentMethodTypes),s=e?.clientSecret??null;if(this.elements&&o&&(o!==this.appliedPaymentMethodTypesKey||s!==this.appliedClientSecret)&&(this.elements=null,this.appliedAppearanceKey=null,this.appliedPaymentMethodTypesKey=null,this.appliedClientSecret=null,this.verifiedClientSecret=null,this.verifiedPaymentMethodTypesKey=null),this.elements)r!==this.appliedAppearanceKey&&(this.elements.update({appearance:t??{}}),this.appliedAppearanceKey=r);else{let i,a=e?.amount??0,l=(e?.currency??"usd").toLowerCase(),c=e?.paymentMethodCreation??"manual";e?.clientSecret?i={clientSecret:e.clientSecret}:a>0?(i={mode:"payment",amount:a,currency:l,paymentMethodCreation:c},e?.setupFutureUsage&&(i.setupFutureUsage=e.setupFutureUsage)):i={mode:"setup",currency:l,paymentMethodCreation:c},!e?.clientSecret&&e?.paymentMethodTypes&&(i.paymentMethodTypes=e.paymentMethodTypes),t&&(i.appearance=t),this.elements=this.stripe.elements(i),this.appliedAppearanceKey=r,this.appliedPaymentMethodTypesKey=o,this.appliedClientSecret=s,this.verifiedClientSecret=null,this.verifiedPaymentMethodTypesKey=null}return this.elements}async assertClientSecretPaymentMethods(e,t){if(!this.stripe)throw new g("StripeAdapter not initialized. Call initialize() first.","api_error");let r,o=!1;if(er(e)){let{setupIntent:l,error:c}=await this.stripe.retrieveSetupIntent(e);r=l,o=!!c}else{let{paymentIntent:l,error:c}=await this.stripe.retrievePaymentIntent(e);r=l,o=!!c}let s=r?.payment_method_types;if(o||!Array.isArray(s))throw new g("Unable to verify the payment methods configured for this client secret.","api_error",{param:"clientSecret"});let i=new Set(t.map(l=>l.toLowerCase()));if(s.some(l=>typeof l!="string"||!i.has(l.trim().toLowerCase()))||s.length===0)throw new g("The client-secret intent must enable only declared non-card payment methods.","validation_error",{param:"clientSecret"})}async createElement(e,t){let r=t;if(e==="payment"){let l=t.paymentMethodTypes?.map(c=>c.trim()).filter(c=>c&&c.toLowerCase()!=="card");if(!l?.length)throw new g("At least one supported non-card payment method is required.","validation_error",{param:"paymentMethodTypes"});if(r={...t,paymentMethodTypes:l},r.clientSecret){let c=Se(l);this.elements&&this.appliedClientSecret===r.clientSecret&&this.appliedPaymentMethodTypesKey===c&&this.verifiedClientSecret===r.clientSecret&&this.verifiedPaymentMethodTypesKey===c||await this.assertClientSecretPaymentMethods(r.clientSecret,l)}}let o=this.getElements(r);e==="payment"&&r.clientSecret&&(this.verifiedClientSecret=r.clientSecret,this.verifiedPaymentMethodTypesKey=Se(r.paymentMethodTypes));let s=Ye(e),i={};r.layout&&(i.layout=r.layout),r.defaultValues&&(i.defaultValues=r.defaultValues),r.readOnly&&(i.readOnly=r.readOnly),r.mode&&(i.mode=r.mode);let a=o.create(s,i);return We(a)}getElement(e){if(!this.elements)return null;let t=Ye(e),r=this.elements.getElement(t);return r?We(r):null}async submitElements(){if(!this.stripe||!this.elements)return{error:new g("Stripe not initialized","api_error")};let{error:e}=await this.elements.submit();return e?{error:new g(e.message??"Validation failed","validation_error")}:{}}async confirmPayment(e){if(!this.stripe||!this.elements)throw new g("StripeAdapter not initialized or no elements created.","api_error");let t=e.billingDetails,r=t?rr(t):void 0,{error:o,paymentIntent:s}=await this.stripe.confirmPayment({elements:this.elements,clientSecret:e.clientSecret,confirmParams:{return_url:e.returnUrl??window.location.href,...r?{payment_method_data:r}:{}},redirect:"if_required"});return o?{status:"failed",error:new g(o.message??"Payment failed","api_error",{code:o.code,declineCode:o.decline_code})}:s?{status:{succeeded:"succeeded",processing:"processing",requires_action:"requires_action",requires_payment_method:"failed",canceled:"failed"}[s.status]??"failed",paymentIntentId:s.id,paymentMethodId:this.extractPaymentMethodId(s.payment_method)}:{status:"failed",error:new g("No payment intent returned","api_error")}}extractPaymentMethodId(e){if(typeof e=="string"&&e.startsWith("pm_"))return e;if(e&&typeof e=="object"&&typeof e.id=="string")return e.id}async confirmPayPalPayment(e){if(!this.stripe)return{status:"failed",error:new g("Stripe not initialized","api_error")};let t=e.billingApiUrl.replace(/\/+$/,"");if(this.elements){let{error:s}=await this.elements.submit();if(s)return{status:"failed",error:new g(s.message??"PayPal payment failed","validation_error",{code:s.code})}}let r;try{let s=await new D(t).createSessionIntent(e.sessionId,e.nonce??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"});if(s.provider!=="stripe")throw new g("Invalid provider returned for PayPal intent","api_error");r=s.clientSecret}catch(s){return{status:"failed",error:s instanceof g?s:new g("Failed to create PayPal payment intent","api_error")}}let{error:o}=await this.stripe.confirmPayment({clientSecret:r,elements:this.elements??void 0,confirmParams:{return_url:e.returnUrl}});if(o){if(e.nonce)try{await new D(t).reportSessionIntentDecline(e.sessionId,e.nonce,{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:o.code??"provider_declined"})}catch{}return{status:"failed",error:new g(o.message??"PayPal payment failed","api_error",{code:o.code})}}return{status:"processing"}}async resumePayPalPayment(){if(!this.stripe||typeof window>"u")return null;let e=new URLSearchParams(window.location.search),t=e.get("payment_intent"),r=e.get("payment_intent_client_secret"),o=e.get("redirect_status");if(!t||!r)return null;if(o==="failed")return{status:"failed",error:new g("PayPal payment was declined. Please try again.","api_error")};let{paymentIntent:s,error:i}=await this.stripe.retrievePaymentIntent(r);if(i)return{status:"failed",error:new g(i.message??"Failed to retrieve PayPal payment","api_error")};if(s&&Zt(s.status)){let a=typeof s.payment_method=="string"?s.payment_method:s.payment_method?.id,l=new URL(window.location.href);return l.searchParams.delete("payment_intent"),l.searchParams.delete("payment_intent_client_secret"),l.searchParams.delete("redirect_status"),window.history.replaceState({},"",l.toString()),{status:s.status,paymentIntentId:s.id,paymentMethodId:a}}return{status:"failed",error:new g("PayPal payment was not completed. Please try again.","api_error")}}getRawProvider(){return this.stripe}createPayPalElements(e){if(!this.stripe)return null;let t={mode:"payment",amount:e.amount??0,currency:(e.currency??"usd").toLowerCase(),captureMethod:"manual"};return e.setupFutureUsage&&(t.setupFutureUsage=e.setupFutureUsage),e.appearance&&(t.appearance={theme:le(e.appearance.theme),variables:e.appearance.variables,rules:e.appearance.rules}),this.stripe.elements(t)}destroy(){this.elements=null,this.appliedAppearanceKey=null,this.appliedPaymentMethodTypesKey=null,this.appliedClientSecret=null,this.verifiedClientSecret=null,this.verifiedPaymentMethodTypesKey=null,this.stripe=null}};import{FloPayError as S,classifyTelemetryFailure as Me,resolveBillingApiUrl as at,SDK_VERSION as ur}from"@flopay/shared";import{FloPayError as nr}from"@flopay/shared";var W=class{constructor(e,t){this.elementMap=new Map;this.provider=e,this.baseOptions=t??{}}async create(e,t){let r={...this.baseOptions,...t};if(e==="payment"){let a=r.paymentMethodTypes?.map(l=>l.trim()).filter(l=>l&&l.toLowerCase()!=="card");if(!a?.length)throw new nr("At least one supported non-card payment method is required.","validation_error",{param:"paymentMethodTypes"});r.paymentMethodTypes=a}let o=this.provider.getElement(e);if(o)return this.elementMap.set(e,o),o;let s=this.elementMap.get(e);s&&s.destroy();let i=await this.provider.createElement(e,r);return this.elementMap.set(e,i),i}getElement(e){return this.elementMap.get(e)??null}async submit(){return{}}destroy(){for(let e of this.elementMap.values())e.destroy();this.elementMap.clear()}};import{buildTelemetryErrorEvent as or,buildTelemetryLogEvent as sr,buildTelemetryTerminalEvent as Ze,FloPayError as Je,resolveBillingApiUrl as Qe,SDK_VERSION as Xe}from"@flopay/shared";var be="flopay-vault",et={ready:["vault.widget.ready","vault_ready"],submitting:["vault.submission.started","vault_submit"],blocked:["operation.state_transition","vault_submit"],action_required:["vault.action.required","three_ds_handoff"]};function J(n){let e={class:n.class,stage:n.stage};"code"in n&&(e.code=n.code),"provider"in n&&n.provider&&(e.provider=n.provider),"paymentMethodCategory"in n&&n.paymentMethodCategory&&(e.paymentMethodCategory=n.paymentMethodCategory),"outcome"in n&&(e.outcome=n.outcome),"durationMs"in n&&n.durationMs!==void 0&&(e.durationMs=n.durationMs),"durationMode"in n&&n.durationMode&&(e.durationMode=n.durationMode);try{globalThis.Sentry?.addBreadcrumb?.({category:"flopay.telemetry",level:n.class==="technical_error"?"error":"info",message:n.class==="lifecycle"?n.name:n.class==="technical_error"?n.code:n.class==="expected_outcome"?n.outcome:"sdk.performance",data:e})}catch{}}function ce(n,e){return sr({eventId:"11111111-1111-4111-8111-111111111111",name:n,stage:e,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}function tt(n){return n?{errorCode:"VAULT_SUBMIT_FAILED",stage:"vault_submit",failureCategory:"provider_runtime"}:{errorCode:"VAULT_LOAD_FAILED",stage:"vault_mount",failureCategory:"provider_runtime"}}function rt(n,e,t="checkout"){return t==="card_setup"?n.type==="decline"?"card_setup_declined":"card_setup_succeeded":n.type==="decline"?"payment_declined":n.outcome==="authorized"||e==="manual"?"payment_authorized":"payment_succeeded"}function ir(n,e,t,r="checkout"){let{type:o}=n;if(o==="complete"||o==="decline")return Ze({eventId:"22222222-2222-4222-8222-222222222222",outcome:rt(n,t,r),sequence:0,provider:"pcivault",paymentMethodCategory:"card"});if(o==="error"){let a=tt(e);return or({eventId:"33333333-3333-4333-8333-333333333333",...a,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}let[s,i]=et[o];return ce(s,i)}function ar(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===be&&(e.type==="ready"||e.type==="submitting"||e.type==="blocked"||e.type==="complete"||e.type==="decline"||e.type==="error"||e.type==="action_required")}function lr(n){if(typeof n!="object"||n===null)return;let e=n,t=e.status;if(!(typeof e.id!="string"||e.id.trim()===""||typeof e.brand!="string"||e.brand.trim()===""||typeof e.lastFour!="string"||!/^\d{4}$/.test(e.lastFour)||typeof e.expiryMonth!="number"||!Number.isInteger(e.expiryMonth)||e.expiryMonth<1||e.expiryMonth>12||typeof e.expiryYear!="number"||!Number.isInteger(e.expiryYear)||e.expiryYear<1970||e.expiryYear>9999||t!=="pending"&&t!=="active"&&t!=="deleted"))return{id:e.id,brand:e.brand,lastFour:e.lastFour,expiryMonth:e.expiryMonth,expiryYear:e.expiryYear,status:t}}function cr(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===be&&e.type==="validation"&&Array.isArray(e.messages)}function dr(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===be&&e.type==="resize"&&typeof e.height=="number"&&Number.isFinite(e.height)}var z=class{constructor(e={},t){this.provider="pcivault";this.container=null;this.messageHandler=null;this.actionOverlay=null;this.threeDsReturnHandler=null;this.messageToken=null;this.expectedOrigin=null;this.theme=null;this.submitGateBlocked=!1;this.cardFieldOrder=null;this.cardAutoFocus=!0;this.mountStartedAt=0;this.vaultReadyReported=!1;this.submissionStarted=!1;this.submissionStartedAt=null;this.listeners=new Map;this.config=e,this.ownsTelemetryReporter=!t&&e.telemetry!==!1,this.telemetryReporter=t?.reporter??(this.ownsTelemetryReporter?new C({billingApiUrl:Qe(),sdkVersion:Xe}):void 0)}async mount(e,t){this.ownsTelemetryReporter&&!this.telemetryReporter&&(this.telemetryReporter=new C({billingApiUrl:Qe(),sdkVersion:Xe}));let r=this.telemetryReporter;if(this.config.operation==="card_setup"&&r&&this.setupTelemetryReporter!==r){this.setupTelemetryReporter=r;try{r.beginCheckout({checkoutMode:"setup"})}catch{}}if(this.mountStartedAt=this.telemetryReporter?.now?.()??_(),this.vaultReadyReported=!1,this.submissionStarted=!1,this.submissionStartedAt=null,typeof window>"u"||typeof document>"u")throw this.reportVaultLoadFailure(),new Je("The vault card form is only available in the browser.","api_error",{code:"card_capture_no_window"});if(!t?.html||!t.html.trim())throw this.reportVaultLoadFailure(),new Je("No vault capture widget HTML was provided to mount the secure card form.","api_error",{code:"card_capture_no_widget_html"});this.container=e,this.messageToken=t.messageToken??null,this.expectedOrigin=t.expectedOrigin??this.config.expectedOrigin??null,this.theme=t.theme??null;try{this.attachMessageListener(),this.injectWidget(e,t.html)}catch(o){throw this.reportVaultLoadFailure(),o}this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),J(ce("vault.widget.mounted","vault_mount")),this.telemetryReporter?.log({name:"vault.widget.mounted",stage:"vault_mount",provider:"pcivault",paymentMethodCategory:"card"}),this.emit("ready",{sessionId:this.config.sessionId})}reportVaultLoadFailure(){this.telemetryReporter?.error({errorCode:"VAULT_LOAD_FAILED",failureCategory:"provider_runtime",stage:"vault_mount",provider:"pcivault",paymentMethodCategory:"card"})}on(e,t){let r=this.listeners.get(e);return r||(r=new Set,this.listeners.set(e,r)),r.add(t),()=>{this.listeners.get(e)?.delete(t)}}unmount(){this.hideActionRequiredOverlay(),this.messageHandler&&(window.removeEventListener("message",this.messageHandler),this.messageHandler=null),this.container&&(this.container.replaceChildren(),this.container=null),this.messageToken=null,this.expectedOrigin=null,this.ownsTelemetryReporter&&(this.telemetryReporter?.destroy(),this.telemetryReporter=void 0)}injectWidget(e,t){e.innerHTML=t;let r=Array.from(e.querySelectorAll("script"));for(let o of r){let s=document.createElement("script");for(let i of Array.from(o.attributes))s.setAttribute(i.name,i.value);s.text=o.text,o.replaceWith(s)}}attachMessageListener(){if(this.messageHandler)return;let e=t=>{if(this.expectedOrigin&&t.origin!==this.expectedOrigin)return;let r=t.data;if(dr(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;this.applyHeight(r.height);return}if(cr(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;let l=r.messages.filter(c=>typeof c=="string"&&c.trim()).join(" ");this.emit("validation",{sessionId:this.config.sessionId,message:l||void 0});return}if(!ar(r)||this.messageToken&&r.messageToken!==this.messageToken)return;let o=this.config.sessionId,s=typeof r.sessionId=="string"?r.sessionId:void 0;if(o&&s&&s!==o||(r.type==="complete"||r.type==="decline")&&o&&s!==o)return;let i=lr(r.paymentMethod),a={...r.sessionId??this.config.sessionId?{sessionId:r.sessionId??this.config.sessionId}:{},...r.outcome?{outcome:r.outcome}:{},...r.paymentId?{paymentId:r.paymentId}:{},...r.authorizationExpiresAt?{authorizationExpiresAt:r.authorizationExpiresAt}:{},...r.failureOutcome?{failureOutcome:r.failureOutcome}:{},...r.intentId?{intentId:r.intentId}:{},...r.declineReason?{declineReason:r.declineReason}:{},...r.message?{message:r.message}:{},...i?{paymentMethod:i}:{}};r.type==="submitting"&&(this.submissionStarted=!0,this.submissionStartedAt=this.telemetryReporter?.now?.()??_()),J(ir(r,this.submissionStarted,this.config.captureMethod,this.config.operation)),this.reportOutcome(r),r.type==="ready"&&(this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder()),r.type==="action_required"&&r.nextActionRedirectUrl&&this.showActionRequiredOverlay(r.nextActionRedirectUrl),(r.type==="complete"||r.type==="decline"||r.type==="error"||r.type==="submitting")&&this.hideActionRequiredOverlay(),r.type!=="action_required"&&this.emit(r.type,a)};this.messageHandler=e,window.addEventListener("message",e)}reportOutcome(e){let t=this.telemetryReporter;if(!t)return;let{type:r}=e;if(r==="ready"&&!this.vaultReadyReported&&(this.vaultReadyReported=!0,t.performance({stage:"vault_ready",durationMs:Math.max(0,t.now()-this.mountStartedAt),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card"})),r==="complete"||r==="decline"){t.log({name:"vault.terminal",stage:"completion",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:rt(e,this.config.captureMethod,this.config.operation),provider:"pcivault",paymentMethodCategory:"card"});return}if(r==="error"){let i=tt(this.submissionStarted);t.log({name:"vault.terminal",stage:i.stage,provider:"pcivault",paymentMethodCategory:"card"}),t.error({...i,provider:"pcivault",paymentMethodCategory:"card"});return}if(r==="action_required"){t.log({name:"vault.action.required",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"}),t.log({name:"vault.three_ds.handoff",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"});let i=this.submissionStartedAt;this.submissionStartedAt=null,i!==null&&t.performance({stage:"three_ds_handoff",durationMs:Math.max(0,t.now()-i),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:"action_required",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"});return}let[o,s]=et[r];t.log({name:o,stage:s,provider:"pcivault",paymentMethodCategory:"card"})}applyTheme(e){this.theme=e,this.postTheme()}postTheme(){if(!this.theme||!this.container)return;let t=this.container.querySelector("iframe")?.contentWindow;if(t)try{t.postMessage({source:"flopay-vault-host",type:"theme",theme:this.theme},"*")}catch{}}setSubmitGate(e){this.submitGateBlocked=e,this.postSubmitGate()}postSubmitGate(){if(!this.container)return;let t=this.container.querySelector("iframe")?.contentWindow;if(t)try{t.postMessage({source:"flopay-vault-host",type:"gate",blocked:this.submitGateBlocked},"*")}catch{}}setCardFieldOrder(e,t){this.cardFieldOrder=e,this.cardAutoFocus=t,this.postCardFieldOrder()}postCardFieldOrder(){if(!this.container)return;let t=this.container.querySelector("iframe")?.contentWindow;if(t)try{t.postMessage({source:"flopay-vault-host",type:"fieldOrder",order:this.cardFieldOrder,autoFocus:this.cardAutoFocus},"*")}catch{}}emit(e,t){for(let r of this.listeners.get(e)??[])r(t)}showActionRequiredOverlay(e){if(typeof document>"u")return;if(this.actionOverlay){let i=this.actionOverlay.querySelector("iframe");i instanceof HTMLIFrameElement&&(i.src=e);return}let t=document.createElement("div");t.setAttribute("data-flopay-action-required","1"),t.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let r=document.createElement("iframe");r.setAttribute("title","Card authentication"),r.setAttribute("allow","payment"),r.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";"),r.src=e,t.appendChild(r);let o=document.createElement("button");o.type="button",o.setAttribute("aria-label","Close card authentication"),o.textContent="\xD7",o.style.cssText=["position:fixed","top:20px","right:20px","width:40px","height:40px","border:0","border-radius:9999px","background:#fff","color:#0f172a","font-size:28px","line-height:40px","cursor:pointer","box-shadow:0 4px 14px rgba(0,0,0,0.25)"].join(";"),o.addEventListener("click",()=>this.abandonActionRequiredOverlay()),t.appendChild(o),t.addEventListener("click",i=>{i.target===t&&this.abandonActionRequiredOverlay()});let s=i=>{if(i.source!==r.contentWindow)return;let a=i.data;if(!a||typeof a!="object")return;let l=a;l.source==="flopay-vault-3ds-return"&&(J(ce("vault.three_ds.returned","three_ds_return")),this.telemetryReporter?.log({name:"vault.three_ds.returned",stage:"three_ds_return",provider:"pcivault",paymentMethodCategory:"card"}),this.hideActionRequiredOverlay(),this.postActionCompleted(l.status))};window.addEventListener("message",s),this.threeDsReturnHandler=s,document.body.appendChild(t),this.actionOverlay=t,J(ce("vault.three_ds.handoff","three_ds_handoff"))}postActionCompleted(e){if(!this.container)return;let r=this.container.querySelector("iframe")?.contentWindow;if(r)try{r.postMessage({source:"flopay-vault-host",type:"action_completed",status:typeof e=="string"?e:"unknown"},"*")}catch{}}abandonActionRequiredOverlay(){if(!this.actionOverlay)return;let e=Ze({eventId:"77777777-7777-4777-8777-777777777777",outcome:"customer_abandoned",stage:"three_ds_handoff",sequence:0,provider:"pcivault",paymentMethodCategory:"card"});J(e),this.telemetryReporter?.terminal({outcome:"customer_abandoned",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"}),this.hideActionRequiredOverlay(),this.postActionCompleted("abandoned")}hideActionRequiredOverlay(){this.threeDsReturnHandler&&(window.removeEventListener("message",this.threeDsReturnHandler),this.threeDsReturnHandler=null),this.actionOverlay&&(this.actionOverlay.parentNode?.removeChild(this.actionOverlay),this.actionOverlay=null)}applyHeight(e){let t=this.container?.querySelector("iframe");if(!t)return;let r=Math.max(0,Math.min(Math.ceil(e),2e3));t.style.height=`${r}px`}};function nt(n,e){let t=z;return new t(n,{reporter:e})}var ot=Symbol.for("@flopay/js.telemetry.bridge.v1");function st(n,e,t){let r=()=>e?.now()??t();Object.defineProperty(n,ot,{configurable:!1,enumerable:!1,writable:!1,value:{error:s=>e?.error(s),log:s=>e?.log(s),performance:s=>e?.performance(s),terminal:s=>e?.terminal(s),now:r,elapsed:s=>Math.max(0,r()-s),setCheckoutContext:s=>e?.setCheckoutContext(s),beginCheckout:(s={})=>e?.beginCheckout(s)??r(),disable:()=>e?.disable()}})}function it(n){return n[ot]}function B(n){if(!n)return!1;let e=n.code?.toLowerCase()??"";return!!n.declineCode||e.includes("declin")}function pr(n){return n==="stripe"||n==="paypal"||n==="pcivault"?n:"other"}var de=class{constructor(e,t,r){this.currentElements=null;this.provider=e,this.config=t,this.telemetryReporter=r??new C({billingApiUrl:at(t.billingApiUrl),sdkVersion:ur,enabled:t.telemetry!==!1}),st(this,this.telemetryReporter,_)}now(){return this.telemetryReporter?.now?.()??_()}elements(e){return this.currentElements&&this.currentElements.destroy(),this.currentElements=new W(this.provider,{appearance:this.config.appearance,...e}),this.currentElements}async submitElements(){return this.provider.submitElements()}cardCapture(e){return this.telemetryReporter?.log({name:"vault.capture.requested",stage:"vault_request",provider:"pcivault",paymentMethodCategory:"card"}),this.telemetryReporter?nt({sessionId:e?.sessionId,captureMethod:e?.captureMethod},this.telemetryReporter):new z({sessionId:e?.sessionId,captureMethod:e?.captureMethod,telemetry:!1})}async confirmPayPalPayment(e){let t=this.now();this.telemetryReporter?.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),this.telemetryReporter?.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});try{let r=await this.provider.confirmPayPalPayment(e);return this.telemetryReporter?.performance({stage:"processing",durationMs:this.now()-t,durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),r.error||this.telemetryReporter?.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),r.status==="requires_action"?(this.telemetryReporter?.log({name:"provider.redirect.started",stage:"redirect",provider:"paypal",paymentMethodCategory:"paypal"}),this.telemetryReporter?.terminal({outcome:"action_required",stage:"redirect",provider:"paypal",paymentMethodCategory:"paypal"})):r.status==="succeeded"?this.telemetryReporter?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}):r.status!=="processing"&&(B(r.error)?this.telemetryReporter?.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):r.error?.type==="validation_error"?this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal"}):r.error&&this.telemetryReporter?.error({errorCode:"PAYMENT_PROCESSING_FAILED",failureCategory:"provider_runtime",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"})),r}catch(r){if(this.telemetryReporter?.performance({stage:"processing",durationMs:this.now()-t,durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),r instanceof S&&B(r))this.telemetryReporter?.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"});else if(r instanceof S&&r.type==="validation_error")this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal"});else{let o=Me(r,"PAYMENT_PROCESSING_FAILED","unknown");this.telemetryReporter?.error({...o,failureCategory:o.failureCategory??"provider_runtime",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"})}throw r}}async resumePayPalPayment(){let e=this.now();try{let t=await this.provider.resumePayPalPayment();return t===null?null:(this.telemetryReporter?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),this.telemetryReporter?.performance({stage:"redirect_resume",durationMs:this.now()-e,durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),t.status==="succeeded"?this.telemetryReporter?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}):B(t.error)?this.telemetryReporter?.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):t.error?.type==="validation_error"?this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal"}):t.error&&this.telemetryReporter?.error({errorCode:"REDIRECT_RESUME_FAILED",failureCategory:"provider_runtime",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),t)}catch(t){if(this.telemetryReporter?.performance({stage:"redirect_resume",durationMs:this.now()-e,durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),t instanceof S&&B(t))this.telemetryReporter?.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"});else if(t instanceof S&&t.type==="validation_error")this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal"});else{let r=Me(t,"REDIRECT_RESUME_FAILED","unknown");this.telemetryReporter?.error({...r,failureCategory:r.failureCategory??"provider_runtime",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"})}throw t}}async confirmPayment(e){if(e.paymentMethodCategory!=="wallet"&&e.paymentMethodCategory!=="apm"||!e.paymentMethodType?.trim()||e.paymentMethodType.trim().toLowerCase()==="card")throw new S("A supported non-card payment method is required.","validation_error",{param:"paymentMethodType"});let t=this.now(),r=pr(this.provider.name);this.telemetryReporter?.log({name:"payment.processing.started",stage:"processing",provider:r,paymentMethodCategory:e.paymentMethodCategory});try{let o=await this.provider.confirmPayment(e),s=this.now()-t;return this.telemetryReporter?.performance({stage:"processing",durationMs:s,durationMode:"machine",provider:r,paymentMethodCategory:e.paymentMethodCategory}),o.status==="succeeded"?this.telemetryReporter?.terminal({outcome:"payment_succeeded",provider:r,paymentMethodCategory:e.paymentMethodCategory}):B(o.error)?this.telemetryReporter?.terminal({outcome:"payment_declined",provider:r,paymentMethodCategory:e.paymentMethodCategory}):o.error?.type==="validation_error"?this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:r,paymentMethodCategory:e.paymentMethodCategory}):o.status==="requires_action"?this.telemetryReporter?.terminal({outcome:"action_required",stage:"three_ds_handoff",provider:r,paymentMethodCategory:e.paymentMethodCategory}):o.status==="failed"&&o.error&&this.telemetryReporter?.error({errorCode:"PAYMENT_PROCESSING_FAILED",failureCategory:"provider_runtime",stage:"processing",provider:r,paymentMethodCategory:e.paymentMethodCategory}),o.status==="succeeded"||o.status==="failed"?this.telemetryReporter?.log({name:"payment.processing.completed",stage:"processing",provider:r,paymentMethodCategory:e.paymentMethodCategory}):this.telemetryReporter?.log({name:"operation.state_transition",stage:o.status==="requires_action"?"three_ds_handoff":"processing",provider:r,paymentMethodCategory:e.paymentMethodCategory}),o}catch(o){throw this.telemetryReporter?.performance({stage:"processing",durationMs:this.now()-t,durationMode:"machine",provider:r,paymentMethodCategory:e.paymentMethodCategory}),o instanceof S&&B(o)?this.telemetryReporter?.terminal({outcome:"payment_declined",provider:r,paymentMethodCategory:e.paymentMethodCategory}):o instanceof S&&o.type==="validation_error"?this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:r,paymentMethodCategory:e.paymentMethodCategory}):this.telemetryReporter?.error({errorCode:"PAYMENT_PROCESSING_FAILED",failureCategory:"provider_runtime",stage:"processing",provider:r,paymentMethodCategory:e.paymentMethodCategory}),o}}async retrieveSession(e,t){if(!e)throw new S("sessionId is required to retrieve a session.","validation_error",{param:"sessionId"});let r=await this.retrieveUnifiedSession(e,t);if(!r.data.session)throw new S("Session not found","api_error");return r.data.session}async retrieveUnifiedSession(e,t){if(!e)throw new S("sessionId is required.","validation_error",{param:"sessionId"});let r=at(t??this.config.billingApiUrl),o=this.now();this.telemetryReporter?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let s,i=Ge(r,{now:()=>this.telemetryReporter?.now()??_(),onFirstByte:a=>{s=a},onRetry:(a,l)=>{this.telemetryReporter?.log({name:"operation.retry",stage:a==="session_read"?"session_read":"processing",requestCategory:a,attempt:l})}});try{let a=await i.getUnifiedCheckoutSession(e);return s!==void 0&&(this.telemetryReporter?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:"2xx"}),this.telemetryReporter?.performance({stage:"session_first_byte",durationMs:s,durationMode:"machine",requestCategory:"session_read",statusClass:"2xx"})),this.telemetryReporter?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:"2xx"}),this.telemetryReporter?.log({name:"checkout.data.ready",stage:"checkout_data_ready"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-o,durationMode:"machine",requestCategory:"session_read",statusClass:"2xx"}),a}catch(a){let l=Me(a,a instanceof S&&a.code==="checkout_processing_timeout"?"REQUEST_TIMEOUT":"NETWORK_REQUEST_FAILED");throw this.telemetryReporter?.error({...l,stage:"session_read",provider:"flo",paymentMethodCategory:"unknown"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-o,durationMode:"machine",requestCategory:"session_read",statusClass:l.statusClass}),a}}getRawProvider(){return this.provider.getRawProvider()}destroy(){this.telemetryReporter?.log({name:"checkout.unmount",stage:"unmount"}),this.telemetryReporter?.destroy(),this.currentElements?.destroy(),this.currentElements=null,this.provider.destroy()}};function lt(n,e,t){let r=de;return new r(n,e,t)}var dt=new Map;function Pe(n){return Array.isArray(n)?n.map(Pe):n&&typeof n=="object"?Object.fromEntries(Object.entries(n).filter(([,e])=>e!==void 0).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,Pe(t)])):n}function yr(n,e){return JSON.stringify([n,ke(e?.billingApiUrl),e?.telemetry!==!1,e?.locale??"auto",e?.apiVersion??null,Pe(e?.appearance??null)])}var ue=new Map;async function hr(n,e){if(!n){let a=new C({billingApiUrl:ke(e?.billingApiUrl),sdkVersion:ct,enabled:e?.telemetry!==!1});throw a.error({errorCode:"CONFIGURATION_INVALID",stage:"sdk_initialize",paymentMethodCategory:"unknown"}),a.flush().catch(()=>{}).finally(()=>a.destroy()),new mr("A publishable key is required to initialize FloPay.","validation_error",{param:"publishableKey"})}let t=yr(n,e),r=dt.get(t);if(r)return e?.telemetry!==!1&&it(r)?.log({name:"sdk.cache.hit",stage:"sdk_initialize"}),r;let o=ue.get(t);if(o)return o;let s={...e,publishableKey:n},i=(async()=>{let a=new C({billingApiUrl:ke(s.billingApiUrl),sdkVersion:ct,enabled:s.telemetry!==!1}),l=a.now();a.log({name:"sdk.initialize.started",stage:"sdk_initialize"}),a.log({name:"sdk.cache.miss",stage:"sdk_initialize"}),a.log({name:"provider.load.started",stage:"provider_load",provider:"stripe"});let c=new Y,d=a.now();try{await c.initialize(s)}catch(p){throw a.error({errorCode:"SDK_INITIALIZATION_FAILED",failureCategory:"provider_runtime",stage:"sdk_initialize",provider:"stripe",paymentMethodCategory:"unknown"}),a.destroy(),p}let m=a.now();a.log({name:"provider.ready",stage:"provider_ready",provider:"stripe"}),a.log({name:"provider.availability.checked",stage:"provider_ready",provider:"stripe"}),a.log({name:"sdk.initialize.ready",stage:"sdk_initialize"}),a.performance({stage:"sdk_initialize",durationMs:m-l,durationMode:"machine",provider:"stripe"}),a.performance({stage:"provider_ready",durationMs:m-d,durationMode:"machine",provider:"stripe"});let u=lt(c,s,a);return dt.set(t,u),u})();ue.set(t,i);try{return await i}finally{ue.get(t)===i&&ue.delete(t)}}import{FloPayError as K,IDEMPOTENCY_IN_PROGRESS_CODE as gr,IDEMPOTENCY_KEY_HEADER as fr,SDK_VERSION as ut,assertCaptureMethodEligible as Cr,buildProductPayload as vr,classifyTelemetryFailure as Tr,foldIntoProducts as _r,resolveIdempotencyKey as pt,resolveSessionCurrency as wr,telemetryStatusClass as mt}from"@flopay/shared";var Ee=5,yt=new WeakSet;function Sr(n){(typeof n=="object"&&n!==null||typeof n=="function")&&yt.add(n)}function br(n){return(typeof n=="object"&&n!==null||typeof n=="function")&&yt.has(n)}function Mr(n,e){let t=e?.error,r=E(e?.code)??E(t?.code)??`http_${n}`,o=E(e?.message)??E(t?.message)??kr(r,n);return new K(o,"api_error",{code:r,statusCode:n})}function kr(n,e){switch(n){case"CouponLimitExceeded":return`Too many coupon codes \u2014 a checkout session accepts at most ${Ee}.`;case"CouponCurrencyUnsupported":return"One of the applied coupons has no price configured for the cart currency.";default:return`Failed to create checkout session (HTTP ${e}).`}}async function ht(n,e,t){let{billingApiUrl:r,checkoutBaseUrl:o,items:s=[],subscriptions:i=[],products:a,account:l,successUrl:c,cancelUrl:d,checkoutMode:m="confirm",captureMethod:u,couponCodes:p=[],tagsData:w,redirectParams:v={},setCookie:T=!0,clientId:Re,currency:H,utmMetadata:y,idempotencyKey:Q}=n,X=pt(Q);if(p.length>Ee)throw new K(`Too many coupon codes \u2014 a checkout session accepts at most ${Ee}.`,"validation_error",{code:"CouponLimitExceeded",param:"couponCodes"});let P=a??_r(s,i);Cr({captureMethod:u,products:P});let M=wr(H,s,i,P);if(!M)throw new K("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});let F={clientId:Re,checkoutVersion:ut,successUrl:c,cancelUrl:d,currency:M,checkoutMode:m,products:P.map(k=>vr(k,M)),accountData:{userId:l.userId,firstName:l.firstName??null,lastName:l.lastName??null,email:l.email,country:l.country??null,gender:l.gender??null,city:l.city??null,state:l.state??null,zip:l.zip??null,addressLine1:l.addressLine1??null,addressLine2:l.addressLine2??null},couponCodes:p};u==="manual"&&(F.captureMethod=u),w&&(F.tagsData=w),y?.length&&(F.utmMetadata=y);let $=`${r.replace(/\/+$/,"")}/v1/checkouts/sessions`,Z={"Content-Type":"application/json"};X&&(Z[fr]=X);let O,ee,vt={method:"POST",headers:Z,body:JSON.stringify(F),signal:e},te;try{te=await fetch($,vt)}catch(k){throw Sr(k),k}try{t?.(te.status)}catch{}O=te.status;try{ee=await te.json()}catch{}if(O>=400)throw Mr(O,ee);if(O===201){let k=ee?.data?.uuid,me=ee?.data?.nonce;if(!k)throw new Error("Checkout session created but no UUID was returned by the billing API");if(!me)throw new K("Checkout session created but no `nonce` was returned by the billing API. Upgrade the billing service to TeamFloPay/backend#640 or later.","api_error",{code:"MissingCheckoutSessionToken"});(P.length||M)&&q(k,{currency:M,products:P.map(f=>({code:f.code??f.providerItemId??f.providerPlanId,type:f.type,name:f.name??f.itemName??f.providerItemName??f.subscriptionName??f.providerPlanName??null,totalAmount:f.totalAmount,overrideAmount:f.overrideAmount,currency:f.currency??M}))});let re=new URL(`${o.replace(/\/+$/,"")}/secure`);re.searchParams.set("id",k);for(let[f,ne]of Object.entries(v))re.searchParams.set(f,ne);if(T&&typeof window<"u"&&typeof document<"u"){let f=JSON.stringify({origin_url:d}),ne=window.location.hostname.split(".").slice(-2).join(".");document.cookie=`checkout_data=${encodeURIComponent(f)}; domain=.${ne}; path=/; max-age=3600; SameSite=Lax; Secure;`,document.cookie=`flopay_checkout_token=${encodeURIComponent(me)}; domain=.${ne}; path=/; max-age=3600; SameSite=Lax; Secure;`}return typeof window<"u"&&(window.location.href=re.toString()),{status:201,redirectUrl:re.toString(),nonce:me}}return O===204?(typeof window<"u"&&(window.location.href=c),{status:204}):{status:O}}async function Pr(n){let e=ft(n),t=gt(e),r=R(n.timeoutMs);try{let o=await ht(n,r.signal,t);return Ct(e,o),o}catch(o){throw pe(e,o),o}finally{r.clear(),j(e.reporter)}}function gt(n){let e=!1;return t=>{if(e)return;e=!0;let r=mt(t);n.reporter.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:r,attempt:n.attempt}),n.reporter.performance({stage:"session_first_byte",durationMs:n.reporter.now()-n.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:r,attempt:n.attempt})}}function ft(n){let e=new C({billingApiUrl:n.billingApiUrl,sdkVersion:ut,enabled:n.telemetry!==!1}),t=e.now();return e.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"}),{reporter:e,startedAt:t,attempt:0}}function Ct(n,e){let t=mt(e.status);n.reporter.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:t}),n.reporter.performance({stage:"session_create",durationMs:n.reporter.now()-n.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:t,attempt:n.attempt})}function pe(n,e){let{reporter:t}=n,r=Tr(e,"CHECKOUT_SESSION_CREATE_FAILED");if(t.performance({stage:"session_create",durationMs:t.now()-n.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:r.statusClass,attempt:n.attempt}),e instanceof K&&e.type==="validation_error"){t.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"});return}if(r.statusClass==="4xx"){t.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create",statusClass:"4xx"});return}t.error({...r,stage:"session_create",requestCategory:"session_create"})}function j(n){n.flush().catch(()=>{}).finally(()=>n.destroy())}async function Er(n){let{maxRetries:e=2,...t}=n,r=ft(n),o=gt(r);if(!Number.isFinite(e)||!Number.isInteger(e)||e<0||e>=3)throw r.reporter.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),j(r.reporter),new Error(`Number of retries must be an integer between 0 and ${2}`);let s={...t,idempotencyKey:pt(t.idempotencyKey)},i=R(t.timeoutMs),a;for(let l=0;l<=e;l++){r.attempt=l;try{let c=await ht(s,i.signal,o);return Ct(r,c),i.clear(),j(r.reporter),c}catch(c){a=c;let d=c instanceof Error&&c.name==="AbortError",m=br(c),u=c instanceof K&&c.code===gr;if((d||m||u)&&!i.signal.aborted&&l<e){r.reporter.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:l+1});try{await L(l,i.signal)}catch(p){throw pe(r,p),i.clear(),j(r.reporter),p}continue}throw pe(r,c),i.clear(),j(r.reporter),c}}throw pe(r,a),i.clear(),j(r.reporter),a??new Error("Unknown error during checkout session creation")}import{dropThirdPartyOnlyError as En}from"@flopay/shared";export{de as FloPay,W as FloPayElements,D as PaymentAPI,z as PciVaultCardCapture,Ke as SESSION_CREATE_TELEMETRY,Y as StripeAdapter,q as cacheSessionDisplayData,ge as clearSessionDisplayData,Pr as createCheckoutSession,Er as createCheckoutSessionWithRetries,En as dropThirdPartyOnlyError,he as getSessionDisplayData,hr as loadFloPay,tr as toStripeAppearance,le as toStripeAppearanceTheme};
1
+ import{a as E,b as K,c as Re,d as Te,e as x,f as g,g as j,h as Z,i as ke,j as O,k as ee,l as z,m as te}from"./chunk-G6M32WZN.mjs";import{FloPayError as qe,resolveBillingApiUrl as $,SDK_VERSION as de}from"@flopay/shared";import{loadStripe as be}from"@stripe/stripe-js";import{FloPayError as p,isMoneySettledOutcome as Ae,isSetupIntentClientSecret as Ie}from"@flopay/shared";function re(r){return{payment:"payment",address:"address"}[r]}function U(r){switch(r){case"night":return"night";case"flat":return"flat";default:return"stripe"}}function Fe(r){return{...r,theme:U(r.theme)}}function B(r){return r?JSON.stringify(r.map(e=>e.trim().toLowerCase())):null}function ne(r){let e=r;return{mount(n){e.mount(n)},unmount(){e.unmount()},update(n){e.update(n)},on(n,t){e.on?.(n,t)},off(n,t){e.off?.(n,t)},destroy(){e.destroy()}}}function xe(r){return{billing_details:{...r.email?{email:r.email}:{},...r.name?{name:r.name}:{},...r.address?{address:{...r.address.country?{country:r.address.country}:{},...r.address.postal_code?{postal_code:r.address.postal_code}:{},...r.address.city?{city:r.address.city}:{},...r.address.line1?{line1:r.address.line1}:{},...r.address.line2?{line2:r.address.line2}:{},...r.address.state?{state:r.address.state}:{}}}:{}}}}var R=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 n=await be(e.publishableKey,{locale:e.locale??"auto"});if(!n)throw new p("Failed to initialize Stripe. Check your publishable key.","authentication_error");this.stripe=n}getElements(e){if(!this.stripe)throw new p("StripeAdapter not initialized. Call initialize() first.","api_error");let n=e?.appearance?{theme:U(e.appearance.theme),variables:e.appearance.variables,rules:e.appearance.rules}:void 0,t=n?JSON.stringify(n):null,a=B(e?.paymentMethodTypes),o=e?.clientSecret??null;if(this.elements&&a&&(a!==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)t!==this.appliedAppearanceKey&&(this.elements.update({appearance:n??{}}),this.appliedAppearanceKey=t);else{let l,s=e?.amount??0,i=(e?.currency??"usd").toLowerCase(),d=e?.paymentMethodCreation??"manual";e?.clientSecret?l={clientSecret:e.clientSecret}:s>0?(l={mode:"payment",amount:s,currency:i,paymentMethodCreation:d},e?.setupFutureUsage&&(l.setupFutureUsage=e.setupFutureUsage)):l={mode:"setup",currency:i,paymentMethodCreation:d},!e?.clientSecret&&e?.paymentMethodTypes&&(l.paymentMethodTypes=e.paymentMethodTypes),n&&(l.appearance=n),this.elements=this.stripe.elements(l),this.appliedAppearanceKey=t,this.appliedPaymentMethodTypesKey=a,this.appliedClientSecret=o,this.verifiedClientSecret=null,this.verifiedPaymentMethodTypesKey=null}return this.elements}async assertClientSecretPaymentMethods(e,n){if(!this.stripe)throw new p("StripeAdapter not initialized. Call initialize() first.","api_error");let t,a=!1;if(Ie(e)){let{setupIntent:i,error:d}=await this.stripe.retrieveSetupIntent(e);t=i,a=!!d}else{let{paymentIntent:i,error:d}=await this.stripe.retrievePaymentIntent(e);t=i,a=!!d}let o=t?.payment_method_types;if(a||!Array.isArray(o))throw new p("Unable to verify the payment methods configured for this client secret.","api_error",{param:"clientSecret"});let l=new Set(n.map(i=>i.toLowerCase()));if(o.some(i=>typeof i!="string"||!l.has(i.trim().toLowerCase()))||o.length===0)throw new p("The client-secret intent must enable only declared non-card payment methods.","validation_error",{param:"clientSecret"})}async createElement(e,n){let t=n;if(e==="payment"){let i=n.paymentMethodTypes?.map(d=>d.trim()).filter(d=>d&&d.toLowerCase()!=="card");if(!i?.length)throw new p("At least one supported non-card payment method is required.","validation_error",{param:"paymentMethodTypes"});if(t={...n,paymentMethodTypes:i},t.clientSecret){let d=B(i);this.elements&&this.appliedClientSecret===t.clientSecret&&this.appliedPaymentMethodTypesKey===d&&this.verifiedClientSecret===t.clientSecret&&this.verifiedPaymentMethodTypesKey===d||await this.assertClientSecretPaymentMethods(t.clientSecret,i)}}let a=this.getElements(t);e==="payment"&&t.clientSecret&&(this.verifiedClientSecret=t.clientSecret,this.verifiedPaymentMethodTypesKey=B(t.paymentMethodTypes));let o=re(e),l={};t.layout&&(l.layout=t.layout),t.defaultValues&&(l.defaultValues=t.defaultValues),t.readOnly&&(l.readOnly=t.readOnly),t.mode&&(l.mode=t.mode);let s=a.create(o,l);return ne(s)}getElement(e){if(!this.elements)return null;let n=re(e),t=this.elements.getElement(n);return t?ne(t):null}async submitElements(){if(!this.stripe||!this.elements)return{error:new p("Stripe not initialized","api_error")};let{error:e}=await this.elements.submit();return e?{error:new p(e.message??"Validation failed","validation_error")}:{}}async confirmPayment(e){if(!this.stripe||!this.elements)throw new p("StripeAdapter not initialized or no elements created.","api_error");let n=e.billingDetails,t=n?xe(n):void 0,{error:a,paymentIntent:o}=await this.stripe.confirmPayment({elements:this.elements,clientSecret:e.clientSecret,confirmParams:{return_url:e.returnUrl??window.location.href,...t?{payment_method_data:t}:{}},redirect:"if_required"});return a?{status:"failed",error:new p(a.message??"Payment failed","api_error",{code:a.code,declineCode:a.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 p("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 p("Stripe not initialized","api_error")};let n=e.billingApiUrl.replace(/\/+$/,"");if(this.elements){let{error:o}=await this.elements.submit();if(o)return{status:"failed",error:new p(o.message??"PayPal payment failed","validation_error",{code:o.code})}}let t;try{let o=await new O(n).createSessionIntent(e.sessionId,e.nonce??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"});if(o.provider!=="stripe")throw new p("Invalid provider returned for PayPal intent","api_error");t=o.clientSecret}catch(o){return{status:"failed",error:o instanceof p?o:new p("Failed to create PayPal payment intent","api_error")}}let{error:a}=await this.stripe.confirmPayment({clientSecret:t,elements:this.elements??void 0,confirmParams:{return_url:e.returnUrl}});if(a){if(e.nonce)try{await new O(n).reportSessionIntentDecline(e.sessionId,e.nonce,{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:a.code??"provider_declined"})}catch{}return{status:"failed",error:new p(a.message??"PayPal payment failed","api_error",{code:a.code})}}return{status:"processing"}}async resumePayPalPayment(){if(!this.stripe||typeof window>"u")return null;let e=new URLSearchParams(window.location.search),n=e.get("payment_intent"),t=e.get("payment_intent_client_secret"),a=e.get("redirect_status");if(!n||!t)return null;if(a==="failed")return{status:"failed",error:new p("PayPal payment was declined. Please try again.","api_error")};let{paymentIntent:o,error:l}=await this.stripe.retrievePaymentIntent(t);if(l)return{status:"failed",error:new p(l.message??"Failed to retrieve PayPal payment","api_error")};if(o&&Ae(o.status)){let s=typeof o.payment_method=="string"?o.payment_method:o.payment_method?.id,i=new URL(window.location.href);return i.searchParams.delete("payment_intent"),i.searchParams.delete("payment_intent_client_secret"),i.searchParams.delete("redirect_status"),window.history.replaceState({},"",i.toString()),{status:o.status,paymentIntentId:o.id,paymentMethodId:s}}return{status:"failed",error:new p("PayPal payment was not completed. Please try again.","api_error")}}getRawProvider(){return this.stripe}createPayPalElements(e){if(!this.stripe)return null;let n={mode:"payment",amount:e.amount??0,currency:(e.currency??"usd").toLowerCase(),captureMethod:"manual"};return e.setupFutureUsage&&(n.setupFutureUsage=e.setupFutureUsage),e.appearance&&(n.appearance={theme:U(e.appearance.theme),variables:e.appearance.variables,rules:e.appearance.rules}),this.stripe.elements(n)}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 m,classifyTelemetryFailure as V,resolveBillingApiUrl as se,SDK_VERSION as Ue}from"@flopay/shared";import{FloPayError as Oe}from"@flopay/shared";var T=class{constructor(e,n){this.elementMap=new Map;this.provider=e,this.baseOptions=n??{}}async create(e,n){let t={...this.baseOptions,...n};if(e==="payment"){let s=t.paymentMethodTypes?.map(i=>i.trim()).filter(i=>i&&i.toLowerCase()!=="card");if(!s?.length)throw new Oe("At least one supported non-card payment method is required.","validation_error",{param:"paymentMethodTypes"});t.paymentMethodTypes=s}let a=this.provider.getElement(e);if(a)return this.elementMap.set(e,a),a;let o=this.elementMap.get(e);o&&o.destroy();let l=await this.provider.createElement(e,t);return this.elementMap.set(e,l),l}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 ae=Symbol.for("@flopay/js.telemetry.bridge.v1");function oe(r,e,n){let t=()=>e?.now()??n();Object.defineProperty(r,ae,{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:t,elapsed:o=>Math.max(0,t()-o),setCheckoutContext:o=>e?.setCheckoutContext(o),beginCheckout:(o={})=>e?.beginCheckout(o)??t(),disable:()=>e?.disable()}})}function ie(r){return r[ae]}function v(r){if(!r)return!1;let e=r.code?.toLowerCase()??"";return!!r.declineCode||e.includes("declin")}function De(r){return r==="stripe"||r==="paypal"||r==="pcivault"?r:"other"}var D=class{constructor(e,n,t){this.currentElements=null;this.provider=e,this.config=n,this.telemetryReporter=t??new g({billingApiUrl:se(n.billingApiUrl),sdkVersion:Ue,enabled:n.telemetry!==!1}),oe(this,this.telemetryReporter,x)}now(){return this.telemetryReporter?.now?.()??x()}elements(e){return this.currentElements&&this.currentElements.destroy(),this.currentElements=new T(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?te({sessionId:e?.sessionId,captureMethod:e?.captureMethod},this.telemetryReporter):new z({sessionId:e?.sessionId,captureMethod:e?.captureMethod,telemetry:!1})}async confirmPayPalPayment(e){let n=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 t=await this.provider.confirmPayPalPayment(e);return this.telemetryReporter?.performance({stage:"processing",durationMs:this.now()-n,durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),t.error||this.telemetryReporter?.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),t.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"})):t.status==="succeeded"?this.telemetryReporter?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}):t.status!=="processing"&&(v(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:"PAYMENT_PROCESSING_FAILED",failureCategory:"provider_runtime",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"})),t}catch(t){if(this.telemetryReporter?.performance({stage:"processing",durationMs:this.now()-n,durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),t instanceof m&&v(t))this.telemetryReporter?.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"});else if(t instanceof m&&t.type==="validation_error")this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal"});else{let a=V(t,"PAYMENT_PROCESSING_FAILED","unknown");this.telemetryReporter?.error({...a,failureCategory:a.failureCategory??"provider_runtime",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"})}throw t}}async resumePayPalPayment(){let e=this.now();try{let n=await this.provider.resumePayPalPayment();return n===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"}),n.status==="succeeded"?this.telemetryReporter?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}):v(n.error)?this.telemetryReporter?.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):n.error?.type==="validation_error"?this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal"}):n.error&&this.telemetryReporter?.error({errorCode:"REDIRECT_RESUME_FAILED",failureCategory:"provider_runtime",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),n)}catch(n){if(this.telemetryReporter?.performance({stage:"redirect_resume",durationMs:this.now()-e,durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),n instanceof m&&v(n))this.telemetryReporter?.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"});else if(n instanceof m&&n.type==="validation_error")this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal"});else{let t=V(n,"REDIRECT_RESUME_FAILED","unknown");this.telemetryReporter?.error({...t,failureCategory:t.failureCategory??"provider_runtime",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"})}throw n}}async confirmPayment(e){if(e.paymentMethodCategory!=="wallet"&&e.paymentMethodCategory!=="apm"||!e.paymentMethodType?.trim()||e.paymentMethodType.trim().toLowerCase()==="card")throw new m("A supported non-card payment method is required.","validation_error",{param:"paymentMethodType"});let n=this.now(),t=De(this.provider.name);this.telemetryReporter?.log({name:"payment.processing.started",stage:"processing",provider:t,paymentMethodCategory:e.paymentMethodCategory});try{let a=await this.provider.confirmPayment(e),o=this.now()-n;return this.telemetryReporter?.performance({stage:"processing",durationMs:o,durationMode:"machine",provider:t,paymentMethodCategory:e.paymentMethodCategory}),a.status==="succeeded"?this.telemetryReporter?.terminal({outcome:"payment_succeeded",provider:t,paymentMethodCategory:e.paymentMethodCategory}):v(a.error)?this.telemetryReporter?.terminal({outcome:"payment_declined",provider:t,paymentMethodCategory:e.paymentMethodCategory}):a.error?.type==="validation_error"?this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:t,paymentMethodCategory:e.paymentMethodCategory}):a.status==="requires_action"?this.telemetryReporter?.terminal({outcome:"action_required",stage:"three_ds_handoff",provider:t,paymentMethodCategory:e.paymentMethodCategory}):a.status==="failed"&&a.error&&this.telemetryReporter?.error({errorCode:"PAYMENT_PROCESSING_FAILED",failureCategory:"provider_runtime",stage:"processing",provider:t,paymentMethodCategory:e.paymentMethodCategory}),a.status==="succeeded"||a.status==="failed"?this.telemetryReporter?.log({name:"payment.processing.completed",stage:"processing",provider:t,paymentMethodCategory:e.paymentMethodCategory}):this.telemetryReporter?.log({name:"operation.state_transition",stage:a.status==="requires_action"?"three_ds_handoff":"processing",provider:t,paymentMethodCategory:e.paymentMethodCategory}),a}catch(a){throw this.telemetryReporter?.performance({stage:"processing",durationMs:this.now()-n,durationMode:"machine",provider:t,paymentMethodCategory:e.paymentMethodCategory}),a instanceof m&&v(a)?this.telemetryReporter?.terminal({outcome:"payment_declined",provider:t,paymentMethodCategory:e.paymentMethodCategory}):a instanceof m&&a.type==="validation_error"?this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:t,paymentMethodCategory:e.paymentMethodCategory}):this.telemetryReporter?.error({errorCode:"PAYMENT_PROCESSING_FAILED",failureCategory:"provider_runtime",stage:"processing",provider:t,paymentMethodCategory:e.paymentMethodCategory}),a}}async retrieveSession(e,n){if(!e)throw new m("sessionId is required to retrieve a session.","validation_error",{param:"sessionId"});let t=await this.retrieveUnifiedSession(e,n);if(!t.data.session)throw new m("Session not found","api_error");return t.data.session}async retrieveUnifiedSession(e,n){if(!e)throw new m("sessionId is required.","validation_error",{param:"sessionId"});let t=se(n??this.config.billingApiUrl),a=this.now();this.telemetryReporter?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let o,l=ee(t,{now:()=>this.telemetryReporter?.now()??x(),onFirstByte:s=>{o=s},onRetry:(s,i)=>{this.telemetryReporter?.log({name:"operation.retry",stage:s==="session_read"?"session_read":"processing",requestCategory:s,attempt:i})}});try{let s=await l.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()-a,durationMode:"machine",requestCategory:"session_read",statusClass:"2xx"}),s}catch(s){let i=V(s,s instanceof m&&s.code==="checkout_processing_timeout"?"REQUEST_TIMEOUT":"NETWORK_REQUEST_FAILED");throw this.telemetryReporter?.error({...i,stage:"session_read",provider:"flo",paymentMethodCategory:"unknown"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-a,durationMode:"machine",requestCategory:"session_read",statusClass:i.statusClass}),s}}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 le(r,e,n){let t=D;return new t(r,e,n)}var pe=new Map;function Y(r){return Array.isArray(r)?r.map(Y):r&&typeof r=="object"?Object.fromEntries(Object.entries(r).filter(([,e])=>e!==void 0).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>[e,Y(n)])):r}function Le(r,e){return JSON.stringify([r,$(e?.billingApiUrl),e?.telemetry!==!1,e?.locale??"auto",e?.apiVersion??null,Y(e?.appearance??null)])}var q=new Map;async function Ne(r,e){if(!r){let s=new g({billingApiUrl:$(e?.billingApiUrl),sdkVersion:de,enabled:e?.telemetry!==!1});throw s.error({errorCode:"CONFIGURATION_INVALID",stage:"sdk_initialize",paymentMethodCategory:"unknown"}),s.flush().catch(()=>{}).finally(()=>s.destroy()),new qe("A publishable key is required to initialize FloPay.","validation_error",{param:"publishableKey"})}let n=Le(r,e),t=pe.get(n);if(t)return e?.telemetry!==!1&&ie(t)?.log({name:"sdk.cache.hit",stage:"sdk_initialize"}),t;let a=q.get(n);if(a)return a;let o={...e,publishableKey:r},l=(async()=>{let s=new g({billingApiUrl:$(o.billingApiUrl),sdkVersion:de,enabled:o.telemetry!==!1}),i=s.now();s.log({name:"sdk.initialize.started",stage:"sdk_initialize"}),s.log({name:"sdk.cache.miss",stage:"sdk_initialize"}),s.log({name:"provider.load.started",stage:"provider_load",provider:"stripe"});let d=new R,h=s.now();try{await d.initialize(o)}catch(f){throw s.error({errorCode:"SDK_INITIALIZATION_FAILED",failureCategory:"provider_runtime",stage:"sdk_initialize",provider:"stripe",paymentMethodCategory:"unknown"}),s.destroy(),f}let C=s.now();s.log({name:"provider.ready",stage:"provider_ready",provider:"stripe"}),s.log({name:"provider.availability.checked",stage:"provider_ready",provider:"stripe"}),s.log({name:"sdk.initialize.ready",stage:"sdk_initialize"}),s.performance({stage:"sdk_initialize",durationMs:C-i,durationMode:"machine",provider:"stripe"}),s.performance({stage:"provider_ready",durationMs:C-h,durationMode:"machine",provider:"stripe"});let y=le(d,o,s);return pe.set(n,y),y})();q.set(n,l);try{return await l}finally{q.get(n)===l&&q.delete(n)}}import{FloPayError as S,IDEMPOTENCY_IN_PROGRESS_CODE as Ke,IDEMPOTENCY_KEY_HEADER as je,SDK_VERSION as ce,assertCaptureMethodEligible as ze,buildProductPayload as Be,classifyTelemetryFailure as Ve,foldIntoProducts as $e,resolveIdempotencyKey as me,resolveSessionCurrency as Ye,telemetryStatusClass as ye}from"@flopay/shared";var H=5,ue=new WeakSet;function Ge(r){(typeof r=="object"&&r!==null||typeof r=="function")&&ue.add(r)}function He(r){return(typeof r=="object"&&r!==null||typeof r=="function")&&ue.has(r)}function Je(r,e){let n=e?.error,t=E(e?.code)??E(n?.code)??`http_${r}`,a=E(e?.message)??E(n?.message)??We(t,r);return new S(a,"api_error",{code:t,statusCode:r})}function We(r,e){switch(r){case"CouponLimitExceeded":return`Too many coupon codes \u2014 a checkout session accepts at most ${H}.`;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 he(r,e,n){let{billingApiUrl:t,checkoutBaseUrl:a,items:o=[],subscriptions:l=[],products:s,account:i,successUrl:d,cancelUrl:h,checkoutMode:C="confirm",captureMethod:y,couponCodes:f=[],tagsData:J,redirectParams:Pe={},setCookie:we=!0,clientId:ve,currency:_e,utmMetadata:W,idempotencyKey:Se}=r,Q=me(Se);if(f.length>H)throw new S(`Too many coupon codes \u2014 a checkout session accepts at most ${H}.`,"validation_error",{code:"CouponLimitExceeded",param:"couponCodes"});let M=s??$e(o,l);ze({captureMethod:y,products:M});let P=Ye(_e,o,l,M);if(!P)throw new S("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 k={clientId:ve,checkoutVersion:ce,successUrl:d,cancelUrl:h,currency:P,checkoutMode:C,products:M.map(u=>Be(u,P)),accountData:{userId:i.userId,firstName:i.firstName??null,lastName:i.lastName??null,email:i.email,country:i.country??null,gender:i.gender??null,city:i.city??null,state:i.state??null,zip:i.zip??null,addressLine1:i.addressLine1??null,addressLine2:i.addressLine2??null},couponCodes:f};y==="manual"&&(k.captureMethod=y),J&&(k.tagsData=J),W?.length&&(k.utmMetadata=W);let Me=`${t.replace(/\/+$/,"")}/v1/checkouts/sessions`,X={"Content-Type":"application/json"};Q&&(X[je]=Q);let w,b,Ee={method:"POST",headers:X,body:JSON.stringify(k),signal:e},A;try{A=await fetch(Me,Ee)}catch(u){throw Ge(u),u}try{n?.(A.status)}catch{}w=A.status;try{b=await A.json()}catch{}if(w>=400)throw Je(w,b);if(w===201){let u=b?.data?.uuid,N=b?.data?.nonce;if(!u)throw new Error("Checkout session created but no UUID was returned by the billing API");if(!N)throw new S("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"});(M.length||P)&&K(u,{currency:P,products:M.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??P}))});let I=new URL(`${a.replace(/\/+$/,"")}/secure`);I.searchParams.set("id",u);for(let[c,F]of Object.entries(Pe))I.searchParams.set(c,F);if(we&&typeof window<"u"&&typeof document<"u"){let c=JSON.stringify({origin_url:h}),F=window.location.hostname.split(".").slice(-2).join(".");document.cookie=`checkout_data=${encodeURIComponent(c)}; domain=.${F}; path=/; max-age=3600; SameSite=Lax; Secure;`,document.cookie=`flopay_checkout_token=${encodeURIComponent(N)}; domain=.${F}; path=/; max-age=3600; SameSite=Lax; Secure;`}return typeof window<"u"&&(window.location.href=I.toString()),{status:201,redirectUrl:I.toString(),nonce:N}}return w===204?(typeof window<"u"&&(window.location.href=d),{status:204}):{status:w}}async function Qe(r){let e=ge(r),n=fe(e),t=j(r.timeoutMs);try{let a=await he(r,t.signal,n);return Ce(e,a),a}catch(a){throw L(e,a),a}finally{t.clear(),_(e.reporter)}}function fe(r){let e=!1;return n=>{if(e)return;e=!0;let t=ye(n);r.reporter.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:t,attempt:r.attempt}),r.reporter.performance({stage:"session_first_byte",durationMs:r.reporter.now()-r.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:t,attempt:r.attempt})}}function ge(r){let e=new g({billingApiUrl:r.billingApiUrl,sdkVersion:ce,enabled:r.telemetry!==!1}),n=e.now();return e.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"}),{reporter:e,startedAt:n,attempt:0}}function Ce(r,e){let n=ye(e.status);r.reporter.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:n}),r.reporter.performance({stage:"session_create",durationMs:r.reporter.now()-r.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:n,attempt:r.attempt})}function L(r,e){let{reporter:n}=r,t=Ve(e,"CHECKOUT_SESSION_CREATE_FAILED");if(n.performance({stage:"session_create",durationMs:n.now()-r.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:t.statusClass,attempt:r.attempt}),e instanceof S&&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 _(r){r.flush().catch(()=>{}).finally(()=>r.destroy())}async function Xe(r){let{maxRetries:e=2,...n}=r,t=ge(r),a=fe(t);if(!Number.isFinite(e)||!Number.isInteger(e)||e<0||e>=3)throw t.reporter.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),_(t.reporter),new Error(`Number of retries must be an integer between 0 and ${2}`);let o={...n,idempotencyKey:me(n.idempotencyKey)},l=j(n.timeoutMs),s;for(let i=0;i<=e;i++){t.attempt=i;try{let d=await he(o,l.signal,a);return Ce(t,d),l.clear(),_(t.reporter),d}catch(d){s=d;let h=d instanceof Error&&d.name==="AbortError",C=He(d),y=d instanceof S&&d.code===Ke;if((h||C||y)&&!l.signal.aborted&&i<e){t.reporter.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:i+1});try{await Z(i,l.signal)}catch(f){throw L(t,f),l.clear(),_(t.reporter),f}continue}throw L(t,d),l.clear(),_(t.reporter),d}}throw L(t,s),l.clear(),_(t.reporter),s??new Error("Unknown error during checkout session creation")}import{dropThirdPartyOnlyError as Dt}from"@flopay/shared";export{D as FloPay,T as FloPayElements,O as PaymentAPI,z as PciVaultCardCapture,ke as SESSION_CREATE_TELEMETRY,R as StripeAdapter,K as cacheSessionDisplayData,Te as clearSessionDisplayData,Qe as createCheckoutSession,Xe as createCheckoutSessionWithRetries,Dt as dropThirdPartyOnlyError,Re as getSessionDisplayData,Ne as loadFloPay,Fe as toStripeAppearance,U as toStripeAppearanceTheme};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flopay/js",
3
- "version": "1.4.22",
3
+ "version": "1.4.24",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "publishConfig": {
@@ -17,6 +17,11 @@
17
17
  "types": "./dist/index.d.ts",
18
18
  "import": "./dist/index.mjs",
19
19
  "require": "./dist/index.cjs"
20
+ },
21
+ "./card-setup": {
22
+ "types": "./dist/card-setup.d.ts",
23
+ "import": "./dist/card-setup.mjs",
24
+ "require": "./dist/card-setup.cjs"
20
25
  }
21
26
  },
22
27
  "main": "./dist/index.cjs",
@@ -27,7 +32,7 @@
27
32
  ],
28
33
  "dependencies": {
29
34
  "@stripe/stripe-js": "^9.8.0",
30
- "@flopay/shared": "1.4.22"
35
+ "@flopay/shared": "1.4.24"
31
36
  },
32
37
  "devDependencies": {
33
38
  "jsdom": "^29.1.1",