@flopay/js 1.14.9 → 1.14.11

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.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var Se=Object.defineProperty;var Ct=Object.getOwnPropertyDescriptor;var vt=Object.getOwnPropertyNames;var Tt=Object.prototype.hasOwnProperty;var bt=(t,e)=>{for(var r in e)Se(t,r,{get:e[r],enumerable:!0})},St=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of vt(e))!Tt.call(t,o)&&o!==r&&Se(t,o,{get:()=>e[o],enumerable:!(n=Ct(e,o))||n.enumerable});return t};var _t=t=>St(Se({},"__esModule",{value:!0}),t);var wr={};bt(wr,{FloPay:()=>ie,PaymentAPI:()=>oe,PciVaultCardCapture:()=>H,SESSION_CREATE_TELEMETRY:()=>Ee,StripeAdapter:()=>Q,cacheSessionDisplayData:()=>z,clearSessionDisplayData:()=>ye,completeSavedCardNextAction:()=>ht,createCheckoutSession:()=>Ne,createCheckoutSessionWithRetries:()=>je,createSavedCardActionAbortedError:()=>ae,dropThirdPartyOnlyError:()=>gt.dropThirdPartyOnlyError,getSessionDisplayData:()=>pe,loadFloPay:()=>mt,runSavedCardChallenge:()=>xe,toStripeAppearance:()=>X.toStripeAppearance,toStripeAppearanceTheme:()=>X.toStripeAppearanceTheme});module.exports=_t(wr);var gt=require("@flopay/shared");var T=require("@flopay/shared");function ee(t){return typeof t=="string"&&t.trim()?t:void 0}function te(t){if(typeof t=="string")return t.trim()?t:void 0;if(Array.isArray(t))return t.filter(r=>typeof r=="string"&&r.trim().length>0).join("; ")||void 0}function O(t=12e3){let e=Number.isFinite(t)&&t>=0?t:12e3,r=new AbortController,n=setTimeout(()=>r.abort(),e);return{signal:r.signal,clear:()=>clearTimeout(n)}}function wt(){return Object.assign(new Error("The operation was aborted."),{name:"AbortError"})}function G(t,e){let r=150*2**t,n=Math.round(r*(.75+Math.random()*.5));return new Promise((o,s)=>{let i,a=()=>e.removeEventListener("abort",c),c=()=>{i!==void 0&&clearTimeout(i),a(),s(wt())};if(e.aborted){c();return}i=setTimeout(()=>{a(),o()},n),e.addEventListener("abort",c,{once:!0})})}var Rt="flopay_session_display:";var de=new Map;function me(t){return`${Rt}${t}`}function _e(){if(typeof window>"u")return null;try{return window.sessionStorage}catch{return null}}function z(t,e,r){if(!t)return;let n=r?.ttlMs??36e5,o={data:e,expiresAt:Date.now()+n},s=_e();if(s)try{s.setItem(me(t),JSON.stringify(o));return}catch{}de.set(t,o)}function pe(t){if(!t)return null;let e=_e();if(e)try{let n=e.getItem(me(t));if(n){let o=JSON.parse(n);if(o&&typeof o.expiresAt=="number"&&o.expiresAt>Date.now())return o.data;e.removeItem(me(t))}}catch{}let r=de.get(t);if(r){if(r.expiresAt>Date.now())return r.data;de.delete(t)}return null}function ye(t){if(!t)return;de.delete(t);let e=_e();if(e)try{e.removeItem(me(t))}catch{}}var R=require("@flopay/shared"),At="/v1/sdk-telemetry/events",we=16,kt=64,Et=1500,Oe=1e3,Mt=64,It="00000000-0000-4000-8000-000000000000",Pt={technical_error:8,lifecycle:32,expected_outcome:32,performance:24};function Y(){try{return globalThis.crypto.randomUUID()}catch{let t=new Uint8Array(16);try{globalThis.crypto.getRandomValues(t)}catch{for(let r=0;r<t.length;r+=1)t[r]=Math.floor(Math.random()*256)}t[6]=(t[6]??0)&15|64,t[8]=(t[8]??0)&63|128;let e=[...t].map(r=>r.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(t){try{return new TextEncoder().encode(t).byteLength}catch{return t.length}}function Dt(t){return JSON.stringify([t.code,t.failureCategory,t.reason,t.stage,t.provider,t.attempt,t.statusClass,t.requestCategory,t.paymentMethodCategory,t.walletType,t.operationOutcome,t.checkoutMode,t.layout,t.inAppBrowser,t.appFamily,t.popupCapability,t.presentationMode,t.terminalReason])}function A(){return globalThis.performance?.now()??0}var w=class{constructor(e){this.ingestionDisabled=!1;this.queue=[];this.sequence=0;this.flushTimer=null;this.flushInFlight=null;this.reportedFailures=new Map;this.checkoutContext={};this.checkoutStartedAt=null;this.destroyed=!1;this.observers=new Set;this.pageExitHandler=()=>{this.drainQueue()};this.visibilityHandler=()=>{document.visibilityState==="hidden"&&this.flush()};this.eventCounts={technical_error:0,lifecycle:0,expected_outcome:0,performance:0};this.endpoint=`${e.billingApiUrl.replace(/\/+$/,"")}${At}`,this.sdkPackage=e.sdkPackage??"@flopay/js",this.sdkVersion=e.sdkVersion,this.correlationId=Y(),this.merchantEnabled=e.enabled!==!1,this.clock=e.clock??A,this.browserTransportAvailable=typeof window<"u"&&typeof document<"u",this.browserTransportAvailable&&(window.addEventListener("pagehide",this.pageExitHandler),document.addEventListener("visibilitychange",this.visibilityHandler))}log(e){this.notify({...e,class:"lifecycle"}),this.canCollect()&&this.enqueue((0,R.buildTelemetryLogEvent)({...this.checkoutContext,...e,eventId:Y(),sequence:this.sequence++}))}error(e){if(this.notify({...e,class:"technical_error"}),!this.canCollect())return;let r=(0,R.buildTelemetryErrorEvent)({...this.checkoutContext,...e,eventId:It,sequence:0}),n=Dt(r),o=this.now();this.pruneReportedFailures(o);let s=this.reportedFailures.get(n);if(s!==void 0&&o>=s&&o-s<Oe){this.log({name:"operation.deduplicated",stage:e.stage,provider:e.provider,paymentMethodCategory:e.paymentMethodCategory,attempt:e.attempt,inAppBrowser:e.inAppBrowser,appFamily:e.appFamily,popupCapability:e.popupCapability,presentationMode:e.presentationMode,terminalReason:e.terminalReason});return}this.rememberReportedFailure(n,o),this.enqueue((0,R.buildTelemetryErrorEvent)({...this.checkoutContext,...e,eventId:Y(),sequence:this.sequence++}))}performance(e){this.canCollect()&&this.enqueue((0,R.buildTelemetryPerformanceEvent)({...this.checkoutContext,...e,eventId:Y(),sequence:this.sequence++}))}terminal(e){if(this.canCollect()&&(this.enqueue((0,R.buildTelemetryTerminalEvent)({...this.checkoutContext,...e,eventId:Y(),sequence:this.sequence++})),e.outcome!=="action_required"&&this.checkoutStartedAt!==null)){let r=this.checkoutStartedAt;this.checkoutStartedAt=null,this.performance({...e,stage:"total_journey",durationMs:Math.max(0,this.now()-r),durationMode:"total"})}}now(){try{return this.clock()}catch{return A()}}subscribe(e){return this.destroyed?()=>{}:(this.observers.add(e),()=>this.observers.delete(e))}notify(e){if(!this.destroyed)for(let r of this.observers)try{r(e)}catch{}}pruneReportedFailures(e){for(let[r,n]of this.reportedFailures)(e<n||e-n>=Oe)&&this.reportedFailures.delete(r)}rememberReportedFailure(e,r){for(;this.reportedFailures.size>=Mt;){let n=this.reportedFailures.keys().next();if(n.done)break;this.reportedFailures.delete(n.value)}this.reportedFailures.set(e,r)}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>=kt||this.eventCounts[e.class]>=Pt[e.class])){if(this.eventCounts[e.class]+=1,this.queue.push(e),this.queue.length>=we){this.flush();return}this.scheduleFlush()}}canCollect(){return this.browserTransportAvailable&&this.merchantEnabled&&!this.ingestionDisabled&&!this.destroyed}async flush(){if(this.flushInFlight!==null)return this.flushInFlight;if(!this.browserTransportAvailable||this.destroyed||this.ingestionDisabled||this.queue.length===0)return;this.clearFlushTimer();let e=this.queue.splice(0,we);return this.flushInFlight=this.sendBatch(e).finally(()=>{this.flushInFlight=null,this.queue.length>0&&this.scheduleFlush()}),this.flushInFlight}destroy(){this.destroyed||(this.drainQueue(),this.destroyed=!0,this.clearFlushTimer(),this.browserTransportAvailable&&(window.removeEventListener("pagehide",this.pageExitHandler),document.removeEventListener("visibilitychange",this.visibilityHandler)),this.queue.splice(0),this.reportedFailures.clear(),this.observers.clear())}disable(){this.merchantEnabled=!1,this.queue.splice(0),this.reportedFailures.clear(),this.clearFlushTimer()}drainQueue(){if(!(!this.browserTransportAvailable||this.destroyed||this.ingestionDisabled||this.queue.length===0))for(this.clearFlushTimer();this.queue.length>0;){let e=this.queue.splice(0,we);this.sendBatch(e)}}async sendBatch(e){if(!this.browserTransportAvailable||this.ingestionDisabled)return;let r=(0,R.serializeTelemetryBatch)(e,{correlationId:this.correlationId,sdkPackage:this.sdkPackage,sdkVersion:this.sdkVersion,batchId:Y()});if(xt(r)>R.TELEMETRY_MAX_BATCH_BYTES)return;let n=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:r,credentials:"omit",keepalive:!0,referrerPolicy:"no-referrer",signal:n?.signal}).then(async c=>{if(c.status!==202)return null;let l=null;try{l=await c.json()}catch{}return l?.status==="disabled"?"disabled":null}).catch(()=>null),i=new Promise(c=>{o=setTimeout(()=>{n?.abort(),c(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)}},Fe=Symbol.for("@flopay/js.telemetry.reporter-factory.v1"),Ue=globalThis;Ue[Fe]===void 0&&Object.defineProperty(Ue,Fe,{configurable:!0,enumerable:!1,writable:!1,value:t=>new w(t)});var Re=5,qe=new WeakSet;function Ot(t){(typeof t=="object"&&t!==null||typeof t=="function")&&qe.add(t)}function Ft(t){return(typeof t=="object"&&t!==null||typeof t=="function")&&qe.has(t)}function Ut(t,e){let r=e?.error,n=ee(e?.code)??ee(r?.code)??`http_${t}`,o=te(e?.message)??te(r?.message)??qt(n,t);return new T.FloPayError(o,"api_error",{code:n,statusCode:t})}function qt(t,e){switch(t){case"CouponLimitExceeded":return`Too many coupon codes \u2014 a checkout session accepts at most ${Re}.`;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 Le(t,e,r){let{billingApiUrl:n,checkoutBaseUrl:o,items:s=[],subscriptions:i=[],products:a,account:c,successUrl:l,cancelUrl:m,checkoutMode:y="confirm",captureMethod:d,couponCodes:h=[],checkoutMetadata:p,tagsData:C,redirectParams:f={},setCookie:v=!0,clientId:S,currency:g,utmMetadata:P,idempotencyKey:K}=t,E=(0,T.resolveIdempotencyKey)(K);if(h.length>Re)throw new T.FloPayError(`Too many coupon codes \u2014 a checkout session accepts at most ${Re}.`,"validation_error",{code:"CouponLimitExceeded",param:"couponCodes"});let M=a??(0,T.foldIntoProducts)(s,i);(0,T.assertCaptureMethodEligible)({captureMethod:d,products:M});let x=(0,T.resolveSessionCurrency)(g,s,i,M);if(!x)throw new T.FloPayError("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});let D={clientId:S,checkoutVersion:T.SDK_VERSION,successUrl:l,cancelUrl:m,currency:x,checkoutMode:y,products:M.map(q=>(0,T.buildProductPayload)(q,x)),accountData:{userId:c.userId,firstName:c.firstName??null,lastName:c.lastName??null,email:c.email,country:c.country??null,gender:c.gender??null,city:c.city??null,state:c.state??null,zip:c.zip??null,addressLine1:c.addressLine1??null,addressLine2:c.addressLine2??null},couponCodes:h};d==="manual"&&(D.captureMethod=d),p!==void 0&&(D.checkoutMetadata=p),C&&(D.tagsData=C),P&&P.length>0&&(D.utmMetadata=P);let Te=`${n.replace(/\/+$/,"")}/v1/checkouts/sessions`,De={"Content-Type":"application/json"};E&&(De[T.IDEMPOTENCY_KEY_HEADER]=E);let $,ce,ft={method:"POST",headers:De,body:JSON.stringify(D),signal:e},Z;try{r?.startAttempt(),Z=await fetch(Te,ft)}catch(q){throw Ot(q),q}try{r?.record(Z.status)}catch{}$=Z.status;try{ce=await Z.json()}catch{}if($>=400)throw(0,T.withTelemetryHttpDiagnostics)(Ut($,ce),Z);if($===201){let q=ce?.data?.uuid,be=ce?.data?.nonce;if(!q)throw new Error("Checkout session created but no UUID was returned by the billing API");if(!be)throw new T.FloPayError("Checkout session created but no `nonce` was returned by the billing API. Upgrade the billing service to TeamFloPay/backend#640 or later.","api_error",{code:"MissingCheckoutSessionToken"});(M.length>0||x)&&z(q,{currency:x,products:M.map(_=>({code:_.code??_.providerItemId??_.providerPlanId,type:_.type,name:_.name??_.itemName??_.providerItemName??_.subscriptionName??_.providerPlanName??null,totalAmount:_.totalAmount,overrideAmount:_.overrideAmount,currency:_.currency??x}))});let le=new URL(`${o.replace(/\/+$/,"")}/secure`);le.searchParams.set("id",q);for(let[_,ue]of Object.entries(f))le.searchParams.set(_,ue);if(v&&typeof window<"u"&&typeof document<"u"){let _=JSON.stringify({origin_url:m}),ue=window.location.hostname.split(".").slice(-2).join(".");document.cookie=`checkout_data=${encodeURIComponent(_)}; domain=.${ue}; path=/; max-age=3600; SameSite=Lax; Secure;`,document.cookie=`flopay_checkout_token=${encodeURIComponent(be)}; domain=.${ue}; path=/; max-age=3600; SameSite=Lax; Secure;`}return typeof window<"u"&&(window.location.href=le.toString()),{status:201,redirectUrl:le.toString(),nonce:be}}return $===204?(typeof window<"u"&&(window.location.href=l),{status:204}):{status:$}}async function Ne(t){let e=ze(t),r=Ve(e),n=O(t.timeoutMs);try{let o=await Le(t,n.signal,r);return r.commit(),Be(e,o),o}catch(o){throw r.commit(),he(e,o),o}finally{n.clear(),W(e.reporter)}}function Ve(t){let e=!1,r=t.startedAt,n;return{startAttempt(){r=t.reporter.now()},record(o){n={status:o,durationMs:Math.max(0,t.reporter.now()-r),attempt:t.attempt}},commit(){if(e||!n)return;e=!0;let o=(0,T.telemetryStatusClass)(n.status);t.reporter.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:o,attempt:n.attempt}),t.reporter.performance({stage:"session_first_byte",durationMs:n.durationMs,durationMode:"machine",requestCategory:"session_create",statusClass:o,attempt:n.attempt})}}}function ze(t){let e=new w({billingApiUrl:t.billingApiUrl,sdkVersion:T.SDK_VERSION,enabled:t.telemetry!==!1}),r=e.now();return e.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"}),{reporter:e,startedAt:r,attempt:0}}function Be(t,e){let r=(0,T.telemetryStatusClass)(e.status);t.reporter.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:r}),t.reporter.performance({stage:"session_create",durationMs:t.reporter.now()-t.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:r,attempt:t.attempt})}function he(t,e){let{reporter:r}=t,n=(0,T.classifyTelemetryFailure)(e,"CHECKOUT_SESSION_CREATE_FAILED");if(r.performance({stage:"session_create",durationMs:r.now()-t.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:n.statusClass,attempt:t.attempt}),e instanceof T.FloPayError&&e.type==="validation_error"){r.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"});return}if(n.statusClass==="4xx"){r.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create",statusClass:"4xx"});return}r.error({...n,stage:"session_create",requestCategory:"session_create"})}function W(t){t.flush().catch(()=>{}).finally(()=>t.destroy())}async function je(t){let{maxRetries:e=2,...r}=t,n=ze(t),o=Ve(n);if(!Number.isFinite(e)||!Number.isInteger(e)||e<0||e>=3)throw n.reporter.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),W(n.reporter),new Error(`Number of retries must be an integer between 0 and ${2}`);let s={...r,idempotencyKey:(0,T.resolveIdempotencyKey)(r.idempotencyKey)},i=O(r.timeoutMs),a;for(let c=0;c<=e;c++){n.attempt=c;try{let l=await Le(s,i.signal,o);return o.commit(),Be(n,l),i.clear(),W(n.reporter),l}catch(l){a=l;let m=l instanceof Error&&l.name==="AbortError",y=Ft(l),d=l instanceof T.FloPayError&&l.code===T.IDEMPOTENCY_IN_PROGRESS_CODE;if((m||y||d)&&!i.signal.aborted&&c<e){n.reporter.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:c+1});try{await G(c,i.signal)}catch(h){throw o.commit(),he(n,h),i.clear(),W(n.reporter),h}continue}throw o.commit(),he(n,l),i.clear(),W(n.reporter),l}}throw o.commit(),he(n,a),i.clear(),W(n.reporter),a??new Error("Unknown error during checkout session creation")}var k=require("@flopay/shared");var u=require("@flopay/shared");function Lt(t){return t==="on_session"||t==="off_session"}function Nt(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.paymentMethodType=="string"&&typeof e.reason=="string"}var Vt="x-flopay-process-result-source",zt="status";function He(t){return t?.result==="DECLINE"||t?.result==="ERROR"}var Bt=50,B=new Map;function jt(t,e){return B.get(t)?.has(e)===!0}function Ht(t,e){let r=B.get(t)??new Set;if(r.add(e),B.delete(t),B.set(t,r),B.size>Bt){let n=B.keys().next().value;n!==void 0&&B.delete(n)}}function Kt(t){let e=t?.threeDSecureActionResultTokenId;if(typeof e=="string"&&e.length>0)return e;if(t?.gateway==="paypal"&&t.type!=="paypal_setup_token"&&typeof t.id=="string"&&t.id.length>0)return t.id}var Ke=0,$e=500,ge=15e3,Ge=15e3,$t=3e3,Gt=1e4,Yt=1e4;function ne(t){return typeof t=="object"&&t!==null}function N(t,e){return ee(t?.[e])}function Ye(t,e){return te(t?.[e])}function Wt(t,e){let r=t?.[e];return typeof r=="number"&&Number.isFinite(r)?r:void 0}function ke(t,e){return e?new Promise((r,n)=>{let o=()=>{clearTimeout(s),n(e.reason??Object.assign(new Error("The operation was aborted."),{name:"AbortError"}))},s=setTimeout(()=>{e.removeEventListener("abort",o),r()},t);e.aborted?o():e.addEventListener("abort",o,{once:!0})}):new Promise(r=>setTimeout(r,t))}function Ae(t){return t instanceof Error&&t.name==="AbortError"}function I(){return new u.FloPayError(u.CHECKOUT_PROCESSING_TIMEOUT_MESSAGE,"api_error",{code:"checkout_processing_timeout"})}async function L(t,e){let r=await t.json().catch(()=>null),n=ne(r?.error)?r.error:null,o=Ye(r,"message")??Ye(n,"message")??e,s=N(r,"code")??N(r,"gatewayErrorCode")??N(n,"code")??`http_${t.status}`;return(0,u.withTelemetryHttpDiagnostics)(new u.FloPayError(o,"api_error",{code:s,statusCode:t.status}),t)}async function Jt(t){if(t.status!==403)return!1;let e=await t.clone().json().catch(()=>null),r=ne(e?.error)?e.error:null;return(N(e,"code")??N(r,"code"))==="verification_required"}function Qt(t){if(!(!ne(t)||typeof t.required!="boolean"))return{required:t.required,provider:"turnstile"}}async function Xt(t){let e=t.status===400?await t.clone().json().catch(()=>null):null;return(0,u.classifyPaymentRejection)(t.status,e)}function We(t){return t===400||t===422}var Ce=2;async function fe(t,e,r=Ce,n,o){let s;for(let i=0;;i++)try{return o?.(i),await fetch(t,e)}catch(a){if(e?.signal?.aborted||a instanceof Error&&a.name==="AbortError")throw a;if(s=a,i>=r)throw s;try{n?.(i+1)}catch{}await ke(150*2**i,e?.signal??void 0)}}var Ee=Symbol.for("@flopay/js.session-create.telemetry.v1");function Zt(t){return t[Ee]}function er(t){return"now"in t||"onFirstByte"in t||"onSessionCreateFailure"in t||"onRetry"in t}function Qe(t){let e=(0,u.isCardHolderNamePlaceholder)(t.firstName,t.lastName);return{userId:t.userId,firstName:e?null:t.firstName??null,lastName:e?null:t.lastName??null,email:t.email,country:t.country??null,gender:t.gender??null,city:t.city??null,state:t.state??null,zip:t.zip??null,addressLine1:t.addressLine1??null,addressLine2:t.addressLine2??null}}function Xe(t,e){e.checkoutMetadata!==void 0&&(t.checkoutMetadata=e.checkoutMetadata),e.tagsData&&(t.tagsData=e.tagsData),e.utmMetadata&&e.utmMetadata.length>0&&(t.utmMetadata=e.utmMetadata),e.avsCheck!==void 0&&(t.avsCheck=e.avsCheck),e.checkoutType&&(t.checkoutType=e.checkoutType),e.checkoutLayout&&(t.checkoutLayout=e.checkoutLayout),e.avsConfig&&(t.avsConfig=e.avsConfig)}function tr(t,e){let r={clientId:t.clientId,checkoutVersion:u.SDK_VERSION,successUrl:t.successUrl,cancelUrl:t.cancelUrl,currency:e,checkoutMode:"full",deferDataAttachment:!0};return t.captureMethod==="manual"&&(r.captureMethod=t.captureMethod),t.account.country&&(r.accountData={country:t.account.country}),Xe(r,t),r}function Je(t,e,r){return{currency:e,products:r.map(n=>(0,u.buildProductPayload)(n,e)),couponCodes:t.couponCodes??[],accountData:Qe(t.account)}}function rr(t,e,r){return{currency:e,products:r.map(n=>(0,u.buildProductPayload)(n,e)),couponCodes:t.couponCodes??[]}}function nr(t){let e={},r=(0,u.isCardHolderNamePlaceholder)(t.firstName,t.lastName);for(let[n,o]of Object.entries(t)){if(r&&n.endsWith("Name")||typeof o!="string")continue;let s=o.trim();s&&(e[n]=s)}return{accountData:e}}var j=class j{constructor(e,r={}){this.baseUrl=e.replace(/\/+$/,"");let n=er(r);this.telemetryHooks=n?r:void 0,this.directTelemetry=n||r.telemetry===!1?void 0:new w({billingApiUrl:this.baseUrl,sdkVersion:u.SDK_VERSION})}destroy(){this.directTelemetry?.destroy()}reportDirectFailure(e,r,n,o,s="unknown"){let i=(0,u.classifyTelemetryFailure)(e,r);this.directTelemetry?.error({...i,stage:n,requestCategory:o,paymentMethodCategory:s})}reportAccountSnapshotFailure(e,r){let n=(0,u.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED");if(r==="best_effort"&&n.errorCode==="REQUEST_TIMEOUT"){this.directTelemetry?.log({name:"operation.fallback",stage:"processing",requestCategory:"account_snapshot",statusClass:"timeout"});return}this.directTelemetry?.error({...n,stage:"processing",requestCategory:"account_snapshot",paymentMethodCategory:"unknown"})}telemetryTimestamp(){try{return this.telemetryHooks?.now?.()??this.directTelemetry?.now()??A()}catch{return A()}}beginDirectTelemetryCheckout(e){!this.directTelemetry||this.directTelemetryCheckoutId===e||(this.directTelemetryCheckoutId=e,this.directTelemetry.beginCheckout())}beginDirectTelemetryOperation(){this.directTelemetry&&(this.directTelemetryCheckoutId=void 0,this.directTelemetry.beginCheckout())}adoptDirectTelemetryCheckout(e){e&&(this.directTelemetryCheckoutId=e)}async getCheckoutSession(e,r){return this.fetchCheckoutSession(e,r)}async fetchCheckoutSession(e,r,n=!0,o){this.beginDirectTelemetryCheckout(e);let s=this.telemetryTimestamp(),i=s,a=0;this.directTelemetry?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let c={[u.FLO_SDK_VERSION_HEADER]:u.SDK_VERSION};r&&(c["x-checkout-session-token"]=r);let l=!1;try{let m=await fe(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}`,{headers:c,signal:o},Ce,p=>{this.telemetryHooks?.onRetry?.("session_read",p),this.directTelemetry?.log({name:"operation.retry",stage:"session_read",requestCategory:"session_read",attempt:p})},p=>{a=p,i=this.telemetryTimestamp()});l=!0;let y=Math.max(0,this.telemetryTimestamp()-i);try{this.telemetryHooks?.onFirstByte?.(y,a)}catch{}let d=`${Math.floor(m.status/100)}xx`;if(this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:d,attempt:a}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:y,durationMode:"machine",requestCategory:"session_read",statusClass:d,attempt:a}),!m.ok)throw await L(m,"Failed to get checkout session");let h=await m.json();return this.directTelemetry?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:d}),this.directTelemetry?.performance({stage:"session_complete",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"session_read",statusClass:d}),{...h,data:this.mergeCachedDisplayData(h.data)}}catch(m){throw l&&(0,u.markSessionResponseReceived)(m),n&&this.directTelemetry?.error({...(0,u.classifyTelemetryFailure)(m,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"}),m}}cacheSessionDisplayData(e,r,n){z(e,r,n)}clearSessionDisplayData(e){ye(e)}async getVaultCapture(e,r){let n=`${this.baseUrl}\0${e}\0${r??""}`,o=j.activeVaultCaptureRequests.get(n);if(o!==void 0)return o;let s=this.requestVaultCapture(e,r);j.activeVaultCaptureRequests.set(n,s);try{return await s}finally{j.activeVaultCaptureRequests.get(n)===s&&j.activeVaultCaptureRequests.delete(n)}}async requestVaultCapture(e,r){let n=new AbortController,o=setTimeout(()=>n.abort(),Yt);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"};r&&(i["x-checkout-session-token"]=r);try{let a=await fe(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/vault/capture`,{method:"POST",headers:i,signal:n.signal},Ce,l=>{this.telemetryHooks?.onRetry?.("vault_capture",l),this.directTelemetry?.log({name:"operation.retry",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card",attempt:l})});if(await Jt(a))return this.directTelemetry?.performance({stage:"vault_request",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"4xx"}),{verification:{required:!0,provider:"turnstile"}};if(!a.ok)throw await L(a,"Failed to load the secure card form");let c=await a.json();return this.directTelemetry?.performance({stage:"vault_request",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"2xx"}),this.toVaultBlock(c)}catch(a){let c=n.signal.aborted?new u.FloPayError("Timed out while loading the secure card form. Please try again.","api_error",{code:"vault_capture_timeout"}):a;throw this.reportDirectFailure(c,"VAULT_LOAD_FAILED","vault_request","vault_capture","card"),c}finally{clearTimeout(o)}}async getUnifiedCheckoutSession(e,r){let n=await this.getCheckoutSession(e,r);return this.normalizeCheckoutSessionResponse(n)}async getUnifiedCheckoutSessionForRecovery(e,r,n){let o=await this.fetchCheckoutSession(e,r,!1,n);return this.normalizeCheckoutSessionResponse(o)}normalizeCheckoutSessionResponse(e){try{let r=this.normalizeRawSession(e.data),n=e.vault;return n&&r.data.session&&(r.data.session.vault=this.toVaultBlock(n)),r}catch(r){throw(0,u.markSessionResponseReceived)(r)}}async processPayment(e,r,n){this.beginDirectTelemetryCheckout(r.sessionId);let o=r.paymentMethodCategory??"unknown";if(!r.nonce)throw this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"process_payment",paymentMethodCategory:o}),new u.FloPayError("processPayment requires `nonce` \u2014 pass the value returned from session creation.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let s=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.processing.started",stage:"processing",requestCategory:"process_payment",paymentMethodCategory:o});let{nonce:i,paymentMethodCategory:a,...c}=r,l=Kt(r.tokenizedData),m,y;try{m=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(r.sessionId)}/process`,{method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":i},body:JSON.stringify(c)}),y=m}catch(d){if(Ae(d))throw this.reportDirectFailure(d,"PAYMENT_PROCESSING_FAILED","processing","process_payment",o),d;m=await this.reconcileProcessPayment(r.sessionId,{...n,nonce:i,paymentMethodCategory:o,submittedIntentId:l})}if(!m.ok&&m.status!==202){let d=await Xt(m);return d?this.directTelemetry?.terminal({outcome:d,stage:"processing",requestCategory:"process_payment",statusClass:"4xx",paymentMethodCategory:o}):this.directTelemetry?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",requestCategory:"process_payment",statusClass:(0,u.telemetryStatusClass)(m.status),failureCategory:m.status>=500?"server_error":void 0,paymentMethodCategory:o,...(0,u.readTelemetryHttpDiagnostics)(y)}),m}try{let d=await this.resolveProcessResponse(m,r.sessionId,{...n,nonce:i,paymentMethodCategory:o,submittedIntentId:l});return this.directTelemetry?.log({name:"payment.processing.completed",stage:"processing",requestCategory:"process_payment",statusClass:(0,u.telemetryStatusClass)(d.status),paymentMethodCategory:o}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"process_payment",statusClass:(0,u.telemetryStatusClass)(d.status),paymentMethodCategory:o}),d}catch(d){throw d instanceof u.FloPayError&&d.code==="checkout_processing_timeout"||this.reportDirectFailure(d,"PAYMENT_PROCESSING_FAILED","processing","process_payment",o),d}}async patchAccountSnapshot(e,r,n,o){this.beginDirectTelemetryCheckout(e);let s=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.state_transition",stage:"processing",requestCategory:"account_snapshot"});let i=o?.timeoutMs??Gt,a=new AbortController,c=()=>a.abort();o?.signal&&(o.signal.aborted?a.abort():o.signal.addEventListener("abort",c,{once:!0}));let l=setTimeout(()=>a.abort(),i);try{let m;try{m=await fe(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/account`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":r},body:JSON.stringify(n),signal:a.signal},Ce,y=>{this.telemetryHooks?.onRetry?.("account_snapshot",y),this.directTelemetry?.log({name:"operation.retry",stage:"processing",requestCategory:"account_snapshot",attempt:y})})}finally{clearTimeout(l),o?.signal?.removeEventListener("abort",c)}if(!m.ok)throw await L(m,"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(m){throw this.reportAccountSnapshotFailure(m,o?.telemetryMode??"blocking"),m}}async createSessionIntent(e,r,n,o){if(!r)throw new u.FloPayError("createSessionIntent requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let s=n,i=s.paymentMethodType,a=typeof i=="string"&&i.trim().toLowerCase()==="card",c=typeof i=="string"&&i.length>0&&!a&&(typeof s.paymentMethodId=="string"||s.paymentMethodId===null),l=s.provider==="stripe"&&(s.paymentMethodCategory==="wallet"||s.paymentMethodCategory==="apm")&&(s.intentKind==="payment"||s.intentKind==="setup"),m=s.provider==="paypal"&&s.paymentMethodCategory==="wallet"&&s.paymentMethodId===null&&(s.paymentMethodType==="paypal"&&s.intentKind==="payment"||s.paymentMethodType===u.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&(s.intentKind==="payment"||s.intentKind==="setup"));if(!c||!l&&!m)throw new u.FloPayError("Only wallet, APM, and PayPal session intents are supported.","validation_error",{code:"InvalidSessionIntentRequest"});let y=s.authorizationAttemptId;if(y!==void 0&&!(0,u.isUuidV4)(y))throw new u.FloPayError("authorizationAttemptId must be a v4 UUID identifying one buyer authorization attempt.","validation_error",{code:"InvalidAuthorizationAttemptId",param:"authorizationAttemptId"});let d=(0,u.isUuidV4)(y)?y:(0,u.randomUuidV4)();this.beginDirectTelemetryCheckout(e);let h=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.intent.started",stage:"processing",requestCategory:"intent_create"});let p={"Content-Type":"application/json","x-checkout-session-token":r,[u.IDEMPOTENCY_KEY_HEADER]:o?.idempotencyKey||d},C=!1;try{let f=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents`,{method:"POST",headers:p,body:JSON.stringify({...n,authorizationAttemptId:d}),signal:o?.signal});if(!f.ok){C=!0;let D=await L(f,"Failed to create checkout intent"),Te=(0,u.classifyTelemetryFailure)(D,"PAYMENT_PROCESSING_FAILED");throw We(D.statusCode)?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"intent_create",statusClass:"4xx"}):this.directTelemetry?.error({...Te,stage:"processing",requestCategory:"intent_create"}),D}let v=await f.json();if(f.status===202&&ne(v)&&v.type==="checkout_processing")return C=!0,await this.settleProcessingSessionIntent(v,f,e,r,n);let S=v.data;if(!S||typeof S!="object")throw new u.FloPayError("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});let g=S,P=g.paymentMethodType,K=(g.paymentMethodCategory==="wallet"||g.paymentMethodCategory==="apm")&&typeof P=="string"&&P.trim().toLowerCase()!=="card"&&(typeof g.paymentMethodId=="string"||g.paymentMethodId===null)&&typeof g.providerObjectId=="string",E=g.provider==="stripe"&&(g.intentKind==="payment"||g.intentKind==="setup")&&typeof g.clientSecret=="string",M=g.provider==="paypal"&&g.paymentMethodCategory==="wallet"&&g.paymentMethodId===null&&(g.paymentMethodType==="paypal"&&g.intentKind==="payment"&&(g.providerObjectType==="order"||g.providerObjectType==="subscription")||g.paymentMethodType===u.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&g.intentKind==="payment"&&g.providerObjectType==="order"||g.paymentMethodType===u.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&g.intentKind==="setup"&&g.providerObjectType==="setup_token")&&g.clientSecret===null,x=g.provider===n.provider&&g.paymentMethodCategory===n.paymentMethodCategory&&g.paymentMethodType===n.paymentMethodType&&g.paymentMethodId===n.paymentMethodId&&g.intentKind===n.intentKind;if(!K||!E&&!M||!x)throw new u.FloPayError("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});return this.directTelemetry?.log({name:"payment.intent.completed",stage:"processing",requestCategory:"intent_create",statusClass:(0,u.telemetryStatusClass)(f.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-h),durationMode:"machine",requestCategory:"intent_create",statusClass:(0,u.telemetryStatusClass)(f.status)}),g}catch(f){throw C||this.reportDirectFailure(f,"PAYMENT_PROCESSING_FAILED","processing","intent_create"),f}}async settleProcessingSessionIntent(e,r,n,o,s){let i=this.toCheckoutProcessingPending(e,r,n);try{return{settled:!0,response:await this.resolveCheckoutProcessing(i,n,{nonce:o,paymentMethodCategory:s.provider==="paypal"?"paypal":s.paymentMethodCategory})}}catch(a){throw a instanceof u.FloPayError&&a.code==="checkout_processing_timeout"?new u.FloPayError(a.message,a.type,{code:a.code,statusCode:202,sessionId:i.sessionId,cause:a}):a}}async reportSessionIntentDecline(e,r,n,o){if(!r)throw new u.FloPayError("reportSessionIntentDecline requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let s=n,i=s.providerDeclineReason,a=s.paymentMethodType,c=s.providerIntentId,l=typeof i=="string"&&/^[a-z0-9][a-z0-9_.:-]{0,63}$/i.test(i)&&!/^(?:pm|pi|seti|tok|src|cus|sess|sk|pk)_/i.test(i),m=typeof a=="string"&&a.length>0&&a.trim().toLowerCase()!=="card"&&l,y=s.provider==="stripe"&&(s.paymentMethodCategory==="wallet"||s.paymentMethodCategory==="apm")&&(c===void 0||typeof c=="string"&&/^pi_[a-z0-9_]{1,252}$/i.test(c)),d=s.provider==="paypal"&&s.paymentMethodCategory==="wallet"&&s.paymentMethodType==="paypal"&&c===void 0;if(!m||!y&&!d)throw new u.FloPayError("Invalid non-card decline classification.","validation_error",{code:"InvalidSessionIntentDeclineRequest"});let h=d?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:i}:{provider:"stripe",paymentMethodCategory:s.paymentMethodCategory,paymentMethodType:s.paymentMethodType,providerDeclineReason:i,...typeof c=="string"?{providerIntentId:c}:{}},p=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents/decline`,{method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":r},body:JSON.stringify(h),signal:o?.signal});if(!p.ok)throw await L(p,"Failed to report checkout decline")}async getPaymentsByEmail(e,r){this.beginDirectTelemetryOperation();let n=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved"});let o=r?.page??1,s=r?.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:r?.signal,keepalive:!0});if(!a.ok)throw(0,u.withTelemetryHttpDiagnostics)(new u.FloPayError("Failed to fetch payments","api_error",{statusCode:a.status}),a);let c=await a.json();return this.directTelemetry?.log({name:"operation.recovery.completed",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),this.directTelemetry?.performance({stage:"recovery",durationMs:Math.max(0,this.telemetryTimestamp()-n),durationMode:"machine",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),c}catch(a){throw this.reportDirectFailure(a,"RECOVERY_FAILED","recovery","other","saved"),a}}async createAndFetchSession(e){if((0,u.isDetachedSessionEligible)(e)){let s=e.account.email?.trim();if(s&&!(0,u.isValidEmail)(s))throw new u.FloPayError("Buyer email must be valid when supplied.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"});return(await this.createDetachedSession(e)).claimed}this.beginDirectTelemetryOperation();let r=this.telemetryTimestamp(),n=O(e.timeoutMs??12e3),o={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});try{let s=await this.createAndFetchSessionRequest(e,n.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()-r),durationMode:"machine",requestCategory:"session_create",statusClass:o.statusClass,attempt:o.attempt}),s}catch(s){throw this.reportSessionCreateFailure(s,r,o),s}finally{n.clear()}}async createAndFetchSessionRequest(e,r,n){let o=e.products??(0,u.foldIntoProducts)(e.items,e.subscriptions);(0,u.assertCaptureMethodEligible)({captureMethod:e.captureMethod,products:o});let s=(0,u.resolveSessionCurrency)(e.currency,e.items,e.subscriptions,o);if(!s)throw new u.FloPayError("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});let i={clientId:e.clientId,checkoutVersion:u.SDK_VERSION,successUrl:e.successUrl,cancelUrl:e.cancelUrl,currency:s,checkoutMode:e.checkoutMode??"full",products:o.map(l=>(0,u.buildProductPayload)(l,s)),accountData:Qe(e.account),couponCodes:e.couponCodes??[]};e.captureMethod==="manual"&&(i.captureMethod=e.captureMethod),e.tokenizedData&&(i.tokenizedData=e.tokenizedData),Xe(i,e);let a=await this.postCheckoutSessionCreate(i,e,r,n),c=!1;try{let l=await a.json();if(l.data&&"gateways"in l.data){this.autoCacheDisplayData(l.data.uuid,e);let d=this.mergeCachedDisplayData(l.data),h=this.normalizeRawSession(d);return l.vault&&h.data.session&&(h.data.session.vault=this.toVaultBlock(l.vault)),{...h,autoProcessingError:l.autoProcessingError,autoProcessingAttempted:l.autoProcessingAttempted,autoProcessingPending:l.autoProcessingPending}}let m=l.data?.uuid;if(!m)throw new u.FloPayError("No session ID returned","api_error",{code:"InvalidCheckoutSessionResponse"});return this.autoCacheDisplayData(m,e),this.adoptDirectTelemetryCheckout(m),c=!0,{...await this.getUnifiedCheckoutSession(m),autoProcessingError:l.autoProcessingError,autoProcessingAttempted:l.autoProcessingAttempted,autoProcessingPending:l.autoProcessingPending}}catch(l){throw c?l:(0,u.markSessionResponseReceived)(l)}}async postCheckoutSessionCreate(e,r,n,o){let s={"Content-Type":"application/json",[u.FLO_SDK_VERSION_HEADER]:u.SDK_VERSION},i=(0,u.resolveIdempotencyKey)(r.idempotencyKey);i&&(s[u.IDEMPOTENCY_KEY_HEADER]=i),r.checkoutMode==="auto"&&(s[u.FLO_SDK_CAPABILITIES_HEADER]=u.ASYNC_AUTO_CHECKOUT_CAPABILITY);let a,c=!1,l=Zt(r),m=(d,h,p)=>{c||(c=!0,this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:p,attempt:d}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:Math.max(0,this.telemetryTimestamp()-h),durationMode:"machine",requestCategory:"session_create",statusClass:p,attempt:d}))},y=d=>{try{this.telemetryHooks?.onRetry?.("session_create",d),this.directTelemetry?.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:d})}catch{}};for(let d=0;d<3;d++){o.attempt=d;let h=this.telemetryTimestamp();try{l?.onAttempt?.(d)}catch{}try{a=await fetch(`${this.baseUrl}/v1/checkouts/sessions?expand=true`,{method:"POST",headers:s,body:JSON.stringify(e),signal:n})}catch(f){if(o.statusClass=n.aborted||f instanceof Error&&f.name==="AbortError"?"timeout":"network_error",n.aborted||f instanceof Error&&f.name==="AbortError"||d>=2)throw f;let v=d+1;y(v),await G(d,n);continue}let p=(0,u.telemetryStatusClass)(a.status);if(o.statusClass=p,a.status===204)throw m(d,h,p),new u.FloPayError("Session auto-completed \u2014 payment method already on file","api_error",{code:"session_auto_completed"});if(a.ok){m(d,h,p);break}let C=await L(a,"Failed to create checkout session");if(C.code===u.IDEMPOTENCY_IN_PROGRESS_CODE&&d<2){y(d+1),await G(d,n);continue}throw m(d,h,p),C}if(!a)throw new TypeError("Checkout-session creation exhausted its retry budget.");return a}async createDetachedSession(e){this.beginDirectTelemetryOperation();let r=this.telemetryTimestamp(),n=O(e.timeoutMs??12e3),o={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let s=e.products??(0,u.foldIntoProducts)(e.items,e.subscriptions);try{(0,u.assertCaptureMethodEligible)({captureMethod:e.captureMethod,products:s})}catch(v){throw n.clear(),this.reportSessionCreateFailure(v,r,o),v}let i=(0,u.resolveSessionCurrency)(e.currency,e.items,e.subscriptions,s);if(!i)throw n.clear(),this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),new u.FloPayError("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});try{Je(e,i,s)}catch(v){throw n.clear(),this.reportSessionCreateFailure(v,r,o),v}let a,c,l=!1;try{let v=await this.postCheckoutSessionCreate(tr(e,i),e,n.signal,o);if(l=!0,c=await v.json(),!c.data||!("gateways"in c.data))throw new u.FloPayError("The billing API returned no session shell for a detached create. It must support `deferDataAttachment` (TeamFloPay/backend#1099).","api_error",{code:"InvalidCheckoutSessionResponse"});a=this.normalizeRawSession(this.mergeCachedDisplayData(c.data)),c.vault&&a.data.session&&(a.data.session.vault=this.toVaultBlock(c.vault))}catch(v){throw n.clear(),l&&(0,u.markSessionResponseReceived)(v),this.reportSessionCreateFailure(v,r,o),v}let m=a.data.session?.id??c.data.uuid??"",y=a.data.session?.clientSecret??c.data.nonce??"";if(!m||!y){n.clear();let v=new u.FloPayError("Checkout session shell was created without a session id or nonce.","api_error",{code:"InvalidCheckoutSessionResponse"});throw this.reportSessionCreateFailure(v,r,o),v}n.clear(),this.adoptDirectTelemetryCheckout(m),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()-r),durationMode:"machine",requestCategory:"session_create",statusClass:o.statusClass,attempt:o.attempt,paymentMethodCategory:"card"});let d=!e.account.email?.trim(),h=O(e.timeoutMs??12e3),p=this.claimCheckoutSession(m,y,d?rr(e,i,s):Je(e,i,s),{params:e,startedAt:r,deadline:h,createAttempt:o.attempt}),C=d?void 0:p,f=(v={})=>{if(C!==void 0)return C;let S={...e,account:{...e.account,...v,email:v.email?.trim()||e.account.email?.trim()}};return(0,u.isValidEmail)(S.account.email)?(C=p.then(()=>{let g=this.telemetryTimestamp();return this.claimCheckoutSession(m,y,nr(S.account),{params:S,startedAt:g,deadline:O(e.timeoutMs??12e3),createAttempt:0})}),C.catch(()=>{}),C):Promise.reject(new u.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}))};return p.catch(()=>{}),{shell:a,sessionId:m,nonce:y,claimed:p,claim:f}}async claimCheckoutSession(e,r,n,o){let s=o?.startedAt??this.telemetryTimestamp(),i=this.telemetryTimestamp(),a=o?.deadline??O(12e3),c=JSON.stringify(n),l="unknown",m=0,y=!1;this.directTelemetry?.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"});try{let d;for(m=0;m<3;m++){try{d=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/claim`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":r,[u.FLO_SDK_VERSION_HEADER]:u.SDK_VERSION},body:c,signal:a.signal})}catch(C){let f=a.signal.aborted||C instanceof Error&&C.name==="AbortError";if(l=f?"timeout":"network_error",f||m>=2)throw C;try{this.telemetryHooks?.onRetry?.("session_claim",m+1),this.directTelemetry?.log({name:"operation.retry",stage:"session_claim",requestCategory:"session_claim",attempt:m+1})}catch{}await G(m,a.signal);continue}if(l=(0,u.telemetryStatusClass)(d.status),d.ok)break;throw await L(d,"Failed to attach checkout session data")}if(!d)throw new TypeError("Checkout-session claim exhausted its retry budget.");y=!0;let h=await d.json();if(!h.data?.gateways)throw new u.FloPayError("The billing API returned no checkout session with gateways after claiming it.","api_error",{code:"InvalidCheckoutSessionResponse"});o?.params&&this.autoCacheDisplayData(h.data.uuid??e,o.params);let p=this.normalizeRawSession(this.mergeCachedDisplayData(h.data));return h.vault&&p.data.session&&(p.data.session.vault=this.toVaultBlock(h.vault)),this.directTelemetry?.log({name:"session.claim.completed",stage:"session_claim",requestCategory:"session_claim",statusClass:l}),this.directTelemetry?.performance({stage:"session_claim",durationMs:Math.max(0,this.telemetryTimestamp()-i),durationMode:"machine",requestCategory:"session_claim",statusClass:l,attempt:m}),this.directTelemetry?.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:l}),this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"session_create",statusClass:l,attempt:o?.createAttempt??m}),p}catch(d){throw y&&(0,u.markSessionResponseReceived)(d),this.reportSessionCreateFailure(d,i,{attempt:m,statusClass:l},"session_claim"),d}finally{a.clear()}}reportSessionCreateFailure(e,r,n,o="session_create"){if(!(e instanceof u.FloPayError&&e.code==="session_auto_completed"))try{this.telemetryHooks?.onSessionCreateFailure?.(e)}catch{}let s=(0,u.classifyTelemetryFailure)(e,"CHECKOUT_SESSION_CREATE_FAILED");if(this.directTelemetry?.performance({stage:o,durationMs:Math.max(0,this.telemetryTimestamp()-r),durationMode:"machine",requestCategory:o==="session_claim"?"session_claim":"session_create",statusClass:s.statusClass,attempt:n.attempt}),e instanceof u.FloPayError&&e.type==="validation_error"||e instanceof u.FloPayError&&We(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 u.FloPayError&&e.code==="session_auto_completed"||this.directTelemetry?.error({...s,stage:o,requestCategory:o==="session_claim"?"session_claim":"session_create"})}reportThreeDsAbandoned(e){this.beginDirectTelemetryCheckout(e),this.directTelemetry?.terminal({outcome:"customer_abandoned",stage:"three_ds_handoff",paymentMethodCategory:"saved"})}async waitForCheckoutSessionCompletion(e,r){this.beginDirectTelemetryCheckout(e);let n=this.telemetryTimestamp(),o=r?.paymentMethodCategory??"saved";this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:o});let s=r?.timeoutMs??ge,i=Date.now()+s,a=new AbortController,c=!1,l,m=setTimeout(()=>{l=setTimeout(()=>{c=!0,a.abort()},Ge)},s),y=()=>a.abort(r?.signal?.reason);r?.signal?.aborted?y():r?.signal?.addEventListener("abort",y,{once:!0});let d=this.clampRetryAfterMs(r?.initialDelayMs??Ke),h=0;try{if(r?.statusUrl){let p=await this.waitForCheckoutStatus(e,{initialDelayMs:d,timeoutMs:s,nonce:r.nonce,statusUrl:r.statusUrl,pollAfterAction:r.continueAfterActionRequired,signal:a.signal});if(p){let C=await this.resolveCheckoutSessionStatus(e,p,r.nonce,a.signal,()=>c);return this.reportRecoveryCompleted(n,o),C}}for(;;){let p=i-Date.now();if(p<=0)throw I();if(d>0){try{h+=1,this.telemetryHooks?.onRetry?.("session_read",h),this.directTelemetry?.log({name:"operation.retry",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:o,attempt:h})}catch{}if(await ke(Math.min(d,p),a.signal),Date.now()>=i)throw I()}let C=await this.getUnifiedCheckoutSessionForRecovery(e,r?.nonce,a.signal),f=C.data.session?.status;if(f==="authorized"||f==="complete"||f==="expired")return this.reportRecoveryCompleted(n,o),C;if(Date.now()>=i)throw I();d=this.clampRetryAfterMs(Math.max(d*2,$e))}}catch(p){let C=c&&Ae(p)?I():p;throw this.reportDirectFailure(C,"RECOVERY_FAILED","recovery","session_read",o),C}finally{clearTimeout(m),clearTimeout(l),r?.signal?.removeEventListener("abort",y)}}reportRecoveryCompleted(e,r){let n={stage:"recovery",requestCategory:"session_read",paymentMethodCategory:r};this.directTelemetry?.log({name:"operation.recovery.completed",...n}),this.directTelemetry?.performance({...n,durationMs:Math.max(0,this.telemetryTimestamp()-e),durationMode:"machine"})}async resolveCheckoutSessionStatus(e,r,n,o,s){let i=r.latestTransactionAttempt;if(this.rememberReportedFailure(e,r),i?.result==="DECLINE"){let l=i.code===u.STORED_PAYMENT_METHOD_UNSUPPORTED_CODE;throw new u.FloPayError(l?u.STORED_PAYMENT_METHOD_UNSUPPORTED_MESSAGE:"Payment was declined. Please choose another payment method.","api_error",{code:i.code??i.declineReason??"authorization_declined",statusCode:400})}if(i?.result==="ERROR"||r.status==="voided")throw new u.FloPayError("Payment could not be completed. Please try again.","api_error",{code:i?.code??"payment_processing_error",statusCode:500});let a;try{a=await this.getUnifiedCheckoutSessionForRecovery(e,n,o)}catch(l){if(!s?.()||!Ae(l))throw l;a={providers:[],mode:"tokenize",data:{},raw:r}}let c=a.data.session;return c&&i?.result==="SUCCESS"?{...a,data:{...a.data,session:{...c,status:"complete"}}}:c&&i?.result==="AUTHORIZED"?{...a,data:{...a.data,session:{...c,status:"authorized",paymentId:r.paymentId??void 0,authorizationExpiresAt:r.authorizationExpiresAt??void 0}}}:c&&r.status==="completed"?{...a,data:{...a.data,session:{...c,status:"complete"}}}:c&&r.status==="authorized"?{...a,data:{...a.data,session:{...c,status:"authorized",paymentId:r.paymentId??void 0,authorizationExpiresAt:r.authorizationExpiresAt??void 0}}}:c&&r.status==="expired"?{...a,data:{...a.data,session:{...c,status:"expired"}}}:i?.result!=="ACTION_REQUIRED"?a:i.gateway==="paypal"&&i.providerIntentId?{...a,autoProcessingError:{type:"paypal_direct_required",message:"PayPal authorization required",orderId:i.providerIntentId,checkoutMethod:"paypal"}}:i.nextActionRedirectUrl?{...a,autoProcessingError:{type:"3ds_required",message:"Additional authentication is required.",nextActionRedirectUrl:i.nextActionRedirectUrl}}:a}async waitForCheckoutStatus(e,r){let n=r.timeoutMs??ge,o=Date.now()+n,s=this.clampRetryAfterMs(r.initialDelayMs);for(;;){let i=o-Date.now();if(i<=0||s>0&&(await ke(Math.min(s,i),r.signal),Date.now()>=o))throw I();let a=o-Date.now();if(a<=0)throw I();let c=new AbortController,l,m=r.signal?new Promise((S,g)=>{l=g}):null,y=()=>{c.abort(r.signal?.reason),l?.(r.signal?.reason??Object.assign(new Error("The operation was aborted."),{name:"AbortError"}))};r.signal?.aborted?y():r.signal?.addEventListener("abort",y,{once:!0});let d,h=r.signal?null:new Promise((S,g)=>{d=setTimeout(()=>{g(I()),c.abort()},a+Ge)}),p;try{let S=this.fetchCheckoutStatus(e,r.nonce,r.statusUrl,c.signal);p=await Promise.race([S,h,m].filter(g=>g!==null))}finally{d!==void 0&&clearTimeout(d),r.signal?.removeEventListener("abort",y)}if(!p)return null;let C=He(p.latestTransactionAttempt)&&!this.isOwnFailedAttempt(e,p,r.submittedIntentId);if(p.status==="completed"||p.status==="authorized"||p.status==="expired"||p.status==="voided")return C?{...p,latestTransactionAttempt:null}:p;let f=p.latestTransactionAttempt?.result,v=r.pollAfterAction===!0&&f==="ACTION_REQUIRED";if(!C&&f!==void 0&&f!=="PENDING"&&!v)return p;s=this.clampRetryAfterMs(Math.max(s*2,$e))}}isOwnFailedAttempt(e,r,n){let o=r.latestTransactionAttempt?.providerIntentId??null;return n!==void 0?o===n:o===null?!0:!jt(r.uuid||e,o)}rememberReportedFailure(e,r){let n=r.latestTransactionAttempt;!He(n)||!n.providerIntentId||Ht(r.uuid||e,n.providerIntentId)}async fetchCheckoutStatus(e,r,n,o){let s=`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/status`,i=s;if(n)try{let m=new URL(n,`${this.baseUrl}/`),y=new URL(s);m.origin===y.origin&&(i=m.toString())}catch{}let a={[u.FLO_SDK_VERSION_HEADER]:u.SDK_VERSION};r&&(a["x-checkout-session-token"]=r);let c=await fe(i,{headers:a,signal:o});if(c.status===404||c.status===405)return null;if(!c.ok)throw await L(c,"Failed to get checkout session status");let l=await c.json();return ne(l.data)&&"latestTransactionAttempt"in l.data?l.data:null}normalizeRawSession(e){let r=e.gateways??{},n=[],o={session:this.toCheckoutSession(e)},s=r.stripe;if(s?.publishableKey){n.push("stripe");let c=[e.stripeClientSecret,s.stripeClientSecret].find(l=>typeof l=="string"&&l.length>0);o.stripe={clientSecret:c??"",publishableKey:s.publishableKey??void 0,paypalPublishableKey:s.paypalPublishableKey??void 0,environment:s.environment,enabledPaymentMethods:Array.isArray(s.enabledPaymentMethods)?s.enabledPaymentMethods.filter(l=>typeof l=="string"):void 0}}let i=r.paypal;return i?.publishableKey&&(n.push("paypal"),o.paypal={publishableKey:i.publishableKey,environment:i.environment,providerObjectType:i.providerObjectType,approvalPresentation:i.approvalPresentation}),{providers:n,mode:"tokenize",...e.checkoutMetadata===void 0?{}:{checkoutMetadata:e.checkoutMetadata},data:o,raw:{data:e}}}toCheckoutSession(e){let r=e.products??[],n=typeof e.totalAmount=="number"&&Number.isFinite(e.totalAmount),o=r.reduce((l,m)=>l+(m.overrideAmount??m.totalAmount??0),0),s=n?e.totalAmount:o,i=Math.round(s*100),a=e.currency??r[0]?.currency??"USD",c="payment";return e.checkoutMode==="setup"?c="setup":r.some(l=>l.type==="subscription")&&(c="subscription"),{id:e.uuid,clientSecret:e.nonce,mode:c,status:this.toCheckoutSessionStatus(e.status),amount:i,currency:a,captureMethod:e.captureMethod,paymentId:e.paymentId,authorizationExpiresAt:e.authorizationExpiresAt,failureOutcome:(0,u.normalizeCheckoutFailureOutcome)(e.outcome)??(0,u.normalizeCheckoutFailureOutcome)(e.failureReason)??(e.status==="expired"&&e.captureMethod==="manual"?"authorization_expired":void 0),customer:{id:e.accountData.userId??void 0,email:e.accountData.email??void 0,firstName:e.accountData.firstName??void 0,lastName:e.accountData.lastName??void 0,country:e.accountData.country??void 0,city:e.accountData.city??void 0,state:e.accountData.state??void 0,zip:e.accountData.zip??void 0,gender:e.accountData.gender??void 0,line1:e.accountData.addressLine1??void 0,line2:e.accountData.addressLine2??void 0},...e.checkoutMetadata===void 0?{}:{checkoutMetadata:e.checkoutMetadata},metadata:{},checkoutMode:e.checkoutMode,...Array.isArray(e.advertisedPaymentMethods)?{advertisedPaymentMethods:e.advertisedPaymentMethods}:{},...Lt(e.futureUse)?{futureUse:e.futureUse}:{},...Array.isArray(e.futureUseUnsupported)?{futureUseUnsupported:e.futureUseUnsupported.filter(Nt)}:{},buyerIdentified:e.buyerIdentified,providerPaymentMethodId:typeof e.providerPaymentMethodId=="string"?e.providerPaymentMethodId:null,products:r.map(l=>({...l,totalAmount:typeof l.totalAmount=="number"?l.totalAmount:void 0,overrideAmount:typeof l.overrideAmount=="number"?l.overrideAmount:null,currency:typeof l.currency=="string"?l.currency:void 0,metadata:l.metadata??null})),successUrl:e.successUrl,cancelUrl:e.cancelUrl,coupons:e.coupons,subtotalAmount:e.subtotalAmount,discountAmount:e.discountAmount,totalAmount:e.totalAmount,createdAt:e.createdAt,gateways:e.gateways,accountData:e.accountData,tagsData:e.tagsData}}toVaultBlock(e){let r=Qt(e.verification);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,...r?{verification:r}:{}}}toCheckoutSessionStatus(e){return e==="completed"?"complete":e==="authorized"?"authorized":e==="expired"?"expired":"open"}async resolveProcessResponse(e,r,n){if(e.status!==202)return e;let o=await e.json().catch(()=>null),s=this.toCheckoutProcessingPending(o,e,r);return this.resolveCheckoutProcessing(s,r,n)}async resolveCheckoutProcessing(e,r,n){let o=n?.pollTimeoutMs??ge,s=Date.now()+o;if(e.statusUrl){let a=await this.waitForCheckoutStatus(e.sessionId,{initialDelayMs:e.retryAfterMs,timeoutMs:o,nonce:n?.nonce,statusUrl:e.statusUrl,submittedIntentId:n?.submittedIntentId});if(a)return this.toProcessResponseFromStatus(a,r,n?.nonce)}let i=await this.waitForCheckoutSessionCompletion(e.sessionId,{initialDelayMs:e.retryAfterMs,timeoutMs:s-Date.now(),nonce:n?.nonce,paymentMethodCategory:n?.paymentMethodCategory});return this.toProcessResponseFromSession(i,r)}async toProcessResponseFromStatus(e,r,n){let o=e.latestTransactionAttempt?.result,s={[Vt]:zt},i={"Content-Type":"application/json",...s};if(e.status==="completed"||o==="SUCCESS")return new Response(null,{status:204,statusText:"No Content",headers:s});if(e.status==="authorized"||o==="AUTHORIZED")return new Response(JSON.stringify({status:"authorized",paymentId:e.paymentId??void 0,sessionId:e.uuid||r,authorizationExpiresAt:e.authorizationExpiresAt??void 0}),{status:200,headers:i});if(e.status==="expired"){let a=await this.resolveCheckoutSessionStatus(r,e,n);return this.toProcessResponseFromSession(a,r)}if(this.rememberReportedFailure(r,e),o==="DECLINE"){let a=e.latestTransactionAttempt,c=a?.code===u.STORED_PAYMENT_METHOD_UNSUPPORTED_CODE,l=a?.declineReason??void 0;return new Response(JSON.stringify({type:l??"authorization_declined",message:c?u.STORED_PAYMENT_METHOD_UNSUPPORTED_MESSAGE:"Payment was declined. Please choose another payment method.",code:a?.code??l??"authorization_declined",...l?{declineCode:l}:{}}),{status:400,headers:i})}if(o==="ACTION_REQUIRED"&&e.latestTransactionAttempt?.gateway==="paypal"&&e.latestTransactionAttempt.providerIntentId)return new Response(JSON.stringify({type:"paypal_direct_required",message:"PayPal authorization required",orderId:e.latestTransactionAttempt.providerIntentId}),{status:400,headers:i});if(o==="ACTION_REQUIRED"&&e.latestTransactionAttempt?.nextActionRedirectUrl)return new Response(JSON.stringify({type:"3ds_required",message:"Additional authentication is required.",nextActionRedirectUrl:e.latestTransactionAttempt.nextActionRedirectUrl}),{status:400,headers:i});if(o==="ERROR"||e.status==="voided")return new Response(JSON.stringify({type:"unknown",code:e.latestTransactionAttempt?.code??"payment_processing_error",message:"Payment could not be completed. Please try again."}),{status:500,headers:i});throw I()}async reconcileProcessPayment(e,r){let n=r?.pollTimeoutMs??ge,o=Date.now()+n,s=null;try{s=await this.waitForCheckoutStatus(e,{initialDelayMs:0,timeoutMs:n,nonce:r?.nonce,submittedIntentId:r?.submittedIntentId})}catch(c){if(this.reportDirectFailure(c,"RECOVERY_FAILED","recovery","session_read",r?.paymentMethodCategory??"saved"),c instanceof u.FloPayError&&c.code==="checkout_processing_timeout")throw c}if(s)return this.toProcessResponseFromStatus(s,e,r?.nonce);let i=o-Date.now();if(i<=0)throw I();let a=await this.waitForCheckoutSessionCompletion(e,{initialDelayMs:0,timeoutMs:i,nonce:r?.nonce,paymentMethodCategory:r?.paymentMethodCategory});return this.toProcessResponseFromSession(a,e)}toProcessResponseFromSession(e,r){if(e.data.session?.status==="complete")return new Response(null,{status:204,statusText:"No Content"});if(e.data.session?.status==="authorized"){let n=e.data.session;return new Response(JSON.stringify({status:"authorized",paymentId:n.paymentId,sessionId:n.id||r,authorizationExpiresAt:n.authorizationExpiresAt}),{status:200,headers:{"Content-Type":"application/json"}})}if(e.data.session?.status==="expired"){let n=e.data.session.failureOutcome==="authorization_expired"||e.data.session.captureMethod==="manual";throw new u.FloPayError(n?"Authorization has expired.":"Checkout session has expired.","api_error",{code:n?"authorization_expired":"checkout_session_expired"})}throw I()}toCheckoutProcessingPending(e,r,n){let o=r.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:N(e,"sessionId")??n,retryAfterMs:this.clampRetryAfterMs(Wt(e,"retryAfterMs")??i??Ke),statusUrl:N(e,"statusUrl"),sessionUrl:N(e,"sessionUrl")}}clampRetryAfterMs(e){return Math.max(0,Math.min(e,$t))}autoCacheDisplayData(e,r){if(!e)return;let n=r.products??(0,u.foldIntoProducts)(r.items,r.subscriptions);if(n.length===0&&!r.currency)return;let o=r.products!==void 0,s=(0,u.resolveSessionCurrency)(r.currency,o?void 0:r.items,o?void 0:r.subscriptions,n);z(e,{currency:s??void 0,products:n.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 r=pe(e.uuid),n=new Map,o=i=>i?`code:${i}`:void 0;for(let i of r?.products??[]){let a=o(i.code);a&&n.set(a,i)}let s=(e.products??[]).map(i=>{let a=o(i.code),c=a?n.get(a):void 0;return{...i,name:i.name??c?.name??null,totalAmount:i.totalAmount??c?.totalAmount,overrideAmount:i.overrideAmount??c?.overrideAmount,currency:i.currency??c?.currency}});return{...e,currency:e.currency??r?.currency,products:s}}};j.activeVaultCaptureRequests=new Map;var oe=j;function Ze(t,e){let r=oe;return new r(t,e)}var b=require("@flopay/shared");var Me="flopay-vault",or=3e4,sr=b.THREE_DS_CHALLENGE_WINDOW_MS+or,ir="Card authentication timed out.",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 ar(t){return t.class==="lifecycle"?t.name:t.class==="technical_error"?t.code:t.class==="expected_outcome"?t.outcome:"sdk.performance"}function J(t){let e={class:t.class,stage:t.stage};"code"in t&&(e.code=t.code),"provider"in t&&t.provider&&(e.provider=t.provider),"paymentMethodCategory"in t&&t.paymentMethodCategory&&(e.paymentMethodCategory=t.paymentMethodCategory),"outcome"in t&&(e.outcome=t.outcome),"durationMs"in t&&t.durationMs!==void 0&&(e.durationMs=t.durationMs),"durationMode"in t&&t.durationMode&&(e.durationMode=t.durationMode);try{globalThis.Sentry?.addBreadcrumb?.({category:"flopay.telemetry",level:t.class==="technical_error"?"error":"info",message:ar(t),data:e})}catch{}}function se(t,e){return(0,b.buildTelemetryLogEvent)({eventId:"11111111-1111-4111-8111-111111111111",name:t,stage:e,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}var cr=new Set(["authorization_declined","authentication_required","authorization_expired","capture_failed"]);function lr(t){return typeof t=="string"&&cr.has(t)?t:"unknown"}var ur=new Set(["verification_failed","verification_expired"]);function dr(t){return t==null?!0:typeof t=="string"&&ur.has(t)}function tt(t,e){return t?{errorCode:"VAULT_SUBMIT_FAILED",stage:"vault_submit",failureCategory:"provider_runtime",reason:lr(e.failureOutcome)}:{errorCode:"VAULT_LOAD_FAILED",stage:"vault_mount",failureCategory:"provider_runtime"}}function rt(t,e,r="checkout"){return r==="card_setup"?t.type==="decline"?"card_setup_declined":"card_setup_succeeded":t.type==="decline"?"payment_declined":t.outcome==="authorized"||e==="manual"?"payment_authorized":"payment_succeeded"}function mr(t,e,r,n="checkout"){let{type:o}=t;if(o==="complete"||o==="decline")return(0,b.buildTelemetryTerminalEvent)({eventId:"22222222-2222-4222-8222-222222222222",outcome:rt(t,r,n),sequence:0,provider:"pcivault",paymentMethodCategory:"card"});if(o==="error"){let a=tt(e,t);return(0,b.buildTelemetryErrorEvent)({eventId:"33333333-3333-4333-8333-333333333333",...a,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}let[s,i]=et[o];return se(s,i)}function pr(t){if(typeof t!="object"||t===null)return!1;let e=t;return e.source===Me&&(e.type==="ready"||e.type==="submitting"||e.type==="blocked"||e.type==="complete"||e.type==="decline"||e.type==="error"||e.type==="action_required")}function yr(t){if(typeof t!="object"||t===null)return;let e=t,r=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||r!=="pending"&&r!=="active"&&r!=="deleted"))return{id:e.id,brand:e.brand,lastFour:e.lastFour,expiryMonth:e.expiryMonth,expiryYear:e.expiryYear,status:r}}function hr(t){if(typeof t!="object"||t===null)return!1;let e=t;return e.source===Me&&e.type==="validation"&&Array.isArray(e.messages)}function gr(t){if(typeof t!="object"||t===null)return!1;let e=t;return e.source===Me&&e.type==="resize"&&typeof e.height=="number"&&Number.isFinite(e.height)}var H=class{constructor(e={},r){this.provider="pcivault";this.container=null;this.messageHandler=null;this.actionOverlay=null;this.threeDsReturnHandler=null;this.actionOverlayPreviousFocus=null;this.actionOverlayTimer=null;this.messageToken=null;this.expectedOrigin=null;this.theme=void 0;this.submitGateBlocked=!1;this.cardFieldOrder=null;this.cardAutoFocus=!0;this.submitLabel=void 0;this.mountStartedAt=0;this.vaultReadyReported=!1;this.verificationRequired=!1;this.submissionStarted=!1;this.submissionStartedAt=null;this.listeners=new Map;this.config=e,this.ownsTelemetryReporter=!r&&e.telemetry!==!1,this.telemetryReporter=r?.reporter??(this.ownsTelemetryReporter?new w({billingApiUrl:(0,b.resolveBillingApiUrl)(e.billingApiUrl),sdkVersion:b.SDK_VERSION}):void 0)}async mount(e,r){this.ownsTelemetryReporter&&!this.telemetryReporter&&(this.telemetryReporter=new w({billingApiUrl:(0,b.resolveBillingApiUrl)(this.config.billingApiUrl),sdkVersion:b.SDK_VERSION}));let n=this.telemetryReporter;if(this.config.operation==="card_setup"&&n&&this.setupTelemetryReporter!==n){this.setupTelemetryReporter=n;try{n.beginCheckout({checkoutMode:"setup"})}catch{}}if(this.mountStartedAt=this.telemetryReporter?.now?.()??A(),this.vaultReadyReported=!1,this.submissionStarted=!1,this.submissionStartedAt=null,typeof window>"u"||typeof document>"u")throw this.reportVaultLoadFailure(),new b.FloPayError("The vault card form is only available in the browser.","api_error",{code:"card_capture_no_window"});if(!r?.html?.trim())throw this.reportVaultLoadFailure(),new b.FloPayError("No vault capture widget HTML was provided to mount the secure card form.","api_error",{code:"card_capture_no_widget_html"});this.container=e,this.verificationRequired=r.verificationRequired===!0,this.messageToken=r.messageToken??null,this.expectedOrigin=r.expectedOrigin??this.config.expectedOrigin??null,this.theme=r.theme,r.submitLabel!==void 0&&(this.submitLabel=r.submitLabel);try{this.attachMessageListener(),this.injectWidget(e,r.html)}catch(o){throw this.reportVaultLoadFailure(),o}this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),this.postSubmitLabel(),J(se("vault.widget.mounted","vault_mount")),this.telemetryReporter?.log({name:"vault.widget.mounted",stage:"vault_mount",provider:"pcivault",paymentMethodCategory:"card"}),this.telemetryReporter?.performance?.({stage:"vault_mount",durationMs:Math.max(0,(this.telemetryReporter.now?.()??A())-this.mountStartedAt),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card"}),this.emit("ready",{sessionId:this.config.sessionId})}reportVaultLoadFailure(){this.telemetryReporter?.error({errorCode:"VAULT_LOAD_FAILED",failureCategory:"provider_runtime",stage:"vault_mount",provider:"pcivault",paymentMethodCategory:"card"})}on(e,r){let n=this.listeners.get(e);return n||(n=new Set,this.listeners.set(e,n)),n.add(r),()=>{this.listeners.get(e)?.delete(r)}}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,r){e.innerHTML=r;let n=Array.from(e.querySelectorAll("script"));for(let o of n){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=r=>{if(this.expectedOrigin&&r.origin!==this.expectedOrigin)return;let n=r.data;if(gr(n)){if(this.messageToken&&n.messageToken!==this.messageToken)return;this.applyHeight(n.height);return}if(hr(n)){if(this.messageToken&&n.messageToken!==this.messageToken)return;let c=n.messages.filter(l=>typeof l=="string"&&l.trim()).join(" ");this.emit("validation",{sessionId:this.config.sessionId,message:c||void 0});return}if(!pr(n)||this.messageToken&&n.messageToken!==this.messageToken)return;let o=this.config.sessionId,s=typeof n.sessionId=="string"?n.sessionId:void 0;if(o&&s&&s!==o||(n.type==="complete"||n.type==="decline")&&o&&s!==o)return;let i=yr(n.paymentMethod),a={...n.sessionId??this.config.sessionId?{sessionId:n.sessionId??this.config.sessionId}:{},...n.outcome?{outcome:n.outcome}:{},...n.paymentId?{paymentId:n.paymentId}:{},...n.authorizationExpiresAt?{authorizationExpiresAt:n.authorizationExpiresAt}:{},...n.failureOutcome?{failureOutcome:n.failureOutcome}:{},...n.intentId?{intentId:n.intentId}:{},...n.declineReason?{declineReason:n.declineReason}:{},...n.message?{message:n.message}:{},...i?{paymentMethod:i}:{}};n.type==="submitting"&&(this.submissionStarted=!0,this.submissionStartedAt=this.telemetryReporter?.now?.()??A()),this.isVerificationStateError(n)?(J(se("operation.state_transition","vault_mount")),this.telemetryReporter?.log({name:"operation.state_transition",stage:"vault_mount",provider:"pcivault",paymentMethodCategory:"card"})):(J(mr(n,this.submissionStarted,this.config.captureMethod,this.config.operation)),this.reportOutcome(n)),n.type==="ready"&&(this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),this.postSubmitLabel()),n.type==="action_required"&&n.nextActionRedirectUrl&&this.showActionRequiredOverlay(n.nextActionRedirectUrl),(n.type==="complete"||n.type==="decline"||n.type==="error"||n.type==="submitting")&&this.hideActionRequiredOverlay(),n.type!=="action_required"&&this.emit(n.type,a)};this.messageHandler=e,window.addEventListener("message",e)}isVerificationStateError(e){return e.type==="error"&&this.verificationRequired&&!this.submissionStarted&&dr(e.failureOutcome)}reportOutcome(e){let r=this.telemetryReporter;if(!r)return;let{type:n}=e;if(n==="ready"&&!this.vaultReadyReported&&(this.vaultReadyReported=!0,r.performance({stage:"vault_ready",durationMs:Math.max(0,r.now()-this.mountStartedAt),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card",requestCategory:"provider_sdk"})),n==="complete"||n==="decline"){r.log({name:"vault.terminal",stage:"completion",provider:"pcivault",paymentMethodCategory:"card"}),r.terminal({outcome:rt(e,this.config.captureMethod,this.config.operation),provider:"pcivault",paymentMethodCategory:"card"});return}if(n==="error"){let i=tt(this.submissionStarted,e);r.log({name:"vault.terminal",stage:i.stage,provider:"pcivault",paymentMethodCategory:"card"}),r.error({...i,provider:"pcivault",paymentMethodCategory:"card"});return}if(n==="action_required"){r.log({name:"vault.action.required",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"}),r.log({name:"vault.three_ds.handoff",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"});let i=this.submissionStartedAt;this.submissionStartedAt=null,i!==null&&r.performance({stage:"three_ds_handoff",durationMs:Math.max(0,r.now()-i),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card"}),r.terminal({outcome:"action_required",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"});return}let[o,s]=et[n];r.log({name:o,stage:s,provider:"pcivault",paymentMethodCategory:"card"})}applyTheme(e){this.theme=e,this.postTheme()}postTheme(){this.theme!==void 0&&this.postToHostedWindow({source:"flopay-vault-host",type:"theme",theme:this.theme},this.directiveTargetOrigin())}setSubmitGate(e){this.submitGateBlocked=e,this.postSubmitGate()}postSubmitGate(){this.postToHostedWindow({source:"flopay-vault-host",type:"gate",blocked:this.submitGateBlocked},this.directiveTargetOrigin())}setCardFieldOrder(e,r){this.cardFieldOrder=e,this.cardAutoFocus=r,this.postCardFieldOrder()}postCardFieldOrder(){this.postToHostedWindow({source:"flopay-vault-host",type:"fieldOrder",order:this.cardFieldOrder,autoFocus:this.cardAutoFocus},this.directiveTargetOrigin())}setSubmitLabel(e){this.submitLabel=e,this.postSubmitLabel()}postSubmitLabel(){let e=this.submitLabel,r=this.config.sessionId,{messageToken:n,expectedOrigin:o}=this;e===void 0||!r||!n||!o||this.postToHostedWindow({source:"flopay-vault-host",type:"submitLabel",sessionId:r,messageToken:n,label:e},o)}hostedWindow(){return this.container?.querySelector("iframe")?.contentWindow??null}postToHostedWindow(e,r){let n=this.hostedWindow();if(n)try{n.postMessage(e,r)}catch{}}directiveTargetOrigin(){return this.expectedOrigin??"*"}emit(e,r){for(let n of this.listeners.get(e)??[])n(r)}showActionRequiredOverlay(e){if(typeof document>"u")return;if(this.actionOverlay){let i=this.actionOverlay.querySelector("iframe");i instanceof HTMLIFrameElement&&i.src!==e&&(i.src=e),this.armActionRequiredTimeout();return}this.actionOverlayPreviousFocus=document.activeElement instanceof HTMLElement?document.activeElement:null;let r=document.createElement("div");r.setAttribute("data-flopay-action-required","1"),r.setAttribute("role","dialog"),r.setAttribute("aria-modal","true"),r.setAttribute("aria-label","Card authentication"),r.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 n=document.createElement("iframe");n.setAttribute("title","Card authentication"),n.setAttribute("allow","payment"),n.tabIndex=0,n.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(";"),n.src=e,r.appendChild(n);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()),r.appendChild(o),r.addEventListener("click",i=>{i.target===r&&this.abandonActionRequiredOverlay()});let s=i=>{if(i.source!==n.contentWindow)return;let a=i.data;!a||typeof a!="object"||a.source!=="flopay-vault-3ds-return"||(J(se("vault.three_ds.returned","three_ds_return")),this.telemetryReporter?.log({name:"vault.three_ds.returned",stage:"three_ds_return",provider:"pcivault",paymentMethodCategory:"card"}),this.hideActionRequiredOverlay())};window.addEventListener("message",s),this.threeDsReturnHandler=s,document.body.appendChild(r),this.actionOverlay=r,n.focus(),this.armActionRequiredTimeout(),J(se("vault.three_ds.handoff","three_ds_handoff"))}armActionRequiredTimeout(){this.actionOverlayTimer&&clearTimeout(this.actionOverlayTimer),this.actionOverlayTimer=setTimeout(()=>{this.actionOverlayTimer=null,this.actionOverlay&&this.timeOutActionRequiredOverlay()},sr)}reportChallengeAbandoned(){J((0,b.buildTelemetryTerminalEvent)({eventId:"77777777-7777-4777-8777-777777777777",outcome:"customer_abandoned",stage:"three_ds_handoff",sequence:0,provider:"pcivault",paymentMethodCategory:"card"})),this.telemetryReporter?.terminal({outcome:"customer_abandoned",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"})}timeOutActionRequiredOverlay(){this.reportChallengeAbandoned(),this.hideActionRequiredOverlay(),this.emit("error",{...this.config.sessionId?{sessionId:this.config.sessionId}:{},message:ir})}abandonActionRequiredOverlay(){this.actionOverlay&&(this.reportChallengeAbandoned(),this.hideActionRequiredOverlay(),this.emit("challenge_dismissed",{...this.config.sessionId?{sessionId:this.config.sessionId}:{}}))}hideActionRequiredOverlay(){if(this.actionOverlayTimer&&(clearTimeout(this.actionOverlayTimer),this.actionOverlayTimer=null),this.threeDsReturnHandler&&(window.removeEventListener("message",this.threeDsReturnHandler),this.threeDsReturnHandler=null),!this.actionOverlay)return;this.actionOverlay.parentNode?.removeChild(this.actionOverlay),this.actionOverlay=null;let e=this.actionOverlayPreviousFocus;this.actionOverlayPreviousFocus=null,e?.isConnected&&e.focus()}applyHeight(e){let r=this.container?.querySelector("iframe");if(!r)return;let n=Math.max(0,Math.min(Math.ceil(e),2e3));r.style.height=`${n}px`}};function nt(t,e){let r=H;return new r(t,{reporter:e})}var ot=Symbol.for("@flopay/js.telemetry.bridge.v1");function st(t,e,r){let n=()=>e?.now()??r();Object.defineProperty(t,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:n,elapsed:s=>Math.max(0,n()-s),setCheckoutContext:s=>e?.setCheckoutContext(s),beginCheckout:(s={})=>e?.beginCheckout(s)??n(),disable:()=>e?.disable(),subscribe:s=>e?.subscribe(s)??(()=>{}),flush:()=>e?.flush()??Promise.resolve()}})}function it(t){return t[ot]}var ie=class{now(){return this.telemetryReporter?.now?.()??A()}constructor(e,r,n){this.provider=e,this.config=r,this.telemetryReporter=n??new w({billingApiUrl:(0,k.resolveBillingApiUrl)(r.billingApiUrl),sdkVersion:k.SDK_VERSION,enabled:r.telemetry!==!1}),st(this,this.telemetryReporter,A)}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 H({sessionId:e?.sessionId,captureMethod:e?.captureMethod,telemetry:!1})}async retrieveSession(e,r){if(!e)throw new k.FloPayError("sessionId is required to retrieve a session.","validation_error",{param:"sessionId"});let n=await this.retrieveUnifiedSession(e,r);if(!n.data.session)throw new k.FloPayError("Session not found","api_error");return n.data.session}async retrieveUnifiedSession(e,r){if(!e)throw new k.FloPayError("sessionId is required.","validation_error",{param:"sessionId"});let n=(0,k.resolveBillingApiUrl)(r??this.config.billingApiUrl),o=this.now();this.telemetryReporter?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let s,i,a=l=>{if(s===void 0)return;let m=s,y=i;s=void 0,i=void 0,this.telemetryReporter?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:l,attempt:y}),this.telemetryReporter?.performance({stage:"session_first_byte",durationMs:m,durationMode:"machine",requestCategory:"session_read",statusClass:l,attempt:y})},c=Ze(n,{now:()=>this.telemetryReporter?.now()??A(),onFirstByte:(l,m)=>{s=l,i=m},onRetry:(l,m)=>{this.telemetryReporter?.log({name:"operation.retry",stage:l==="session_read"?"session_read":"processing",requestCategory:l,attempt:m})}});try{let l=await c.getUnifiedCheckoutSession(e);return a("2xx"),this.telemetryReporter?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:"2xx"}),this.telemetryReporter?.log({name:"checkout.data.ready",stage:"checkout_data_ready"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-o,durationMode:"machine",requestCategory:"session_read",statusClass:"2xx"}),l}catch(l){let m=(0,k.classifyTelemetryFailure)(l,l instanceof k.FloPayError&&l.code==="checkout_processing_timeout"?"REQUEST_TIMEOUT":"NETWORK_REQUEST_FAILED");throw a(m.statusClass),this.telemetryReporter?.error({...m,stage:"session_read",provider:"flo",paymentMethodCategory:"unknown"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-o,durationMode:"machine",requestCategory:"session_read",statusClass:m.statusClass}),l}}getRawProvider(){return this.provider.getRawProvider()}destroy(){this.telemetryReporter?.log({name:"checkout.unmount",stage:"unmount"}),this.telemetryReporter?.destroy(),this.provider.destroy()}};function at(t,e,r){let n=ie;return new n(t,e,r)}var U=require("@flopay/shared");var Ie=require("@flopay/shared"),ct=require("@stripe/stripe-js"),X=require("@flopay/shared"),lt=new WeakSet;function ut(t){return t instanceof Ie.FloPayError&&lt.has(t)}var Q=class{constructor(){this.name="stripe";this.stripe=null}async initialize(e){if(typeof window>"u")return;let r=await(0,ct.loadStripe)(e.publishableKey,{locale:e.locale??"auto"});if(!r){let n=new Ie.FloPayError("Failed to initialize Stripe. Check your publishable key.","authentication_error");throw lt.add(n),n}this.stripe=r}getRawProvider(){return this.stripe}destroy(){this.stripe=null}};var dt=new Map;function Pe(t){return Array.isArray(t)?t.map(Pe):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[r])=>e.localeCompare(r)).map(([e,r])=>[e,Pe(r)])):t}function fr(t,e){return JSON.stringify([t,(0,U.resolveBillingApiUrl)(e?.billingApiUrl),e?.telemetry!==!1,e?.locale??"auto",e?.apiVersion??null,Pe(e?.appearance??null)])}var ve=new Map;async function mt(t,e){if(!t){let a=new w({billingApiUrl:(0,U.resolveBillingApiUrl)(e?.billingApiUrl),sdkVersion:U.SDK_VERSION,enabled:e?.telemetry!==!1});throw a.error({errorCode:"CONFIGURATION_INVALID",stage:"sdk_initialize",paymentMethodCategory:"unknown"}),a.flush().catch(()=>{}).finally(()=>a.destroy()),new U.FloPayError("A publishable key is required to initialize FloPay.","validation_error",{param:"publishableKey"})}let r=fr(t,e),n=dt.get(r);if(n)return e?.telemetry!==!1&&it(n)?.log({name:"sdk.cache.hit",stage:"sdk_initialize"}),n;let o=ve.get(r);if(o)return o;let s={...e,publishableKey:t},i=(async()=>{let a=new w({billingApiUrl:(0,U.resolveBillingApiUrl)(s.billingApiUrl),sdkVersion:U.SDK_VERSION,enabled:s.telemetry!==!1}),c=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 l=new Q,m=a.now();try{await l.initialize(s)}catch(h){throw a.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:ut(h)?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"unknown"}),a.destroy(),h}let y=a.now();a.log({name:"provider.ready",stage:"provider_ready",provider:"stripe"}),a.log({name:"provider.availability.checked",stage:"provider_ready",provider:"stripe"}),a.log({name:"sdk.initialize.ready",stage:"sdk_initialize"}),a.performance({stage:"sdk_initialize",durationMs:y-c,durationMode:"machine",provider:"stripe"}),a.performance({stage:"provider_ready",durationMs:y-m,durationMode:"machine",provider:"stripe"});let d=at(l,s,a);return dt.set(r,d),d})();ve.set(r,i);try{return await i}finally{ve.get(r)===i&&ve.delete(r)}}var V=require("@flopay/shared"),Cr=1e3,vr=1e3,Tr=15e3;function ae(t){return new V.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:t})}function pt(){return new V.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function yt(t){return t.replace(/\/+$/,"")}function br(t){return t.status==="succeeded"||t.status==="authorized"||t.status==="declined"}function Sr(t){if(!t||typeof t!="object")return{status:"unknown"};let e=typeof t.status=="string"?t.status:"unknown",r=typeof t.providerIntentId=="string"?t.providerIntentId:null;switch(e){case"succeeded":case"authorized":case"pending":case"timeout":return{status:e,providerIntentId:r};case"declined":return{status:"declined",providerIntentId:r,declineReason:typeof t.declineReason=="string"?t.declineReason:null,gatewayDeclineReason:typeof t.gatewayDeclineReason=="string"?t.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:r,nextActionRedirectUrl:typeof t.nextActionRedirectUrl=="string"?t.nextActionRedirectUrl:null};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}async function xe(t){if(typeof document>"u"||typeof window>"u")throw new V.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(t.signal?.aborted)throw ae();let e=`${yt(t.billingApiUrl)}/v1/checkouts/sessions/${encodeURIComponent(t.sessionId)}/3ds/complete`,r=async()=>{let l=new AbortController,m=()=>l.abort();t.signal?.aborted?l.abort():t.signal?.addEventListener("abort",m);let y=window.setTimeout(()=>l.abort(),Tr);try{let d=await fetch(e,{method:"POST",headers:{"x-checkout-session-token":t.nonce,"content-type":"application/json"},body:"{}",signal:l.signal});if(!d.ok)return{status:"unknown"};let h=await d.json().catch(()=>null);return Sr(h)}catch{return{status:"unknown"}}finally{window.clearTimeout(y),t.signal?.removeEventListener("abort",m)}},n,o=()=>t.pollCompletionEndpoint!==!1?r():(n??(n=r()),n),s=document.activeElement instanceof HTMLElement?document.activeElement:null,i=document.createElement("div");i.setAttribute("data-flopay-auto-3ds-overlay","1"),i.setAttribute("role","dialog"),i.setAttribute("aria-modal","true"),i.setAttribute("aria-label","Card authentication"),i.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 a=document.createElement("iframe");a.setAttribute("title","Card authentication"),a.setAttribute("allow","payment"),a.tabIndex=0,a.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(";");let c=null;try{c=new URL(t.billingApiUrl,window.location.href).origin}catch{c=null}try{let l=await new Promise((m,y)=>{let d=!1,h=0,p=0,C=0,f=!1,v=()=>{window.clearTimeout(h),window.clearInterval(p),window.clearTimeout(C),window.removeEventListener("message",K),a.removeEventListener("load",g),t.signal?.removeEventListener("abort",P)},S=async()=>{if(!(d||f)){f=!0;try{let E=await o();if(d||!br(E))return;d=!0,v(),m(E)}finally{f=!1}}},g=()=>{t.pollCompletionEndpoint!==!1&&(window.clearTimeout(C),C=window.setTimeout(()=>{S()},250))},P=()=>{d||(d=!0,v(),y(ae()))},K=E=>{if(E.source!==a.contentWindow||c&&E.origin!==c)return;let M=E.data;!M||typeof M!="object"||M.source!=="flopay-vault-3ds-return"||d||(d=!0,v(),m(null))};h=window.setTimeout(()=>{d||(d=!0,v(),y(pt()))},V.THREE_DS_CHALLENGE_WINDOW_MS),t.pollCompletionEndpoint!==!1&&(p=window.setInterval(()=>{S()},vr)),a.addEventListener("load",g),window.addEventListener("message",K),t.signal?.addEventListener("abort",P),a.src=t.nextActionRedirectUrl,i.appendChild(a),document.body.appendChild(i),a.focus(),t.signal?.aborted&&P()});return l||await o()}finally{i.parentNode?.removeChild(i),s?.isConnected&&s.focus()}}function _r(t){return new V.FloPayError("Card was declined.","api_error",{code:t.declineReason??"authorization_declined",...t.gatewayDeclineReason?{declineCode:t.gatewayDeclineReason}:{}})}async function ht(t,e){let r=`${yt(t.billingApiUrl)}/v1/checkouts/sessions/${encodeURIComponent(t.sessionId)}/status`,n=new AbortController,o=new AbortController,s=()=>{n.abort(t.signal?.reason),o.abort(t.signal?.reason)};t.signal?.aborted?s():t.signal?.addEventListener("abort",s,{once:!0});let i=xe({billingApiUrl:t.billingApiUrl,sessionId:t.sessionId,nonce:t.nonce,nextActionRedirectUrl:t.nextActionRedirectUrl,signal:n.signal,pollCompletionEndpoint:!1}),a=e.waitForCheckoutSessionCompletion(t.sessionId,{initialDelayMs:Cr,nonce:t.nonce,statusUrl:r,continueAfterActionRequired:!0,timeoutMs:V.THREE_DS_CHALLENGE_WINDOW_MS+15e3,signal:o.signal});a.catch(()=>{}),i.catch(()=>{});try{let c=await Promise.race([i,a]);if("data"in c)return c;if(c.status==="declined")throw(t.createDeclineError??_r)(c);if(c.status==="timeout")throw pt();return await a}catch(c){throw t.signal?.aborted||c instanceof Error&&c.name==="AbortError"?ae(c):c}finally{t.signal?.removeEventListener("abort",s),n.abort(),o.abort()}}0&&(module.exports={FloPay,PaymentAPI,PciVaultCardCapture,SESSION_CREATE_TELEMETRY,StripeAdapter,cacheSessionDisplayData,clearSessionDisplayData,completeSavedCardNextAction,createCheckoutSession,createCheckoutSessionWithRetries,createSavedCardActionAbortedError,dropThirdPartyOnlyError,getSessionDisplayData,loadFloPay,runSavedCardChallenge,toStripeAppearance,toStripeAppearanceTheme});
1
+ "use strict";var Se=Object.defineProperty;var Ct=Object.getOwnPropertyDescriptor;var vt=Object.getOwnPropertyNames;var Tt=Object.prototype.hasOwnProperty;var bt=(t,e)=>{for(var r in e)Se(t,r,{get:e[r],enumerable:!0})},St=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of vt(e))!Tt.call(t,o)&&o!==r&&Se(t,o,{get:()=>e[o],enumerable:!(n=Ct(e,o))||n.enumerable});return t};var _t=t=>St(Se({},"__esModule",{value:!0}),t);var Er={};bt(Er,{FloPay:()=>ie,PaymentAPI:()=>oe,PciVaultCardCapture:()=>H,SESSION_CREATE_TELEMETRY:()=>Ee,StripeAdapter:()=>J,cacheSessionDisplayData:()=>z,clearSessionDisplayData:()=>ye,completeSavedCardNextAction:()=>ht,createCheckoutSession:()=>Ne,createCheckoutSessionWithRetries:()=>je,createSavedCardActionAbortedError:()=>ae,dropThirdPartyOnlyError:()=>gt.dropThirdPartyOnlyError,getSessionDisplayData:()=>pe,loadFloPay:()=>mt,runSavedCardChallenge:()=>xe,toStripeAppearance:()=>X.toStripeAppearance,toStripeAppearanceTheme:()=>X.toStripeAppearanceTheme});module.exports=_t(Er);var gt=require("@flopay/shared");var T=require("@flopay/shared");function ee(t){return typeof t=="string"&&t.trim()?t:void 0}function te(t){if(typeof t=="string")return t.trim()?t:void 0;if(Array.isArray(t))return t.filter(r=>typeof r=="string"&&r.trim().length>0).join("; ")||void 0}function O(t=12e3){let e=Number.isFinite(t)&&t>=0?t:12e3,r=new AbortController,n=setTimeout(()=>r.abort(),e);return{signal:r.signal,clear:()=>clearTimeout(n)}}function Rt(){return Object.assign(new Error("The operation was aborted."),{name:"AbortError"})}function G(t,e){let r=150*2**t,n=Math.round(r*(.75+Math.random()*.5));return new Promise((o,s)=>{let i,a=()=>e.removeEventListener("abort",c),c=()=>{i!==void 0&&clearTimeout(i),a(),s(Rt())};if(e.aborted){c();return}i=setTimeout(()=>{a(),o()},n),e.addEventListener("abort",c,{once:!0})})}var wt="flopay_session_display:";var de=new Map;function me(t){return`${wt}${t}`}function _e(){if(typeof window>"u")return null;try{return window.sessionStorage}catch{return null}}function z(t,e,r){if(!t)return;let n=r?.ttlMs??36e5,o={data:e,expiresAt:Date.now()+n},s=_e();if(s)try{s.setItem(me(t),JSON.stringify(o));return}catch{}de.set(t,o)}function pe(t){if(!t)return null;let e=_e();if(e)try{let n=e.getItem(me(t));if(n){let o=JSON.parse(n);if(o&&typeof o.expiresAt=="number"&&o.expiresAt>Date.now())return o.data;e.removeItem(me(t))}}catch{}let r=de.get(t);if(r){if(r.expiresAt>Date.now())return r.data;de.delete(t)}return null}function ye(t){if(!t)return;de.delete(t);let e=_e();if(e)try{e.removeItem(me(t))}catch{}}var w=require("@flopay/shared"),At="/v1/sdk-telemetry/events",Re=16,kt=64,Et=1500,Oe=1e3,Mt=64,It="00000000-0000-4000-8000-000000000000",Pt={technical_error:8,lifecycle:32,expected_outcome:32,performance:24};function Y(){try{return globalThis.crypto.randomUUID()}catch{let t=new Uint8Array(16);try{globalThis.crypto.getRandomValues(t)}catch{for(let r=0;r<t.length;r+=1)t[r]=Math.floor(Math.random()*256)}t[6]=(t[6]??0)&15|64,t[8]=(t[8]??0)&63|128;let e=[...t].map(r=>r.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(t){try{return new TextEncoder().encode(t).byteLength}catch{return t.length}}function Dt(t){return JSON.stringify([t.code,t.failureCategory,t.reason,t.stage,t.provider,t.attempt,t.statusClass,t.requestCategory,t.paymentMethodCategory,t.walletType,t.operationOutcome,t.checkoutMode,t.layout,t.inAppBrowser,t.appFamily,t.popupCapability,t.presentationMode,t.terminalReason])}function A(){return globalThis.performance?.now()??0}var R=class{constructor(e){this.ingestionDisabled=!1;this.queue=[];this.sequence=0;this.flushTimer=null;this.flushInFlight=null;this.reportedFailures=new Map;this.checkoutContext={};this.checkoutStartedAt=null;this.destroyed=!1;this.observers=new Set;this.pageExitHandler=()=>{this.drainQueue()};this.visibilityHandler=()=>{document.visibilityState==="hidden"&&this.flush()};this.eventCounts={technical_error:0,lifecycle:0,expected_outcome:0,performance:0};this.endpoint=`${e.billingApiUrl.replace(/\/+$/,"")}${At}`,this.sdkPackage=e.sdkPackage??"@flopay/js",this.sdkVersion=e.sdkVersion,this.correlationId=Y(),this.merchantEnabled=e.enabled!==!1,this.clock=e.clock??A,this.browserTransportAvailable=typeof window<"u"&&typeof document<"u",this.browserTransportAvailable&&(window.addEventListener("pagehide",this.pageExitHandler),document.addEventListener("visibilitychange",this.visibilityHandler))}log(e){this.notify({...e,class:"lifecycle"}),this.canCollect()&&this.enqueue((0,w.buildTelemetryLogEvent)({...this.checkoutContext,...e,eventId:Y(),sequence:this.sequence++}))}error(e){if(this.notify({...e,class:"technical_error"}),!this.canCollect())return;let r=(0,w.buildTelemetryErrorEvent)({...this.checkoutContext,...e,eventId:It,sequence:0}),n=Dt(r),o=this.now();this.pruneReportedFailures(o);let s=this.reportedFailures.get(n);if(s!==void 0&&o>=s&&o-s<Oe){this.log({name:"operation.deduplicated",stage:e.stage,provider:e.provider,paymentMethodCategory:e.paymentMethodCategory,attempt:e.attempt,inAppBrowser:e.inAppBrowser,appFamily:e.appFamily,popupCapability:e.popupCapability,presentationMode:e.presentationMode,terminalReason:e.terminalReason});return}this.rememberReportedFailure(n,o),this.enqueue((0,w.buildTelemetryErrorEvent)({...this.checkoutContext,...e,eventId:Y(),sequence:this.sequence++}))}performance(e){this.canCollect()&&this.enqueue((0,w.buildTelemetryPerformanceEvent)({...this.checkoutContext,...e,eventId:Y(),sequence:this.sequence++}))}terminal(e){if(this.canCollect()&&(this.enqueue((0,w.buildTelemetryTerminalEvent)({...this.checkoutContext,...e,eventId:Y(),sequence:this.sequence++})),e.outcome!=="action_required"&&this.checkoutStartedAt!==null)){let r=this.checkoutStartedAt;this.checkoutStartedAt=null,this.performance({...e,stage:"total_journey",durationMs:Math.max(0,this.now()-r),durationMode:"total"})}}now(){try{return this.clock()}catch{return A()}}subscribe(e){return this.destroyed?()=>{}:(this.observers.add(e),()=>this.observers.delete(e))}notify(e){if(!this.destroyed)for(let r of this.observers)try{r(e)}catch{}}pruneReportedFailures(e){for(let[r,n]of this.reportedFailures)(e<n||e-n>=Oe)&&this.reportedFailures.delete(r)}rememberReportedFailure(e,r){for(;this.reportedFailures.size>=Mt;){let n=this.reportedFailures.keys().next();if(n.done)break;this.reportedFailures.delete(n.value)}this.reportedFailures.set(e,r)}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>=kt||this.eventCounts[e.class]>=Pt[e.class])){if(this.eventCounts[e.class]+=1,this.queue.push(e),this.queue.length>=Re){this.flush();return}this.scheduleFlush()}}canCollect(){return this.browserTransportAvailable&&this.merchantEnabled&&!this.ingestionDisabled&&!this.destroyed}async flush(){if(this.flushInFlight!==null)return this.flushInFlight;if(!this.browserTransportAvailable||this.destroyed||this.ingestionDisabled||this.queue.length===0)return;this.clearFlushTimer();let e=this.queue.splice(0,Re);return this.flushInFlight=this.sendBatch(e).finally(()=>{this.flushInFlight=null,this.queue.length>0&&this.scheduleFlush()}),this.flushInFlight}destroy(){this.destroyed||(this.drainQueue(),this.destroyed=!0,this.clearFlushTimer(),this.browserTransportAvailable&&(window.removeEventListener("pagehide",this.pageExitHandler),document.removeEventListener("visibilitychange",this.visibilityHandler)),this.queue.splice(0),this.reportedFailures.clear(),this.observers.clear())}disable(){this.merchantEnabled=!1,this.queue.splice(0),this.reportedFailures.clear(),this.clearFlushTimer()}drainQueue(){if(!(!this.browserTransportAvailable||this.destroyed||this.ingestionDisabled||this.queue.length===0))for(this.clearFlushTimer();this.queue.length>0;){let e=this.queue.splice(0,Re);this.sendBatch(e)}}async sendBatch(e){if(!this.browserTransportAvailable||this.ingestionDisabled)return;let r=(0,w.serializeTelemetryBatch)(e,{correlationId:this.correlationId,sdkPackage:this.sdkPackage,sdkVersion:this.sdkVersion,batchId:Y()});if(xt(r)>w.TELEMETRY_MAX_BATCH_BYTES)return;let n=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:r,credentials:"omit",keepalive:!0,referrerPolicy:"no-referrer",signal:n?.signal}).then(async c=>{if(c.status!==202)return null;let l=null;try{l=await c.json()}catch{}return l?.status==="disabled"?"disabled":null}).catch(()=>null),i=new Promise(c=>{o=setTimeout(()=>{n?.abort(),c(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)}},Fe=Symbol.for("@flopay/js.telemetry.reporter-factory.v1"),Ue=globalThis;Ue[Fe]===void 0&&Object.defineProperty(Ue,Fe,{configurable:!0,enumerable:!1,writable:!1,value:t=>new R(t)});var we=5,qe=new WeakSet;function Ot(t){(typeof t=="object"&&t!==null||typeof t=="function")&&qe.add(t)}function Ft(t){return(typeof t=="object"&&t!==null||typeof t=="function")&&qe.has(t)}function Ut(t,e){let r=e?.error,n=ee(e?.code)??ee(r?.code)??`http_${t}`,o=te(e?.message)??te(r?.message)??qt(n,t);return new T.FloPayError(o,"api_error",{code:n,statusCode:t})}function qt(t,e){switch(t){case"CouponLimitExceeded":return`Too many coupon codes \u2014 a checkout session accepts at most ${we}.`;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 Le(t,e,r){let{billingApiUrl:n,checkoutBaseUrl:o,items:s=[],subscriptions:i=[],products:a,account:c,successUrl:l,cancelUrl:m,checkoutMode:y="confirm",captureMethod:d,couponCodes:h=[],checkoutMetadata:p,tagsData:C,redirectParams:f={},setCookie:v=!0,clientId:S,currency:g,utmMetadata:P,idempotencyKey:K}=t,E=(0,T.resolveIdempotencyKey)(K);if(h.length>we)throw new T.FloPayError(`Too many coupon codes \u2014 a checkout session accepts at most ${we}.`,"validation_error",{code:"CouponLimitExceeded",param:"couponCodes"});let M=a??(0,T.foldIntoProducts)(s,i);(0,T.assertCaptureMethodEligible)({captureMethod:d,products:M});let x=(0,T.resolveSessionCurrency)(g,s,i,M);if(!x)throw new T.FloPayError("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});let D={clientId:S,checkoutVersion:T.SDK_VERSION,successUrl:l,cancelUrl:m,currency:x,checkoutMode:y,products:M.map(q=>(0,T.buildProductPayload)(q,x)),accountData:{userId:c.userId,firstName:c.firstName??null,lastName:c.lastName??null,email:c.email,country:c.country??null,gender:c.gender??null,city:c.city??null,state:c.state??null,zip:c.zip??null,addressLine1:c.addressLine1??null,addressLine2:c.addressLine2??null},couponCodes:h};d==="manual"&&(D.captureMethod=d),p!==void 0&&(D.checkoutMetadata=p),C&&(D.tagsData=C),P&&P.length>0&&(D.utmMetadata=P);let Te=`${n.replace(/\/+$/,"")}/v1/checkouts/sessions`,De={"Content-Type":"application/json"};E&&(De[T.IDEMPOTENCY_KEY_HEADER]=E);let $,ce,ft={method:"POST",headers:De,body:JSON.stringify(D),signal:e},Z;try{r?.startAttempt(),Z=await fetch(Te,ft)}catch(q){throw Ot(q),q}try{r?.record(Z.status)}catch{}$=Z.status;try{ce=await Z.json()}catch{}if($>=400)throw(0,T.withTelemetryHttpDiagnostics)(Ut($,ce),Z);if($===201){let q=ce?.data?.uuid,be=ce?.data?.nonce;if(!q)throw new Error("Checkout session created but no UUID was returned by the billing API");if(!be)throw new T.FloPayError("Checkout session created but no `nonce` was returned by the billing API. Upgrade the billing service to TeamFloPay/backend#640 or later.","api_error",{code:"MissingCheckoutSessionToken"});(M.length>0||x)&&z(q,{currency:x,products:M.map(_=>({code:_.code??_.providerItemId??_.providerPlanId,type:_.type,name:_.name??_.itemName??_.providerItemName??_.subscriptionName??_.providerPlanName??null,totalAmount:_.totalAmount,overrideAmount:_.overrideAmount,currency:_.currency??x}))});let le=new URL(`${o.replace(/\/+$/,"")}/secure`);le.searchParams.set("id",q);for(let[_,ue]of Object.entries(f))le.searchParams.set(_,ue);if(v&&typeof window<"u"&&typeof document<"u"){let _=JSON.stringify({origin_url:m}),ue=window.location.hostname.split(".").slice(-2).join(".");document.cookie=`checkout_data=${encodeURIComponent(_)}; domain=.${ue}; path=/; max-age=3600; SameSite=Lax; Secure;`,document.cookie=`flopay_checkout_token=${encodeURIComponent(be)}; domain=.${ue}; path=/; max-age=3600; SameSite=Lax; Secure;`}return typeof window<"u"&&(window.location.href=le.toString()),{status:201,redirectUrl:le.toString(),nonce:be}}return $===204?(typeof window<"u"&&(window.location.href=l),{status:204}):{status:$}}async function Ne(t){let e=ze(t),r=Ve(e),n=O(t.timeoutMs);try{let o=await Le(t,n.signal,r);return r.commit(),Be(e,o),o}catch(o){throw r.commit(),he(e,o),o}finally{n.clear(),W(e.reporter)}}function Ve(t){let e=!1,r=t.startedAt,n;return{startAttempt(){r=t.reporter.now()},record(o){n={status:o,durationMs:Math.max(0,t.reporter.now()-r),attempt:t.attempt}},commit(){if(e||!n)return;e=!0;let o=(0,T.telemetryStatusClass)(n.status);t.reporter.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:o,attempt:n.attempt}),t.reporter.performance({stage:"session_first_byte",durationMs:n.durationMs,durationMode:"machine",requestCategory:"session_create",statusClass:o,attempt:n.attempt})}}}function ze(t){let e=new R({billingApiUrl:t.billingApiUrl,sdkVersion:T.SDK_VERSION,enabled:t.telemetry!==!1}),r=e.now();return e.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"}),{reporter:e,startedAt:r,attempt:0}}function Be(t,e){let r=(0,T.telemetryStatusClass)(e.status);t.reporter.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:r}),t.reporter.performance({stage:"session_create",durationMs:t.reporter.now()-t.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:r,attempt:t.attempt})}function he(t,e){let{reporter:r}=t,n=(0,T.classifyTelemetryFailure)(e,"CHECKOUT_SESSION_CREATE_FAILED");if(r.performance({stage:"session_create",durationMs:r.now()-t.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:n.statusClass,attempt:t.attempt}),e instanceof T.FloPayError&&e.type==="validation_error"){r.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"});return}if(n.statusClass==="4xx"){r.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create",statusClass:"4xx"});return}r.error({...n,stage:"session_create",requestCategory:"session_create"})}function W(t){t.flush().catch(()=>{}).finally(()=>t.destroy())}async function je(t){let{maxRetries:e=2,...r}=t,n=ze(t),o=Ve(n);if(!Number.isFinite(e)||!Number.isInteger(e)||e<0||e>=3)throw n.reporter.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),W(n.reporter),new Error(`Number of retries must be an integer between 0 and ${2}`);let s={...r,idempotencyKey:(0,T.resolveIdempotencyKey)(r.idempotencyKey)},i=O(r.timeoutMs),a;for(let c=0;c<=e;c++){n.attempt=c;try{let l=await Le(s,i.signal,o);return o.commit(),Be(n,l),i.clear(),W(n.reporter),l}catch(l){a=l;let m=l instanceof Error&&l.name==="AbortError",y=Ft(l),d=l instanceof T.FloPayError&&l.code===T.IDEMPOTENCY_IN_PROGRESS_CODE;if((m||y||d)&&!i.signal.aborted&&c<e){n.reporter.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:c+1});try{await G(c,i.signal)}catch(h){throw o.commit(),he(n,h),i.clear(),W(n.reporter),h}continue}throw o.commit(),he(n,l),i.clear(),W(n.reporter),l}}throw o.commit(),he(n,a),i.clear(),W(n.reporter),a??new Error("Unknown error during checkout session creation")}var k=require("@flopay/shared");var u=require("@flopay/shared");function Lt(t){return t==="on_session"||t==="off_session"}function Nt(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.paymentMethodType=="string"&&typeof e.reason=="string"}function Vt(t){let e=t.vaultOutcome;if(!(!e||e.code!==u.CHECKOUT_SESSION_BUYER_EMAIL_REQUIRED))return typeof e.message=="string"&&e.message.trim()!==""?e.message:void 0}var zt="x-flopay-process-result-source",Bt="status";function He(t){return t?.result==="DECLINE"||t?.result==="ERROR"}var jt=50,B=new Map;function Ht(t,e){return B.get(t)?.has(e)===!0}function Kt(t,e){let r=B.get(t)??new Set;if(r.add(e),B.delete(t),B.set(t,r),B.size>jt){let n=B.keys().next().value;n!==void 0&&B.delete(n)}}function $t(t){let e=t?.threeDSecureActionResultTokenId;if(typeof e=="string"&&e.length>0)return e;if(t?.gateway==="paypal"&&t.type!=="paypal_setup_token"&&typeof t.id=="string"&&t.id.length>0)return t.id}var Ke=0,$e=500,ge=15e3,Ge=15e3,Gt=3e3,Yt=1e4,Wt=1e4;function ne(t){return typeof t=="object"&&t!==null}function N(t,e){return ee(t?.[e])}function Ye(t,e){return te(t?.[e])}function Qt(t,e){let r=t?.[e];return typeof r=="number"&&Number.isFinite(r)?r:void 0}function ke(t,e){return e?new Promise((r,n)=>{let o=()=>{clearTimeout(s),n(e.reason??Object.assign(new Error("The operation was aborted."),{name:"AbortError"}))},s=setTimeout(()=>{e.removeEventListener("abort",o),r()},t);e.aborted?o():e.addEventListener("abort",o,{once:!0})}):new Promise(r=>setTimeout(r,t))}function Ae(t){return t instanceof Error&&t.name==="AbortError"}function I(){return new u.FloPayError(u.CHECKOUT_PROCESSING_TIMEOUT_MESSAGE,"api_error",{code:"checkout_processing_timeout"})}async function L(t,e){let r=await t.json().catch(()=>null),n=ne(r?.error)?r.error:null,o=Ye(r,"message")??Ye(n,"message")??e,s=N(r,"code")??N(r,"gatewayErrorCode")??N(n,"code")??`http_${t.status}`;return(0,u.withTelemetryHttpDiagnostics)(new u.FloPayError(o,"api_error",{code:s,statusCode:t.status}),t)}async function Jt(t){if(t.status!==403)return!1;let e=await t.clone().json().catch(()=>null),r=ne(e?.error)?e.error:null;return(N(e,"code")??N(r,"code"))==="verification_required"}function Xt(t){if(!(!ne(t)||typeof t.required!="boolean"))return{required:t.required,provider:"turnstile"}}async function Zt(t){let e=t.status===400?await t.clone().json().catch(()=>null):null;return(0,u.classifyPaymentRejection)(t.status,e)}function We(t){return t===400||t===422}var Ce=2;async function fe(t,e,r=Ce,n,o){let s;for(let i=0;;i++)try{return o?.(i),await fetch(t,e)}catch(a){if(e?.signal?.aborted||a instanceof Error&&a.name==="AbortError")throw a;if(s=a,i>=r)throw s;try{n?.(i+1)}catch{}await ke(150*2**i,e?.signal??void 0)}}var Ee=Symbol.for("@flopay/js.session-create.telemetry.v1");function er(t){return t[Ee]}function tr(t){return"now"in t||"onFirstByte"in t||"onSessionCreateFailure"in t||"onRetry"in t}function Je(t){let e=(0,u.isCardHolderNamePlaceholder)(t.firstName,t.lastName);return{userId:t.userId,firstName:e?null:t.firstName??null,lastName:e?null:t.lastName??null,email:t.email,country:t.country??null,gender:t.gender??null,city:t.city??null,state:t.state??null,zip:t.zip??null,addressLine1:t.addressLine1??null,addressLine2:t.addressLine2??null}}function Xe(t,e){e.checkoutMetadata!==void 0&&(t.checkoutMetadata=e.checkoutMetadata),e.tagsData&&(t.tagsData=e.tagsData),e.utmMetadata&&e.utmMetadata.length>0&&(t.utmMetadata=e.utmMetadata),e.avsCheck!==void 0&&(t.avsCheck=e.avsCheck),e.checkoutType&&(t.checkoutType=e.checkoutType),e.checkoutLayout&&(t.checkoutLayout=e.checkoutLayout),e.avsConfig&&(t.avsConfig=e.avsConfig)}function rr(t,e){let r={clientId:t.clientId,checkoutVersion:u.SDK_VERSION,successUrl:t.successUrl,cancelUrl:t.cancelUrl,currency:e,checkoutMode:"full",deferDataAttachment:!0};return t.captureMethod==="manual"&&(r.captureMethod=t.captureMethod),t.account.country&&(r.accountData={country:t.account.country}),Xe(r,t),r}function Qe(t,e,r){return{currency:e,products:r.map(n=>(0,u.buildProductPayload)(n,e)),couponCodes:t.couponCodes??[],accountData:Je(t.account)}}function nr(t,e,r){return{currency:e,products:r.map(n=>(0,u.buildProductPayload)(n,e)),couponCodes:t.couponCodes??[]}}function or(t){let e={},r=(0,u.isCardHolderNamePlaceholder)(t.firstName,t.lastName);for(let[n,o]of Object.entries(t)){if(r&&n.endsWith("Name")||typeof o!="string")continue;let s=o.trim();s&&(e[n]=s)}return{accountData:e}}var j=class j{constructor(e,r={}){this.baseUrl=e.replace(/\/+$/,"");let n=tr(r);this.telemetryHooks=n?r:void 0,this.directTelemetry=n||r.telemetry===!1?void 0:new R({billingApiUrl:this.baseUrl,sdkVersion:u.SDK_VERSION})}destroy(){this.directTelemetry?.destroy()}reportDirectFailure(e,r,n,o,s="unknown"){let i=(0,u.classifyTelemetryFailure)(e,r);this.directTelemetry?.error({...i,stage:n,requestCategory:o,paymentMethodCategory:s})}reportAccountSnapshotFailure(e,r){let n=(0,u.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED");if(r==="best_effort"&&n.errorCode==="REQUEST_TIMEOUT"){this.directTelemetry?.log({name:"operation.fallback",stage:"processing",requestCategory:"account_snapshot",statusClass:"timeout"});return}this.directTelemetry?.error({...n,stage:"processing",requestCategory:"account_snapshot",paymentMethodCategory:"unknown"})}telemetryTimestamp(){try{return this.telemetryHooks?.now?.()??this.directTelemetry?.now()??A()}catch{return A()}}beginDirectTelemetryCheckout(e){!this.directTelemetry||this.directTelemetryCheckoutId===e||(this.directTelemetryCheckoutId=e,this.directTelemetry.beginCheckout())}beginDirectTelemetryOperation(){this.directTelemetry&&(this.directTelemetryCheckoutId=void 0,this.directTelemetry.beginCheckout())}adoptDirectTelemetryCheckout(e){e&&(this.directTelemetryCheckoutId=e)}async getCheckoutSession(e,r){return this.fetchCheckoutSession(e,r)}async fetchCheckoutSession(e,r,n=!0,o){this.beginDirectTelemetryCheckout(e);let s=this.telemetryTimestamp(),i=s,a=0;this.directTelemetry?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let c={[u.FLO_SDK_VERSION_HEADER]:u.SDK_VERSION};r&&(c["x-checkout-session-token"]=r);let l=!1;try{let m=await fe(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}`,{headers:c,signal:o},Ce,p=>{this.telemetryHooks?.onRetry?.("session_read",p),this.directTelemetry?.log({name:"operation.retry",stage:"session_read",requestCategory:"session_read",attempt:p})},p=>{a=p,i=this.telemetryTimestamp()});l=!0;let y=Math.max(0,this.telemetryTimestamp()-i);try{this.telemetryHooks?.onFirstByte?.(y,a)}catch{}let d=`${Math.floor(m.status/100)}xx`;if(this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:d,attempt:a}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:y,durationMode:"machine",requestCategory:"session_read",statusClass:d,attempt:a}),!m.ok)throw await L(m,"Failed to get checkout session");let h=await m.json();return this.directTelemetry?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:d}),this.directTelemetry?.performance({stage:"session_complete",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"session_read",statusClass:d}),{...h,data:this.mergeCachedDisplayData(h.data)}}catch(m){throw l&&(0,u.markSessionResponseReceived)(m),n&&this.directTelemetry?.error({...(0,u.classifyTelemetryFailure)(m,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"}),m}}cacheSessionDisplayData(e,r,n){z(e,r,n)}clearSessionDisplayData(e){ye(e)}async getVaultCapture(e,r){let n=`${this.baseUrl}\0${e}\0${r??""}`,o=j.activeVaultCaptureRequests.get(n);if(o!==void 0)return o;let s=this.requestVaultCapture(e,r);j.activeVaultCaptureRequests.set(n,s);try{return await s}finally{j.activeVaultCaptureRequests.get(n)===s&&j.activeVaultCaptureRequests.delete(n)}}async requestVaultCapture(e,r){let n=new AbortController,o=setTimeout(()=>n.abort(),Wt);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"};r&&(i["x-checkout-session-token"]=r);try{let a=await fe(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/vault/capture`,{method:"POST",headers:i,signal:n.signal},Ce,l=>{this.telemetryHooks?.onRetry?.("vault_capture",l),this.directTelemetry?.log({name:"operation.retry",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card",attempt:l})});if(await Jt(a))return this.directTelemetry?.performance({stage:"vault_request",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"4xx"}),{verification:{required:!0,provider:"turnstile"}};if(!a.ok)throw await L(a,"Failed to load the secure card form");let c=await a.json();return this.directTelemetry?.performance({stage:"vault_request",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"2xx"}),this.toVaultBlock(c)}catch(a){let c=n.signal.aborted?new u.FloPayError("Timed out while loading the secure card form. Please try again.","api_error",{code:"vault_capture_timeout"}):a;throw this.reportDirectFailure(c,"VAULT_LOAD_FAILED","vault_request","vault_capture","card"),c}finally{clearTimeout(o)}}async getUnifiedCheckoutSession(e,r){let n=await this.getCheckoutSession(e,r);return this.normalizeCheckoutSessionResponse(n)}async getUnifiedCheckoutSessionForRecovery(e,r,n){let o=await this.fetchCheckoutSession(e,r,!1,n);return this.normalizeCheckoutSessionResponse(o)}normalizeCheckoutSessionResponse(e){try{let r=this.normalizeRawSession(e.data),n=e.vault;return n&&r.data.session&&(r.data.session.vault=this.toVaultBlock(n)),r}catch(r){throw(0,u.markSessionResponseReceived)(r)}}async processPayment(e,r,n){this.beginDirectTelemetryCheckout(r.sessionId);let o=r.paymentMethodCategory??"unknown";if(!r.nonce)throw this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"process_payment",paymentMethodCategory:o}),new u.FloPayError("processPayment requires `nonce` \u2014 pass the value returned from session creation.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let s=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.processing.started",stage:"processing",requestCategory:"process_payment",paymentMethodCategory:o});let{nonce:i,paymentMethodCategory:a,...c}=r,l=$t(r.tokenizedData),m,y;try{m=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(r.sessionId)}/process`,{method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":i},body:JSON.stringify(c)}),y=m}catch(d){if(Ae(d))throw this.reportDirectFailure(d,"PAYMENT_PROCESSING_FAILED","processing","process_payment",o),d;m=await this.reconcileProcessPayment(r.sessionId,{...n,nonce:i,paymentMethodCategory:o,submittedIntentId:l})}if(!m.ok&&m.status!==202){let d=await Zt(m);return d?this.directTelemetry?.terminal({outcome:d,stage:"processing",requestCategory:"process_payment",statusClass:"4xx",paymentMethodCategory:o}):this.directTelemetry?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",requestCategory:"process_payment",statusClass:(0,u.telemetryStatusClass)(m.status),failureCategory:m.status>=500?"server_error":void 0,paymentMethodCategory:o,...(0,u.readTelemetryHttpDiagnostics)(y)}),m}try{let d=await this.resolveProcessResponse(m,r.sessionId,{...n,nonce:i,paymentMethodCategory:o,submittedIntentId:l});return this.directTelemetry?.log({name:"payment.processing.completed",stage:"processing",requestCategory:"process_payment",statusClass:(0,u.telemetryStatusClass)(d.status),paymentMethodCategory:o}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"process_payment",statusClass:(0,u.telemetryStatusClass)(d.status),paymentMethodCategory:o}),d}catch(d){throw d instanceof u.FloPayError&&d.code==="checkout_processing_timeout"||this.reportDirectFailure(d,"PAYMENT_PROCESSING_FAILED","processing","process_payment",o),d}}async patchAccountSnapshot(e,r,n,o){this.beginDirectTelemetryCheckout(e);let s=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.state_transition",stage:"processing",requestCategory:"account_snapshot"});let i=o?.timeoutMs??Yt,a=new AbortController,c=()=>a.abort();o?.signal&&(o.signal.aborted?a.abort():o.signal.addEventListener("abort",c,{once:!0}));let l=setTimeout(()=>a.abort(),i);try{let m;try{m=await fe(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/account`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":r},body:JSON.stringify(n),signal:a.signal},Ce,y=>{this.telemetryHooks?.onRetry?.("account_snapshot",y),this.directTelemetry?.log({name:"operation.retry",stage:"processing",requestCategory:"account_snapshot",attempt:y})})}finally{clearTimeout(l),o?.signal?.removeEventListener("abort",c)}if(!m.ok)throw await L(m,"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(m){throw this.reportAccountSnapshotFailure(m,o?.telemetryMode??"blocking"),m}}async createSessionIntent(e,r,n,o){if(!r)throw new u.FloPayError("createSessionIntent requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let s=n,i=s.paymentMethodType,a=typeof i=="string"&&i.trim().toLowerCase()==="card",c=typeof i=="string"&&i.length>0&&!a&&(typeof s.paymentMethodId=="string"||s.paymentMethodId===null),l=s.provider==="stripe"&&(s.paymentMethodCategory==="wallet"||s.paymentMethodCategory==="apm")&&(s.intentKind==="payment"||s.intentKind==="setup"),m=s.provider==="paypal"&&s.paymentMethodCategory==="wallet"&&s.paymentMethodId===null&&(s.paymentMethodType==="paypal"&&s.intentKind==="payment"||s.paymentMethodType===u.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&(s.intentKind==="payment"||s.intentKind==="setup"));if(!c||!l&&!m)throw new u.FloPayError("Only wallet, APM, and PayPal session intents are supported.","validation_error",{code:"InvalidSessionIntentRequest"});let y=s.authorizationAttemptId;if(y!==void 0&&!(0,u.isUuidV4)(y))throw new u.FloPayError("authorizationAttemptId must be a v4 UUID identifying one buyer authorization attempt.","validation_error",{code:"InvalidAuthorizationAttemptId",param:"authorizationAttemptId"});let d=(0,u.isUuidV4)(y)?y:(0,u.randomUuidV4)();this.beginDirectTelemetryCheckout(e);let h=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.intent.started",stage:"processing",requestCategory:"intent_create"});let p={"Content-Type":"application/json","x-checkout-session-token":r,[u.IDEMPOTENCY_KEY_HEADER]:o?.idempotencyKey||d},C=!1;try{let f=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents`,{method:"POST",headers:p,body:JSON.stringify({...n,authorizationAttemptId:d}),signal:o?.signal});if(!f.ok){C=!0;let D=await L(f,"Failed to create checkout intent"),Te=(0,u.classifyTelemetryFailure)(D,"PAYMENT_PROCESSING_FAILED");throw We(D.statusCode)?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"intent_create",statusClass:"4xx"}):this.directTelemetry?.error({...Te,stage:"processing",requestCategory:"intent_create"}),D}let v=await f.json();if(f.status===202&&ne(v)&&v.type==="checkout_processing")return C=!0,await this.settleProcessingSessionIntent(v,f,e,r,n);let S=v.data;if(!S||typeof S!="object")throw new u.FloPayError("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});let g=S,P=g.paymentMethodType,K=(g.paymentMethodCategory==="wallet"||g.paymentMethodCategory==="apm")&&typeof P=="string"&&P.trim().toLowerCase()!=="card"&&(typeof g.paymentMethodId=="string"||g.paymentMethodId===null)&&typeof g.providerObjectId=="string",E=g.provider==="stripe"&&(g.intentKind==="payment"||g.intentKind==="setup")&&typeof g.clientSecret=="string",M=g.provider==="paypal"&&g.paymentMethodCategory==="wallet"&&g.paymentMethodId===null&&(g.paymentMethodType==="paypal"&&g.intentKind==="payment"&&(g.providerObjectType==="order"||g.providerObjectType==="subscription")||g.paymentMethodType===u.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&g.intentKind==="payment"&&g.providerObjectType==="order"||g.paymentMethodType===u.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&g.intentKind==="setup"&&g.providerObjectType==="setup_token")&&g.clientSecret===null,x=g.provider===n.provider&&g.paymentMethodCategory===n.paymentMethodCategory&&g.paymentMethodType===n.paymentMethodType&&g.paymentMethodId===n.paymentMethodId&&g.intentKind===n.intentKind;if(!K||!E&&!M||!x)throw new u.FloPayError("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});return this.directTelemetry?.log({name:"payment.intent.completed",stage:"processing",requestCategory:"intent_create",statusClass:(0,u.telemetryStatusClass)(f.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-h),durationMode:"machine",requestCategory:"intent_create",statusClass:(0,u.telemetryStatusClass)(f.status)}),g}catch(f){throw C||this.reportDirectFailure(f,"PAYMENT_PROCESSING_FAILED","processing","intent_create"),f}}async settleProcessingSessionIntent(e,r,n,o,s){let i=this.toCheckoutProcessingPending(e,r,n);try{return{settled:!0,response:await this.resolveCheckoutProcessing(i,n,{nonce:o,paymentMethodCategory:s.provider==="paypal"?"paypal":s.paymentMethodCategory})}}catch(a){throw a instanceof u.FloPayError&&a.code==="checkout_processing_timeout"?new u.FloPayError(a.message,a.type,{code:a.code,statusCode:202,sessionId:i.sessionId,cause:a}):a}}async reportSessionIntentDecline(e,r,n,o){if(!r)throw new u.FloPayError("reportSessionIntentDecline requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let s=n,i=s.providerDeclineReason,a=s.paymentMethodType,c=s.providerIntentId,l=typeof i=="string"&&/^[a-z0-9][a-z0-9_.:-]{0,63}$/i.test(i)&&!/^(?:pm|pi|seti|tok|src|cus|sess|sk|pk)_/i.test(i),m=typeof a=="string"&&a.length>0&&a.trim().toLowerCase()!=="card"&&l,y=s.provider==="stripe"&&(s.paymentMethodCategory==="wallet"||s.paymentMethodCategory==="apm")&&(c===void 0||typeof c=="string"&&/^pi_[a-z0-9_]{1,252}$/i.test(c)),d=s.provider==="paypal"&&s.paymentMethodCategory==="wallet"&&s.paymentMethodType==="paypal"&&c===void 0;if(!m||!y&&!d)throw new u.FloPayError("Invalid non-card decline classification.","validation_error",{code:"InvalidSessionIntentDeclineRequest"});let h=d?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:i}:{provider:"stripe",paymentMethodCategory:s.paymentMethodCategory,paymentMethodType:s.paymentMethodType,providerDeclineReason:i,...typeof c=="string"?{providerIntentId:c}:{}},p=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents/decline`,{method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":r},body:JSON.stringify(h),signal:o?.signal});if(!p.ok)throw await L(p,"Failed to report checkout decline")}async getPaymentsByEmail(e,r){this.beginDirectTelemetryOperation();let n=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved"});let o=r?.page??1,s=r?.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:r?.signal,keepalive:!0});if(!a.ok)throw(0,u.withTelemetryHttpDiagnostics)(new u.FloPayError("Failed to fetch payments","api_error",{statusCode:a.status}),a);let c=await a.json();return this.directTelemetry?.log({name:"operation.recovery.completed",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),this.directTelemetry?.performance({stage:"recovery",durationMs:Math.max(0,this.telemetryTimestamp()-n),durationMode:"machine",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),c}catch(a){throw this.reportDirectFailure(a,"RECOVERY_FAILED","recovery","other","saved"),a}}async createAndFetchSession(e){if((0,u.isDetachedSessionEligible)(e)){let s=e.account.email?.trim();if(s&&!(0,u.isValidEmail)(s))throw new u.FloPayError("Buyer email must be valid when supplied.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"});return(await this.createDetachedSession(e)).claimed}this.beginDirectTelemetryOperation();let r=this.telemetryTimestamp(),n=O(e.timeoutMs??12e3),o={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});try{let s=await this.createAndFetchSessionRequest(e,n.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()-r),durationMode:"machine",requestCategory:"session_create",statusClass:o.statusClass,attempt:o.attempt}),s}catch(s){throw this.reportSessionCreateFailure(s,r,o),s}finally{n.clear()}}async createAndFetchSessionRequest(e,r,n){let o=e.products??(0,u.foldIntoProducts)(e.items,e.subscriptions);(0,u.assertCaptureMethodEligible)({captureMethod:e.captureMethod,products:o});let s=(0,u.resolveSessionCurrency)(e.currency,e.items,e.subscriptions,o);if(!s)throw new u.FloPayError("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});let i={clientId:e.clientId,checkoutVersion:u.SDK_VERSION,successUrl:e.successUrl,cancelUrl:e.cancelUrl,currency:s,checkoutMode:e.checkoutMode??"full",products:o.map(l=>(0,u.buildProductPayload)(l,s)),accountData:Je(e.account),couponCodes:e.couponCodes??[]};e.captureMethod==="manual"&&(i.captureMethod=e.captureMethod),e.tokenizedData&&(i.tokenizedData=e.tokenizedData),Xe(i,e);let a=await this.postCheckoutSessionCreate(i,e,r,n),c=!1;try{let l=await a.json();if(l.data&&"gateways"in l.data){this.autoCacheDisplayData(l.data.uuid,e);let d=this.mergeCachedDisplayData(l.data),h=this.normalizeRawSession(d);return l.vault&&h.data.session&&(h.data.session.vault=this.toVaultBlock(l.vault)),{...h,autoProcessingError:l.autoProcessingError,autoProcessingAttempted:l.autoProcessingAttempted,autoProcessingPending:l.autoProcessingPending}}let m=l.data?.uuid;if(!m)throw new u.FloPayError("No session ID returned","api_error",{code:"InvalidCheckoutSessionResponse"});return this.autoCacheDisplayData(m,e),this.adoptDirectTelemetryCheckout(m),c=!0,{...await this.getUnifiedCheckoutSession(m),autoProcessingError:l.autoProcessingError,autoProcessingAttempted:l.autoProcessingAttempted,autoProcessingPending:l.autoProcessingPending}}catch(l){throw c?l:(0,u.markSessionResponseReceived)(l)}}async postCheckoutSessionCreate(e,r,n,o){let s={"Content-Type":"application/json",[u.FLO_SDK_VERSION_HEADER]:u.SDK_VERSION},i=(0,u.resolveIdempotencyKey)(r.idempotencyKey);i&&(s[u.IDEMPOTENCY_KEY_HEADER]=i),r.checkoutMode==="auto"&&(s[u.FLO_SDK_CAPABILITIES_HEADER]=u.ASYNC_AUTO_CHECKOUT_CAPABILITY);let a,c=!1,l=er(r),m=(d,h,p)=>{c||(c=!0,this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:p,attempt:d}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:Math.max(0,this.telemetryTimestamp()-h),durationMode:"machine",requestCategory:"session_create",statusClass:p,attempt:d}))},y=d=>{try{this.telemetryHooks?.onRetry?.("session_create",d),this.directTelemetry?.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:d})}catch{}};for(let d=0;d<3;d++){o.attempt=d;let h=this.telemetryTimestamp();try{l?.onAttempt?.(d)}catch{}try{a=await fetch(`${this.baseUrl}/v1/checkouts/sessions?expand=true`,{method:"POST",headers:s,body:JSON.stringify(e),signal:n})}catch(f){if(o.statusClass=n.aborted||f instanceof Error&&f.name==="AbortError"?"timeout":"network_error",n.aborted||f instanceof Error&&f.name==="AbortError"||d>=2)throw f;let v=d+1;y(v),await G(d,n);continue}let p=(0,u.telemetryStatusClass)(a.status);if(o.statusClass=p,a.status===204)throw m(d,h,p),new u.FloPayError("Session auto-completed \u2014 payment method already on file","api_error",{code:"session_auto_completed"});if(a.ok){m(d,h,p);break}let C=await L(a,"Failed to create checkout session");if(C.code===u.IDEMPOTENCY_IN_PROGRESS_CODE&&d<2){y(d+1),await G(d,n);continue}throw m(d,h,p),C}if(!a)throw new TypeError("Checkout-session creation exhausted its retry budget.");return a}async createDetachedSession(e){this.beginDirectTelemetryOperation();let r=this.telemetryTimestamp(),n=O(e.timeoutMs??12e3),o={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let s=e.products??(0,u.foldIntoProducts)(e.items,e.subscriptions);try{(0,u.assertCaptureMethodEligible)({captureMethod:e.captureMethod,products:s})}catch(v){throw n.clear(),this.reportSessionCreateFailure(v,r,o),v}let i=(0,u.resolveSessionCurrency)(e.currency,e.items,e.subscriptions,s);if(!i)throw n.clear(),this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),new u.FloPayError("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});try{Qe(e,i,s)}catch(v){throw n.clear(),this.reportSessionCreateFailure(v,r,o),v}let a,c,l=!1;try{let v=await this.postCheckoutSessionCreate(rr(e,i),e,n.signal,o);if(l=!0,c=await v.json(),!c.data||!("gateways"in c.data))throw new u.FloPayError("The billing API returned no session shell for a detached create. It must support `deferDataAttachment` (TeamFloPay/backend#1099).","api_error",{code:"InvalidCheckoutSessionResponse"});a=this.normalizeRawSession(this.mergeCachedDisplayData(c.data)),c.vault&&a.data.session&&(a.data.session.vault=this.toVaultBlock(c.vault))}catch(v){throw n.clear(),l&&(0,u.markSessionResponseReceived)(v),this.reportSessionCreateFailure(v,r,o),v}let m=a.data.session?.id??c.data.uuid??"",y=a.data.session?.clientSecret??c.data.nonce??"";if(!m||!y){n.clear();let v=new u.FloPayError("Checkout session shell was created without a session id or nonce.","api_error",{code:"InvalidCheckoutSessionResponse"});throw this.reportSessionCreateFailure(v,r,o),v}n.clear(),this.adoptDirectTelemetryCheckout(m),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()-r),durationMode:"machine",requestCategory:"session_create",statusClass:o.statusClass,attempt:o.attempt,paymentMethodCategory:"card"});let d=!e.account.email?.trim(),h=O(e.timeoutMs??12e3),p=this.claimCheckoutSession(m,y,d?nr(e,i,s):Qe(e,i,s),{params:e,startedAt:r,deadline:h,createAttempt:o.attempt}),C=d?void 0:p,f=(v={})=>{if(C!==void 0)return C;let S={...e,account:{...e.account,...v,email:v.email?.trim()||e.account.email?.trim()}};return(0,u.isValidEmail)(S.account.email)?(C=p.then(()=>{let g=this.telemetryTimestamp();return this.claimCheckoutSession(m,y,or(S.account),{params:S,startedAt:g,deadline:O(e.timeoutMs??12e3),createAttempt:0})}),C.catch(()=>{}),C):Promise.reject(new u.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}))};return p.catch(()=>{}),{shell:a,sessionId:m,nonce:y,claimed:p,claim:f}}async claimCheckoutSession(e,r,n,o){let s=o?.startedAt??this.telemetryTimestamp(),i=this.telemetryTimestamp(),a=o?.deadline??O(12e3),c=JSON.stringify(n),l="unknown",m=0,y=!1;this.directTelemetry?.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"});try{let d;for(m=0;m<3;m++){try{d=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/claim`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":r,[u.FLO_SDK_VERSION_HEADER]:u.SDK_VERSION},body:c,signal:a.signal})}catch(C){let f=a.signal.aborted||C instanceof Error&&C.name==="AbortError";if(l=f?"timeout":"network_error",f||m>=2)throw C;try{this.telemetryHooks?.onRetry?.("session_claim",m+1),this.directTelemetry?.log({name:"operation.retry",stage:"session_claim",requestCategory:"session_claim",attempt:m+1})}catch{}await G(m,a.signal);continue}if(l=(0,u.telemetryStatusClass)(d.status),d.ok)break;throw await L(d,"Failed to attach checkout session data")}if(!d)throw new TypeError("Checkout-session claim exhausted its retry budget.");y=!0;let h=await d.json();if(!h.data?.gateways)throw new u.FloPayError("The billing API returned no checkout session with gateways after claiming it.","api_error",{code:"InvalidCheckoutSessionResponse"});o?.params&&this.autoCacheDisplayData(h.data.uuid??e,o.params);let p=this.normalizeRawSession(this.mergeCachedDisplayData(h.data));return h.vault&&p.data.session&&(p.data.session.vault=this.toVaultBlock(h.vault)),this.directTelemetry?.log({name:"session.claim.completed",stage:"session_claim",requestCategory:"session_claim",statusClass:l}),this.directTelemetry?.performance({stage:"session_claim",durationMs:Math.max(0,this.telemetryTimestamp()-i),durationMode:"machine",requestCategory:"session_claim",statusClass:l,attempt:m}),this.directTelemetry?.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:l}),this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"session_create",statusClass:l,attempt:o?.createAttempt??m}),p}catch(d){throw y&&(0,u.markSessionResponseReceived)(d),this.reportSessionCreateFailure(d,i,{attempt:m,statusClass:l},"session_claim"),d}finally{a.clear()}}reportSessionCreateFailure(e,r,n,o="session_create"){if(!(e instanceof u.FloPayError&&e.code==="session_auto_completed"))try{this.telemetryHooks?.onSessionCreateFailure?.(e)}catch{}let s=(0,u.classifyTelemetryFailure)(e,"CHECKOUT_SESSION_CREATE_FAILED");if(this.directTelemetry?.performance({stage:o,durationMs:Math.max(0,this.telemetryTimestamp()-r),durationMode:"machine",requestCategory:o==="session_claim"?"session_claim":"session_create",statusClass:s.statusClass,attempt:n.attempt}),e instanceof u.FloPayError&&e.type==="validation_error"||e instanceof u.FloPayError&&We(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 u.FloPayError&&e.code==="session_auto_completed"||this.directTelemetry?.error({...s,stage:o,requestCategory:o==="session_claim"?"session_claim":"session_create"})}reportThreeDsAbandoned(e){this.beginDirectTelemetryCheckout(e),this.directTelemetry?.terminal({outcome:"customer_abandoned",stage:"three_ds_handoff",paymentMethodCategory:"saved"})}async waitForCheckoutSessionCompletion(e,r){this.beginDirectTelemetryCheckout(e);let n=this.telemetryTimestamp(),o=r?.paymentMethodCategory??"saved";this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:o});let s=r?.timeoutMs??ge,i=Date.now()+s,a=new AbortController,c=!1,l,m=setTimeout(()=>{l=setTimeout(()=>{c=!0,a.abort()},Ge)},s),y=()=>a.abort(r?.signal?.reason);r?.signal?.aborted?y():r?.signal?.addEventListener("abort",y,{once:!0});let d=this.clampRetryAfterMs(r?.initialDelayMs??Ke),h=0;try{if(r?.statusUrl){let p=await this.waitForCheckoutStatus(e,{initialDelayMs:d,timeoutMs:s,nonce:r.nonce,statusUrl:r.statusUrl,pollAfterAction:r.continueAfterActionRequired,signal:a.signal});if(p){let C=await this.resolveCheckoutSessionStatus(e,p,r.nonce,a.signal,()=>c);return this.reportRecoveryCompleted(n,o),C}}for(;;){let p=i-Date.now();if(p<=0)throw I();if(d>0){try{h+=1,this.telemetryHooks?.onRetry?.("session_read",h),this.directTelemetry?.log({name:"operation.retry",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:o,attempt:h})}catch{}if(await ke(Math.min(d,p),a.signal),Date.now()>=i)throw I()}let C=await this.getUnifiedCheckoutSessionForRecovery(e,r?.nonce,a.signal),f=C.data.session?.status;if(f==="authorized"||f==="complete"||f==="expired")return this.reportRecoveryCompleted(n,o),C;if(Date.now()>=i)throw I();d=this.clampRetryAfterMs(Math.max(d*2,$e))}}catch(p){let C=c&&Ae(p)?I():p;throw this.reportDirectFailure(C,"RECOVERY_FAILED","recovery","session_read",o),C}finally{clearTimeout(m),clearTimeout(l),r?.signal?.removeEventListener("abort",y)}}reportRecoveryCompleted(e,r){let n={stage:"recovery",requestCategory:"session_read",paymentMethodCategory:r};this.directTelemetry?.log({name:"operation.recovery.completed",...n}),this.directTelemetry?.performance({...n,durationMs:Math.max(0,this.telemetryTimestamp()-e),durationMode:"machine"})}async resolveCheckoutSessionStatus(e,r,n,o,s){let i=r.latestTransactionAttempt;if(this.rememberReportedFailure(e,r),i?.result==="DECLINE"){let l=i.code===u.STORED_PAYMENT_METHOD_UNSUPPORTED_CODE;throw new u.FloPayError(l?u.STORED_PAYMENT_METHOD_UNSUPPORTED_MESSAGE:"Payment was declined. Please choose another payment method.","api_error",{code:i.code??i.declineReason??"authorization_declined",statusCode:400})}if(i?.result==="ERROR"||r.status==="voided")throw new u.FloPayError("Payment could not be completed. Please try again.","api_error",{code:i?.code??"payment_processing_error",statusCode:500});let a;try{a=await this.getUnifiedCheckoutSessionForRecovery(e,n,o)}catch(l){if(!s?.()||!Ae(l))throw l;a={providers:[],mode:"tokenize",data:{},raw:r}}let c=a.data.session;return c&&i?.result==="SUCCESS"?{...a,data:{...a.data,session:{...c,status:"complete"}}}:c&&i?.result==="AUTHORIZED"?{...a,data:{...a.data,session:{...c,status:"authorized",paymentId:r.paymentId??void 0,authorizationExpiresAt:r.authorizationExpiresAt??void 0}}}:c&&r.status==="completed"?{...a,data:{...a.data,session:{...c,status:"complete"}}}:c&&r.status==="authorized"?{...a,data:{...a.data,session:{...c,status:"authorized",paymentId:r.paymentId??void 0,authorizationExpiresAt:r.authorizationExpiresAt??void 0}}}:c&&r.status==="expired"?{...a,data:{...a.data,session:{...c,status:"expired"}}}:i?.result!=="ACTION_REQUIRED"?a:i.gateway==="paypal"&&i.providerIntentId?{...a,autoProcessingError:{type:"paypal_direct_required",message:"PayPal authorization required",orderId:i.providerIntentId,checkoutMethod:"paypal"}}:i.nextActionRedirectUrl?{...a,autoProcessingError:{type:"3ds_required",message:"Additional authentication is required.",nextActionRedirectUrl:i.nextActionRedirectUrl}}:a}async waitForCheckoutStatus(e,r){let n=r.timeoutMs??ge,o=Date.now()+n,s=this.clampRetryAfterMs(r.initialDelayMs);for(;;){let i=o-Date.now();if(i<=0||s>0&&(await ke(Math.min(s,i),r.signal),Date.now()>=o))throw I();let a=o-Date.now();if(a<=0)throw I();let c=new AbortController,l,m=r.signal?new Promise((S,g)=>{l=g}):null,y=()=>{c.abort(r.signal?.reason),l?.(r.signal?.reason??Object.assign(new Error("The operation was aborted."),{name:"AbortError"}))};r.signal?.aborted?y():r.signal?.addEventListener("abort",y,{once:!0});let d,h=r.signal?null:new Promise((S,g)=>{d=setTimeout(()=>{g(I()),c.abort()},a+Ge)}),p;try{let S=this.fetchCheckoutStatus(e,r.nonce,r.statusUrl,c.signal);p=await Promise.race([S,h,m].filter(g=>g!==null))}finally{d!==void 0&&clearTimeout(d),r.signal?.removeEventListener("abort",y)}if(!p)return null;let C=He(p.latestTransactionAttempt)&&!this.isOwnFailedAttempt(e,p,r.submittedIntentId);if(p.status==="completed"||p.status==="authorized"||p.status==="expired"||p.status==="voided")return C?{...p,latestTransactionAttempt:null}:p;let f=p.latestTransactionAttempt?.result,v=r.pollAfterAction===!0&&f==="ACTION_REQUIRED";if(!C&&f!==void 0&&f!=="PENDING"&&!v)return p;s=this.clampRetryAfterMs(Math.max(s*2,$e))}}isOwnFailedAttempt(e,r,n){let o=r.latestTransactionAttempt?.providerIntentId??null;return n!==void 0?o===n:o===null?!0:!Ht(r.uuid||e,o)}rememberReportedFailure(e,r){let n=r.latestTransactionAttempt;!He(n)||!n.providerIntentId||Kt(r.uuid||e,n.providerIntentId)}async fetchCheckoutStatus(e,r,n,o){let s=`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/status`,i=s;if(n)try{let m=new URL(n,`${this.baseUrl}/`),y=new URL(s);m.origin===y.origin&&(i=m.toString())}catch{}let a={[u.FLO_SDK_VERSION_HEADER]:u.SDK_VERSION};r&&(a["x-checkout-session-token"]=r);let c=await fe(i,{headers:a,signal:o});if(c.status===404||c.status===405)return null;if(!c.ok)throw await L(c,"Failed to get checkout session status");let l=await c.json();return ne(l.data)&&"latestTransactionAttempt"in l.data?l.data:null}normalizeRawSession(e){let r=e.gateways??{},n=[],o={session:this.toCheckoutSession(e)},s=r.stripe;if(s?.publishableKey){n.push("stripe");let c=[e.stripeClientSecret,s.stripeClientSecret].find(l=>typeof l=="string"&&l.length>0);o.stripe={clientSecret:c??"",publishableKey:s.publishableKey??void 0,paypalPublishableKey:s.paypalPublishableKey??void 0,environment:s.environment,enabledPaymentMethods:Array.isArray(s.enabledPaymentMethods)?s.enabledPaymentMethods.filter(l=>typeof l=="string"):void 0}}let i=r.paypal;return i?.publishableKey&&(n.push("paypal"),o.paypal={publishableKey:i.publishableKey,environment:i.environment,providerObjectType:i.providerObjectType,approvalPresentation:i.approvalPresentation}),{providers:n,mode:"tokenize",...e.checkoutMetadata===void 0?{}:{checkoutMetadata:e.checkoutMetadata},data:o,raw:{data:e}}}toCheckoutSession(e){let r=e.products??[],n=typeof e.totalAmount=="number"&&Number.isFinite(e.totalAmount),o=r.reduce((l,m)=>l+(m.overrideAmount??m.totalAmount??0),0),s=n?e.totalAmount:o,i=Math.round(s*100),a=e.currency??r[0]?.currency??"USD",c="payment";return e.checkoutMode==="setup"?c="setup":r.some(l=>l.type==="subscription")&&(c="subscription"),{id:e.uuid,clientSecret:e.nonce,mode:c,status:this.toCheckoutSessionStatus(e.status),amount:i,currency:a,captureMethod:e.captureMethod,paymentId:e.paymentId,authorizationExpiresAt:e.authorizationExpiresAt,failureOutcome:(0,u.normalizeCheckoutFailureOutcome)(e.outcome)??(0,u.normalizeCheckoutFailureOutcome)(e.failureReason)??(e.status==="expired"&&e.captureMethod==="manual"?"authorization_expired":void 0),customer:{id:e.accountData.userId??void 0,email:e.accountData.email??void 0,firstName:e.accountData.firstName??void 0,lastName:e.accountData.lastName??void 0,country:e.accountData.country??void 0,city:e.accountData.city??void 0,state:e.accountData.state??void 0,zip:e.accountData.zip??void 0,gender:e.accountData.gender??void 0,line1:e.accountData.addressLine1??void 0,line2:e.accountData.addressLine2??void 0},...e.checkoutMetadata===void 0?{}:{checkoutMetadata:e.checkoutMetadata},metadata:{},checkoutMode:e.checkoutMode,...Array.isArray(e.advertisedPaymentMethods)?{advertisedPaymentMethods:e.advertisedPaymentMethods}:{},...Lt(e.futureUse)?{futureUse:e.futureUse}:{},...Array.isArray(e.futureUseUnsupported)?{futureUseUnsupported:e.futureUseUnsupported.filter(Nt)}:{},buyerIdentified:e.buyerIdentified,providerPaymentMethodId:typeof e.providerPaymentMethodId=="string"?e.providerPaymentMethodId:null,products:r.map(l=>({...l,totalAmount:typeof l.totalAmount=="number"?l.totalAmount:void 0,overrideAmount:typeof l.overrideAmount=="number"?l.overrideAmount:null,currency:typeof l.currency=="string"?l.currency:void 0,metadata:l.metadata??null})),successUrl:e.successUrl,cancelUrl:e.cancelUrl,coupons:e.coupons,subtotalAmount:e.subtotalAmount,discountAmount:e.discountAmount,totalAmount:e.totalAmount,createdAt:e.createdAt,gateways:e.gateways,accountData:e.accountData,tagsData:e.tagsData}}toVaultBlock(e){let r=Xt(e.verification);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,...r?{verification:r}:{}}}toCheckoutSessionStatus(e){return e==="completed"?"complete":e==="authorized"?"authorized":e==="expired"?"expired":"open"}async resolveProcessResponse(e,r,n){if(e.status!==202)return e;let o=await e.json().catch(()=>null),s=this.toCheckoutProcessingPending(o,e,r);return this.resolveCheckoutProcessing(s,r,n)}async resolveCheckoutProcessing(e,r,n){let o=n?.pollTimeoutMs??ge,s=Date.now()+o;if(e.statusUrl){let a=await this.waitForCheckoutStatus(e.sessionId,{initialDelayMs:e.retryAfterMs,timeoutMs:o,nonce:n?.nonce,statusUrl:e.statusUrl,submittedIntentId:n?.submittedIntentId});if(a)return this.toProcessResponseFromStatus(a,r,n?.nonce)}let i=await this.waitForCheckoutSessionCompletion(e.sessionId,{initialDelayMs:e.retryAfterMs,timeoutMs:s-Date.now(),nonce:n?.nonce,paymentMethodCategory:n?.paymentMethodCategory});return this.toProcessResponseFromSession(i,r)}async toProcessResponseFromStatus(e,r,n){let o=e.latestTransactionAttempt?.result,s={[zt]:Bt},i={"Content-Type":"application/json",...s};if(e.status==="completed"||o==="SUCCESS")return new Response(null,{status:204,statusText:"No Content",headers:s});if(e.status==="authorized"||o==="AUTHORIZED")return new Response(JSON.stringify({status:"authorized",paymentId:e.paymentId??void 0,sessionId:e.uuid||r,authorizationExpiresAt:e.authorizationExpiresAt??void 0}),{status:200,headers:i});if(e.status==="expired"){let a=await this.resolveCheckoutSessionStatus(r,e,n);return this.toProcessResponseFromSession(a,r)}if(this.rememberReportedFailure(r,e),o==="DECLINE"){let a=e.latestTransactionAttempt,c=a?.code===u.STORED_PAYMENT_METHOD_UNSUPPORTED_CODE,l=a?.declineReason??void 0;return new Response(JSON.stringify({type:l??"authorization_declined",message:c?u.STORED_PAYMENT_METHOD_UNSUPPORTED_MESSAGE:"Payment was declined. Please choose another payment method.",code:a?.code??l??"authorization_declined",...l?{declineCode:l}:{}}),{status:400,headers:i})}if(o==="ACTION_REQUIRED"&&e.latestTransactionAttempt?.gateway==="paypal"&&e.latestTransactionAttempt.providerIntentId)return new Response(JSON.stringify({type:"paypal_direct_required",message:"PayPal authorization required",orderId:e.latestTransactionAttempt.providerIntentId}),{status:400,headers:i});if(o==="ACTION_REQUIRED"&&e.latestTransactionAttempt?.nextActionRedirectUrl)return new Response(JSON.stringify({type:"3ds_required",message:"Additional authentication is required.",nextActionRedirectUrl:e.latestTransactionAttempt.nextActionRedirectUrl}),{status:400,headers:i});if(o==="ERROR"||e.status==="voided")return new Response(JSON.stringify({type:"unknown",code:e.latestTransactionAttempt?.code??"payment_processing_error",message:Vt(e)??"Payment could not be completed. Please try again."}),{status:500,headers:i});throw I()}async reconcileProcessPayment(e,r){let n=r?.pollTimeoutMs??ge,o=Date.now()+n,s=null;try{s=await this.waitForCheckoutStatus(e,{initialDelayMs:0,timeoutMs:n,nonce:r?.nonce,submittedIntentId:r?.submittedIntentId})}catch(c){if(this.reportDirectFailure(c,"RECOVERY_FAILED","recovery","session_read",r?.paymentMethodCategory??"saved"),c instanceof u.FloPayError&&c.code==="checkout_processing_timeout")throw c}if(s)return this.toProcessResponseFromStatus(s,e,r?.nonce);let i=o-Date.now();if(i<=0)throw I();let a=await this.waitForCheckoutSessionCompletion(e,{initialDelayMs:0,timeoutMs:i,nonce:r?.nonce,paymentMethodCategory:r?.paymentMethodCategory});return this.toProcessResponseFromSession(a,e)}toProcessResponseFromSession(e,r){if(e.data.session?.status==="complete")return new Response(null,{status:204,statusText:"No Content"});if(e.data.session?.status==="authorized"){let n=e.data.session;return new Response(JSON.stringify({status:"authorized",paymentId:n.paymentId,sessionId:n.id||r,authorizationExpiresAt:n.authorizationExpiresAt}),{status:200,headers:{"Content-Type":"application/json"}})}if(e.data.session?.status==="expired"){let n=e.data.session.failureOutcome==="authorization_expired"||e.data.session.captureMethod==="manual";throw new u.FloPayError(n?"Authorization has expired.":"Checkout session has expired.","api_error",{code:n?"authorization_expired":"checkout_session_expired"})}throw I()}toCheckoutProcessingPending(e,r,n){let o=r.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:N(e,"sessionId")??n,retryAfterMs:this.clampRetryAfterMs(Qt(e,"retryAfterMs")??i??Ke),statusUrl:N(e,"statusUrl"),sessionUrl:N(e,"sessionUrl")}}clampRetryAfterMs(e){return Math.max(0,Math.min(e,Gt))}autoCacheDisplayData(e,r){if(!e)return;let n=r.products??(0,u.foldIntoProducts)(r.items,r.subscriptions);if(n.length===0&&!r.currency)return;let o=r.products!==void 0,s=(0,u.resolveSessionCurrency)(r.currency,o?void 0:r.items,o?void 0:r.subscriptions,n);z(e,{currency:s??void 0,products:n.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 r=pe(e.uuid),n=new Map,o=i=>i?`code:${i}`:void 0;for(let i of r?.products??[]){let a=o(i.code);a&&n.set(a,i)}let s=(e.products??[]).map(i=>{let a=o(i.code),c=a?n.get(a):void 0;return{...i,name:i.name??c?.name??null,totalAmount:i.totalAmount??c?.totalAmount,overrideAmount:i.overrideAmount??c?.overrideAmount,currency:i.currency??c?.currency}});return{...e,currency:e.currency??r?.currency,products:s}}};j.activeVaultCaptureRequests=new Map;var oe=j;function Ze(t,e){let r=oe;return new r(t,e)}var b=require("@flopay/shared");var Me="flopay-vault",sr=3e4,ir=b.THREE_DS_CHALLENGE_WINDOW_MS+sr,ar="Card authentication timed out.",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 cr(t){return t.class==="lifecycle"?t.name:t.class==="technical_error"?t.code:t.class==="expected_outcome"?t.outcome:"sdk.performance"}function Q(t){let e={class:t.class,stage:t.stage};"code"in t&&(e.code=t.code),"provider"in t&&t.provider&&(e.provider=t.provider),"paymentMethodCategory"in t&&t.paymentMethodCategory&&(e.paymentMethodCategory=t.paymentMethodCategory),"outcome"in t&&(e.outcome=t.outcome),"durationMs"in t&&t.durationMs!==void 0&&(e.durationMs=t.durationMs),"durationMode"in t&&t.durationMode&&(e.durationMode=t.durationMode);try{globalThis.Sentry?.addBreadcrumb?.({category:"flopay.telemetry",level:t.class==="technical_error"?"error":"info",message:cr(t),data:e})}catch{}}function se(t,e){return(0,b.buildTelemetryLogEvent)({eventId:"11111111-1111-4111-8111-111111111111",name:t,stage:e,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}var lr=new Set(["authorization_declined","authentication_required","authorization_expired","capture_failed"]);function ur(t){return typeof t=="string"&&lr.has(t)?t:"unknown"}var dr=new Set(["verification_failed","verification_expired"]);function mr(t){return t==null?!0:typeof t=="string"&&dr.has(t)}var pr="vault_mount";function yr(t){return t.failureStage===pr}function tt(t,e){return t&&!yr(e)?{errorCode:"VAULT_SUBMIT_FAILED",stage:"vault_submit",failureCategory:"provider_runtime",reason:ur(e.failureOutcome)}:{errorCode:"VAULT_LOAD_FAILED",stage:"vault_mount",failureCategory:"provider_runtime"}}function rt(t,e,r="checkout"){return r==="card_setup"?t.type==="decline"?"card_setup_declined":"card_setup_succeeded":t.type==="decline"?"payment_declined":t.outcome==="authorized"||e==="manual"?"payment_authorized":"payment_succeeded"}function hr(t,e,r,n="checkout"){let{type:o}=t;if(o==="complete"||o==="decline")return(0,b.buildTelemetryTerminalEvent)({eventId:"22222222-2222-4222-8222-222222222222",outcome:rt(t,r,n),sequence:0,provider:"pcivault",paymentMethodCategory:"card"});if(o==="error"){let a=tt(e,t);return(0,b.buildTelemetryErrorEvent)({eventId:"33333333-3333-4333-8333-333333333333",...a,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}let[s,i]=et[o];return se(s,i)}function gr(t){if(typeof t!="object"||t===null)return!1;let e=t;return e.source===Me&&(e.type==="ready"||e.type==="submitting"||e.type==="blocked"||e.type==="complete"||e.type==="decline"||e.type==="error"||e.type==="action_required")}function fr(t){if(typeof t!="object"||t===null)return;let e=t;if(typeof e.code!="string"||e.code.trim()==="")return;let r=typeof e.message=="string"&&e.message.trim()!==""?e.message:void 0;return r?{code:e.code,message:r}:{code:e.code}}function Cr(t){if(typeof t!="object"||t===null)return;let e=t,r=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||r!=="pending"&&r!=="active"&&r!=="deleted"))return{id:e.id,brand:e.brand,lastFour:e.lastFour,expiryMonth:e.expiryMonth,expiryYear:e.expiryYear,status:r}}function vr(t){if(typeof t!="object"||t===null)return!1;let e=t;return e.source===Me&&e.type==="validation"&&Array.isArray(e.messages)}function Tr(t){if(typeof t!="object"||t===null)return!1;let e=t;return e.source===Me&&e.type==="resize"&&typeof e.height=="number"&&Number.isFinite(e.height)}var H=class{constructor(e={},r){this.provider="pcivault";this.container=null;this.messageHandler=null;this.actionOverlay=null;this.threeDsReturnHandler=null;this.actionOverlayPreviousFocus=null;this.actionOverlayTimer=null;this.messageToken=null;this.expectedOrigin=null;this.theme=void 0;this.submitGateBlocked=!1;this.cardFieldOrder=null;this.cardAutoFocus=!0;this.submitLabel=void 0;this.mountStartedAt=0;this.vaultReadyReported=!1;this.verificationRequired=!1;this.submissionStarted=!1;this.submissionStartedAt=null;this.listeners=new Map;this.config=e,this.ownsTelemetryReporter=!r&&e.telemetry!==!1,this.telemetryReporter=r?.reporter??(this.ownsTelemetryReporter?new R({billingApiUrl:(0,b.resolveBillingApiUrl)(e.billingApiUrl),sdkVersion:b.SDK_VERSION}):void 0)}async mount(e,r){this.ownsTelemetryReporter&&!this.telemetryReporter&&(this.telemetryReporter=new R({billingApiUrl:(0,b.resolveBillingApiUrl)(this.config.billingApiUrl),sdkVersion:b.SDK_VERSION}));let n=this.telemetryReporter;if(this.config.operation==="card_setup"&&n&&this.setupTelemetryReporter!==n){this.setupTelemetryReporter=n;try{n.beginCheckout({checkoutMode:"setup"})}catch{}}if(this.mountStartedAt=this.telemetryReporter?.now?.()??A(),this.vaultReadyReported=!1,this.submissionStarted=!1,this.submissionStartedAt=null,typeof window>"u"||typeof document>"u")throw this.reportVaultLoadFailure(),new b.FloPayError("The vault card form is only available in the browser.","api_error",{code:"card_capture_no_window"});if(!r?.html?.trim())throw this.reportVaultLoadFailure(),new b.FloPayError("No vault capture widget HTML was provided to mount the secure card form.","api_error",{code:"card_capture_no_widget_html"});this.container=e,this.verificationRequired=r.verificationRequired===!0,this.messageToken=r.messageToken??null,this.expectedOrigin=r.expectedOrigin??this.config.expectedOrigin??null,this.theme=r.theme,r.submitLabel!==void 0&&(this.submitLabel=r.submitLabel);try{this.attachMessageListener(),this.injectWidget(e,r.html)}catch(o){throw this.reportVaultLoadFailure(),o}this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),this.postSubmitLabel(),Q(se("vault.widget.mounted","vault_mount")),this.telemetryReporter?.log({name:"vault.widget.mounted",stage:"vault_mount",provider:"pcivault",paymentMethodCategory:"card"}),this.telemetryReporter?.performance?.({stage:"vault_mount",durationMs:Math.max(0,(this.telemetryReporter.now?.()??A())-this.mountStartedAt),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card"}),this.emit("ready",{sessionId:this.config.sessionId})}reportVaultLoadFailure(){this.telemetryReporter?.error({errorCode:"VAULT_LOAD_FAILED",failureCategory:"provider_runtime",stage:"vault_mount",provider:"pcivault",paymentMethodCategory:"card"})}on(e,r){let n=this.listeners.get(e);return n||(n=new Set,this.listeners.set(e,n)),n.add(r),()=>{this.listeners.get(e)?.delete(r)}}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,r){e.innerHTML=r;let n=Array.from(e.querySelectorAll("script"));for(let o of n){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=r=>{if(this.expectedOrigin&&r.origin!==this.expectedOrigin)return;let n=r.data;if(Tr(n)){if(this.messageToken&&n.messageToken!==this.messageToken)return;this.applyHeight(n.height);return}if(vr(n)){if(this.messageToken&&n.messageToken!==this.messageToken)return;let l=n.messages.filter(m=>typeof m=="string"&&m.trim()).join(" ");this.emit("validation",{sessionId:this.config.sessionId,message:l||void 0});return}if(!gr(n)||this.messageToken&&n.messageToken!==this.messageToken)return;let o=this.config.sessionId,s=typeof n.sessionId=="string"?n.sessionId:void 0;if(o&&s&&s!==o||(n.type==="complete"||n.type==="decline")&&o&&s!==o)return;let i=Cr(n.paymentMethod),a=fr(n.vaultOutcome),c={...n.sessionId??this.config.sessionId?{sessionId:n.sessionId??this.config.sessionId}:{},...n.outcome?{outcome:n.outcome}:{},...n.paymentId?{paymentId:n.paymentId}:{},...n.authorizationExpiresAt?{authorizationExpiresAt:n.authorizationExpiresAt}:{},...n.failureOutcome?{failureOutcome:n.failureOutcome}:{},...n.intentId?{intentId:n.intentId}:{},...n.declineReason?{declineReason:n.declineReason}:{},...n.message?{message:n.message}:{},...a?{vaultOutcome:a}:{},...i?{paymentMethod:i}:{}};n.type==="submitting"&&(this.submissionStarted=!0,this.submissionStartedAt=this.telemetryReporter?.now?.()??A()),this.isVerificationStateError(n)?(Q(se("operation.state_transition","vault_mount")),this.telemetryReporter?.log({name:"operation.state_transition",stage:"vault_mount",provider:"pcivault",paymentMethodCategory:"card"})):(Q(hr(n,this.submissionStarted,this.config.captureMethod,this.config.operation)),this.reportOutcome(n)),n.type==="ready"&&(this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),this.postSubmitLabel()),n.type==="action_required"&&n.nextActionRedirectUrl&&this.showActionRequiredOverlay(n.nextActionRedirectUrl),(n.type==="complete"||n.type==="decline"||n.type==="error"||n.type==="submitting")&&this.hideActionRequiredOverlay(),n.type!=="action_required"&&this.emit(n.type,c)};this.messageHandler=e,window.addEventListener("message",e)}isVerificationStateError(e){return e.type==="error"&&this.verificationRequired&&!this.submissionStarted&&mr(e.failureOutcome)}reportOutcome(e){let r=this.telemetryReporter;if(!r)return;let{type:n}=e;if(n==="ready"&&!this.vaultReadyReported&&(this.vaultReadyReported=!0,r.performance({stage:"vault_ready",durationMs:Math.max(0,r.now()-this.mountStartedAt),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card",requestCategory:"provider_sdk"})),n==="complete"||n==="decline"){r.log({name:"vault.terminal",stage:"completion",provider:"pcivault",paymentMethodCategory:"card"}),r.terminal({outcome:rt(e,this.config.captureMethod,this.config.operation),provider:"pcivault",paymentMethodCategory:"card"});return}if(n==="error"){let i=tt(this.submissionStarted,e);r.log({name:"vault.terminal",stage:i.stage,provider:"pcivault",paymentMethodCategory:"card"}),r.error({...i,provider:"pcivault",paymentMethodCategory:"card"});return}if(n==="action_required"){r.log({name:"vault.action.required",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"}),r.log({name:"vault.three_ds.handoff",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"});let i=this.submissionStartedAt;this.submissionStartedAt=null,i!==null&&r.performance({stage:"three_ds_handoff",durationMs:Math.max(0,r.now()-i),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card"}),r.terminal({outcome:"action_required",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"});return}let[o,s]=et[n];r.log({name:o,stage:s,provider:"pcivault",paymentMethodCategory:"card"})}applyTheme(e){this.theme=e,this.postTheme()}postTheme(){this.theme!==void 0&&this.postToHostedWindow({source:"flopay-vault-host",type:"theme",theme:this.theme},this.directiveTargetOrigin())}setSubmitGate(e){this.submitGateBlocked=e,this.postSubmitGate()}postSubmitGate(){this.postToHostedWindow({source:"flopay-vault-host",type:"gate",blocked:this.submitGateBlocked},this.directiveTargetOrigin())}setCardFieldOrder(e,r){this.cardFieldOrder=e,this.cardAutoFocus=r,this.postCardFieldOrder()}postCardFieldOrder(){this.postToHostedWindow({source:"flopay-vault-host",type:"fieldOrder",order:this.cardFieldOrder,autoFocus:this.cardAutoFocus},this.directiveTargetOrigin())}setSubmitLabel(e){this.submitLabel=e,this.postSubmitLabel()}postSubmitLabel(){let e=this.submitLabel,r=this.config.sessionId,{messageToken:n,expectedOrigin:o}=this;e===void 0||!r||!n||!o||this.postToHostedWindow({source:"flopay-vault-host",type:"submitLabel",sessionId:r,messageToken:n,label:e},o)}hostedWindow(){return this.container?.querySelector("iframe")?.contentWindow??null}postToHostedWindow(e,r){let n=this.hostedWindow();if(n)try{n.postMessage(e,r)}catch{}}directiveTargetOrigin(){return this.expectedOrigin??"*"}emit(e,r){for(let n of this.listeners.get(e)??[])n(r)}showActionRequiredOverlay(e){if(typeof document>"u")return;if(this.actionOverlay){let i=this.actionOverlay.querySelector("iframe");i instanceof HTMLIFrameElement&&i.src!==e&&(i.src=e),this.armActionRequiredTimeout();return}this.actionOverlayPreviousFocus=document.activeElement instanceof HTMLElement?document.activeElement:null;let r=document.createElement("div");r.setAttribute("data-flopay-action-required","1"),r.setAttribute("role","dialog"),r.setAttribute("aria-modal","true"),r.setAttribute("aria-label","Card authentication"),r.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 n=document.createElement("iframe");n.setAttribute("title","Card authentication"),n.setAttribute("allow","payment"),n.tabIndex=0,n.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(";"),n.src=e,r.appendChild(n);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()),r.appendChild(o),r.addEventListener("click",i=>{i.target===r&&this.abandonActionRequiredOverlay()});let s=i=>{if(i.source!==n.contentWindow)return;let a=i.data;!a||typeof a!="object"||a.source!=="flopay-vault-3ds-return"||(Q(se("vault.three_ds.returned","three_ds_return")),this.telemetryReporter?.log({name:"vault.three_ds.returned",stage:"three_ds_return",provider:"pcivault",paymentMethodCategory:"card"}),this.hideActionRequiredOverlay())};window.addEventListener("message",s),this.threeDsReturnHandler=s,document.body.appendChild(r),this.actionOverlay=r,n.focus(),this.armActionRequiredTimeout(),Q(se("vault.three_ds.handoff","three_ds_handoff"))}armActionRequiredTimeout(){this.actionOverlayTimer&&clearTimeout(this.actionOverlayTimer),this.actionOverlayTimer=setTimeout(()=>{this.actionOverlayTimer=null,this.actionOverlay&&this.timeOutActionRequiredOverlay()},ir)}reportChallengeAbandoned(){Q((0,b.buildTelemetryTerminalEvent)({eventId:"77777777-7777-4777-8777-777777777777",outcome:"customer_abandoned",stage:"three_ds_handoff",sequence:0,provider:"pcivault",paymentMethodCategory:"card"})),this.telemetryReporter?.terminal({outcome:"customer_abandoned",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"})}timeOutActionRequiredOverlay(){this.reportChallengeAbandoned(),this.hideActionRequiredOverlay(),this.emit("error",{...this.config.sessionId?{sessionId:this.config.sessionId}:{},message:ar})}abandonActionRequiredOverlay(){this.actionOverlay&&(this.reportChallengeAbandoned(),this.hideActionRequiredOverlay(),this.emit("challenge_dismissed",{...this.config.sessionId?{sessionId:this.config.sessionId}:{}}))}hideActionRequiredOverlay(){if(this.actionOverlayTimer&&(clearTimeout(this.actionOverlayTimer),this.actionOverlayTimer=null),this.threeDsReturnHandler&&(window.removeEventListener("message",this.threeDsReturnHandler),this.threeDsReturnHandler=null),!this.actionOverlay)return;this.actionOverlay.parentNode?.removeChild(this.actionOverlay),this.actionOverlay=null;let e=this.actionOverlayPreviousFocus;this.actionOverlayPreviousFocus=null,e?.isConnected&&e.focus()}applyHeight(e){let r=this.container?.querySelector("iframe");if(!r)return;let n=Math.max(0,Math.min(Math.ceil(e),2e3));r.style.height=`${n}px`}};function nt(t,e){let r=H;return new r(t,{reporter:e})}var ot=Symbol.for("@flopay/js.telemetry.bridge.v1");function st(t,e,r){let n=()=>e?.now()??r();Object.defineProperty(t,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:n,elapsed:s=>Math.max(0,n()-s),setCheckoutContext:s=>e?.setCheckoutContext(s),beginCheckout:(s={})=>e?.beginCheckout(s)??n(),disable:()=>e?.disable(),subscribe:s=>e?.subscribe(s)??(()=>{}),flush:()=>e?.flush()??Promise.resolve()}})}function it(t){return t[ot]}var ie=class{now(){return this.telemetryReporter?.now?.()??A()}constructor(e,r,n){this.provider=e,this.config=r,this.telemetryReporter=n??new R({billingApiUrl:(0,k.resolveBillingApiUrl)(r.billingApiUrl),sdkVersion:k.SDK_VERSION,enabled:r.telemetry!==!1}),st(this,this.telemetryReporter,A)}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 H({sessionId:e?.sessionId,captureMethod:e?.captureMethod,telemetry:!1})}async retrieveSession(e,r){if(!e)throw new k.FloPayError("sessionId is required to retrieve a session.","validation_error",{param:"sessionId"});let n=await this.retrieveUnifiedSession(e,r);if(!n.data.session)throw new k.FloPayError("Session not found","api_error");return n.data.session}async retrieveUnifiedSession(e,r){if(!e)throw new k.FloPayError("sessionId is required.","validation_error",{param:"sessionId"});let n=(0,k.resolveBillingApiUrl)(r??this.config.billingApiUrl),o=this.now();this.telemetryReporter?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let s,i,a=l=>{if(s===void 0)return;let m=s,y=i;s=void 0,i=void 0,this.telemetryReporter?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:l,attempt:y}),this.telemetryReporter?.performance({stage:"session_first_byte",durationMs:m,durationMode:"machine",requestCategory:"session_read",statusClass:l,attempt:y})},c=Ze(n,{now:()=>this.telemetryReporter?.now()??A(),onFirstByte:(l,m)=>{s=l,i=m},onRetry:(l,m)=>{this.telemetryReporter?.log({name:"operation.retry",stage:l==="session_read"?"session_read":"processing",requestCategory:l,attempt:m})}});try{let l=await c.getUnifiedCheckoutSession(e);return a("2xx"),this.telemetryReporter?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:"2xx"}),this.telemetryReporter?.log({name:"checkout.data.ready",stage:"checkout_data_ready"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-o,durationMode:"machine",requestCategory:"session_read",statusClass:"2xx"}),l}catch(l){let m=(0,k.classifyTelemetryFailure)(l,l instanceof k.FloPayError&&l.code==="checkout_processing_timeout"?"REQUEST_TIMEOUT":"NETWORK_REQUEST_FAILED");throw a(m.statusClass),this.telemetryReporter?.error({...m,stage:"session_read",provider:"flo",paymentMethodCategory:"unknown"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-o,durationMode:"machine",requestCategory:"session_read",statusClass:m.statusClass}),l}}getRawProvider(){return this.provider.getRawProvider()}destroy(){this.telemetryReporter?.log({name:"checkout.unmount",stage:"unmount"}),this.telemetryReporter?.destroy(),this.provider.destroy()}};function at(t,e,r){let n=ie;return new n(t,e,r)}var U=require("@flopay/shared");var Ie=require("@flopay/shared"),ct=require("@stripe/stripe-js"),X=require("@flopay/shared"),lt=new WeakSet;function ut(t){return t instanceof Ie.FloPayError&&lt.has(t)}var J=class{constructor(){this.name="stripe";this.stripe=null}async initialize(e){if(typeof window>"u")return;let r=await(0,ct.loadStripe)(e.publishableKey,{locale:e.locale??"auto"});if(!r){let n=new Ie.FloPayError("Failed to initialize Stripe. Check your publishable key.","authentication_error");throw lt.add(n),n}this.stripe=r}getRawProvider(){return this.stripe}destroy(){this.stripe=null}};var dt=new Map;function Pe(t){return Array.isArray(t)?t.map(Pe):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[r])=>e.localeCompare(r)).map(([e,r])=>[e,Pe(r)])):t}function br(t,e){return JSON.stringify([t,(0,U.resolveBillingApiUrl)(e?.billingApiUrl),e?.telemetry!==!1,e?.locale??"auto",e?.apiVersion??null,Pe(e?.appearance??null)])}var ve=new Map;async function mt(t,e){if(!t){let a=new R({billingApiUrl:(0,U.resolveBillingApiUrl)(e?.billingApiUrl),sdkVersion:U.SDK_VERSION,enabled:e?.telemetry!==!1});throw a.error({errorCode:"CONFIGURATION_INVALID",stage:"sdk_initialize",paymentMethodCategory:"unknown"}),a.flush().catch(()=>{}).finally(()=>a.destroy()),new U.FloPayError("A publishable key is required to initialize FloPay.","validation_error",{param:"publishableKey"})}let r=br(t,e),n=dt.get(r);if(n)return e?.telemetry!==!1&&it(n)?.log({name:"sdk.cache.hit",stage:"sdk_initialize"}),n;let o=ve.get(r);if(o)return o;let s={...e,publishableKey:t},i=(async()=>{let a=new R({billingApiUrl:(0,U.resolveBillingApiUrl)(s.billingApiUrl),sdkVersion:U.SDK_VERSION,enabled:s.telemetry!==!1}),c=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 l=new J,m=a.now();try{await l.initialize(s)}catch(h){throw a.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:ut(h)?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"unknown"}),a.destroy(),h}let y=a.now();a.log({name:"provider.ready",stage:"provider_ready",provider:"stripe"}),a.log({name:"provider.availability.checked",stage:"provider_ready",provider:"stripe"}),a.log({name:"sdk.initialize.ready",stage:"sdk_initialize"}),a.performance({stage:"sdk_initialize",durationMs:y-c,durationMode:"machine",provider:"stripe"}),a.performance({stage:"provider_ready",durationMs:y-m,durationMode:"machine",provider:"stripe"});let d=at(l,s,a);return dt.set(r,d),d})();ve.set(r,i);try{return await i}finally{ve.get(r)===i&&ve.delete(r)}}var V=require("@flopay/shared"),Sr=1e3,_r=1e3,Rr=15e3;function ae(t){return new V.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:t})}function pt(){return new V.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function yt(t){return t.replace(/\/+$/,"")}function wr(t){return t.status==="succeeded"||t.status==="authorized"||t.status==="declined"}function Ar(t){if(!t||typeof t!="object")return{status:"unknown"};let e=typeof t.status=="string"?t.status:"unknown",r=typeof t.providerIntentId=="string"?t.providerIntentId:null;switch(e){case"succeeded":case"authorized":case"pending":case"timeout":return{status:e,providerIntentId:r};case"declined":return{status:"declined",providerIntentId:r,declineReason:typeof t.declineReason=="string"?t.declineReason:null,gatewayDeclineReason:typeof t.gatewayDeclineReason=="string"?t.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:r,nextActionRedirectUrl:typeof t.nextActionRedirectUrl=="string"?t.nextActionRedirectUrl:null};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}async function xe(t){if(typeof document>"u"||typeof window>"u")throw new V.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(t.signal?.aborted)throw ae();let e=`${yt(t.billingApiUrl)}/v1/checkouts/sessions/${encodeURIComponent(t.sessionId)}/3ds/complete`,r=async()=>{let l=new AbortController,m=()=>l.abort();t.signal?.aborted?l.abort():t.signal?.addEventListener("abort",m);let y=window.setTimeout(()=>l.abort(),Rr);try{let d=await fetch(e,{method:"POST",headers:{"x-checkout-session-token":t.nonce,"content-type":"application/json"},body:"{}",signal:l.signal});if(!d.ok)return{status:"unknown"};let h=await d.json().catch(()=>null);return Ar(h)}catch{return{status:"unknown"}}finally{window.clearTimeout(y),t.signal?.removeEventListener("abort",m)}},n,o=()=>t.pollCompletionEndpoint!==!1?r():(n??(n=r()),n),s=document.activeElement instanceof HTMLElement?document.activeElement:null,i=document.createElement("div");i.setAttribute("data-flopay-auto-3ds-overlay","1"),i.setAttribute("role","dialog"),i.setAttribute("aria-modal","true"),i.setAttribute("aria-label","Card authentication"),i.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 a=document.createElement("iframe");a.setAttribute("title","Card authentication"),a.setAttribute("allow","payment"),a.tabIndex=0,a.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(";");let c=null;try{c=new URL(t.billingApiUrl,window.location.href).origin}catch{c=null}try{let l=await new Promise((m,y)=>{let d=!1,h=0,p=0,C=0,f=!1,v=()=>{window.clearTimeout(h),window.clearInterval(p),window.clearTimeout(C),window.removeEventListener("message",K),a.removeEventListener("load",g),t.signal?.removeEventListener("abort",P)},S=async()=>{if(!(d||f)){f=!0;try{let E=await o();if(d||!wr(E))return;d=!0,v(),m(E)}finally{f=!1}}},g=()=>{t.pollCompletionEndpoint!==!1&&(window.clearTimeout(C),C=window.setTimeout(()=>{S()},250))},P=()=>{d||(d=!0,v(),y(ae()))},K=E=>{if(E.source!==a.contentWindow||c&&E.origin!==c)return;let M=E.data;!M||typeof M!="object"||M.source!=="flopay-vault-3ds-return"||d||(d=!0,v(),m(null))};h=window.setTimeout(()=>{d||(d=!0,v(),y(pt()))},V.THREE_DS_CHALLENGE_WINDOW_MS),t.pollCompletionEndpoint!==!1&&(p=window.setInterval(()=>{S()},_r)),a.addEventListener("load",g),window.addEventListener("message",K),t.signal?.addEventListener("abort",P),a.src=t.nextActionRedirectUrl,i.appendChild(a),document.body.appendChild(i),a.focus(),t.signal?.aborted&&P()});return l||await o()}finally{i.parentNode?.removeChild(i),s?.isConnected&&s.focus()}}function kr(t){return new V.FloPayError("Card was declined.","api_error",{code:t.declineReason??"authorization_declined",...t.gatewayDeclineReason?{declineCode:t.gatewayDeclineReason}:{}})}async function ht(t,e){let r=`${yt(t.billingApiUrl)}/v1/checkouts/sessions/${encodeURIComponent(t.sessionId)}/status`,n=new AbortController,o=new AbortController,s=()=>{n.abort(t.signal?.reason),o.abort(t.signal?.reason)};t.signal?.aborted?s():t.signal?.addEventListener("abort",s,{once:!0});let i=xe({billingApiUrl:t.billingApiUrl,sessionId:t.sessionId,nonce:t.nonce,nextActionRedirectUrl:t.nextActionRedirectUrl,signal:n.signal,pollCompletionEndpoint:!1}),a=e.waitForCheckoutSessionCompletion(t.sessionId,{initialDelayMs:Sr,nonce:t.nonce,statusUrl:r,continueAfterActionRequired:!0,timeoutMs:V.THREE_DS_CHALLENGE_WINDOW_MS+15e3,signal:o.signal});a.catch(()=>{}),i.catch(()=>{});try{let c=await Promise.race([i,a]);if("data"in c)return c;if(c.status==="declined")throw(t.createDeclineError??kr)(c);if(c.status==="timeout")throw pt();return await a}catch(c){throw t.signal?.aborted||c instanceof Error&&c.name==="AbortError"?ae(c):c}finally{t.signal?.removeEventListener("abort",s),n.abort(),o.abort()}}0&&(module.exports={FloPay,PaymentAPI,PciVaultCardCapture,SESSION_CREATE_TELEMETRY,StripeAdapter,cacheSessionDisplayData,clearSessionDisplayData,completeSavedCardNextAction,createCheckoutSession,createCheckoutSessionWithRetries,createSavedCardActionAbortedError,dropThirdPartyOnlyError,getSessionDisplayData,loadFloPay,runSavedCardChallenge,toStripeAppearance,toStripeAppearanceTheme});
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{a as V,b as H,c as W,d as te,e as Y,f as Ee,g as Te,h as L,i as v,j as Ie,k as xe,l as re,m as G,n as oe}from"./chunk-RDVCOFH5.mjs";import{dropThirdPartyOnlyError as Ut}from"@flopay/shared";import{assertCaptureMethodEligible as Fe,buildProductPayload as Me,classifyTelemetryFailure as Ue,FloPayError as A,foldIntoProducts as Oe,IDEMPOTENCY_IN_PROGRESS_CODE as De,IDEMPOTENCY_KEY_HEADER as Le,resolveIdempotencyKey as ne,resolveSessionCurrency as Ne,SDK_VERSION as ae,telemetryStatusClass as ie,withTelemetryHttpDiagnostics as qe}from"@flopay/shared";var Q=5,se=new WeakSet;function Be(e){(typeof e=="object"&&e!==null||typeof e=="function")&&se.add(e)}function ze(e){return(typeof e=="object"&&e!==null||typeof e=="function")&&se.has(e)}function je(e,t){let r=t?.error,o=V(t?.code)??V(r?.code)??`http_${e}`,l=H(t?.message)??H(r?.message)??$e(o,e);return new A(l,"api_error",{code:o,statusCode:e})}function $e(e,t){switch(e){case"CouponLimitExceeded":return`Too many coupon codes \u2014 a checkout session accepts at most ${Q}.`;case"CouponCurrencyUnsupported":return"One of the applied coupons has no price configured for the cart currency.";default:return`Failed to create checkout session (HTTP ${t}).`}}async function le(e,t,r){let{billingApiUrl:o,checkoutBaseUrl:l,items:s=[],subscriptions:c=[],products:n,account:i,successUrl:a,cancelUrl:d,checkoutMode:p="confirm",captureMethod:u,couponCodes:y=[],checkoutMetadata:k,tagsData:b,redirectParams:R={},setCookie:S=!0,clientId:x,currency:F,utmMetadata:C,idempotencyKey:M}=e,f=ne(M);if(y.length>Q)throw new A(`Too many coupon codes \u2014 a checkout session accepts at most ${Q}.`,"validation_error",{code:"CouponLimitExceeded",param:"couponCodes"});let g=n??Oe(s,c);Fe({captureMethod:u,products:g});let w=Ne(F,s,c,g);if(!w)throw new A("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 E={clientId:x,checkoutVersion:ae,successUrl:a,cancelUrl:d,currency:w,checkoutMode:p,products:g.map(h=>Me(h,w)),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:y};u==="manual"&&(E.captureMethod=u),k!==void 0&&(E.checkoutMetadata=k),b&&(E.tagsData=b),C&&C.length>0&&(E.utmMetadata=C);let ke=`${o.replace(/\/+$/,"")}/v1/checkouts/sessions`,ee={"Content-Type":"application/json"};f&&(ee[Le]=f);let _,U,Re={method:"POST",headers:ee,body:JSON.stringify(E),signal:t},T;try{r?.startAttempt(),T=await fetch(ke,Re)}catch(h){throw Be(h),h}try{r?.record(T.status)}catch{}_=T.status;try{U=await T.json()}catch{}if(_>=400)throw qe(je(_,U),T);if(_===201){let h=U?.data?.uuid,K=U?.data?.nonce;if(!h)throw new Error("Checkout session created but no UUID was returned by the billing API");if(!K)throw new A("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"});(g.length>0||w)&&Y(h,{currency:w,products:g.map(m=>({code:m.code??m.providerItemId??m.providerPlanId,type:m.type,name:m.name??m.itemName??m.providerItemName??m.subscriptionName??m.providerPlanName??null,totalAmount:m.totalAmount,overrideAmount:m.overrideAmount,currency:m.currency??w}))});let O=new URL(`${l.replace(/\/+$/,"")}/secure`);O.searchParams.set("id",h);for(let[m,D]of Object.entries(R))O.searchParams.set(m,D);if(S&&typeof window<"u"&&typeof document<"u"){let m=JSON.stringify({origin_url:d}),D=window.location.hostname.split(".").slice(-2).join(".");document.cookie=`checkout_data=${encodeURIComponent(m)}; domain=.${D}; path=/; max-age=3600; SameSite=Lax; Secure;`,document.cookie=`flopay_checkout_token=${encodeURIComponent(K)}; domain=.${D}; path=/; max-age=3600; SameSite=Lax; Secure;`}return typeof window<"u"&&(window.location.href=O.toString()),{status:201,redirectUrl:O.toString(),nonce:K}}return _===204?(typeof window<"u"&&(window.location.href=a),{status:204}):{status:_}}async function Ke(e){let t=de(e),r=ce(t),o=W(e.timeoutMs);try{let l=await le(e,o.signal,r);return r.commit(),ue(t,l),l}catch(l){throw r.commit(),N(t,l),l}finally{o.clear(),P(t.reporter)}}function ce(e){let t=!1,r=e.startedAt,o;return{startAttempt(){r=e.reporter.now()},record(l){o={status:l,durationMs:Math.max(0,e.reporter.now()-r),attempt:e.attempt}},commit(){if(t||!o)return;t=!0;let l=ie(o.status);e.reporter.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:l,attempt:o.attempt}),e.reporter.performance({stage:"session_first_byte",durationMs:o.durationMs,durationMode:"machine",requestCategory:"session_create",statusClass:l,attempt:o.attempt})}}}function de(e){let t=new v({billingApiUrl:e.billingApiUrl,sdkVersion:ae,enabled:e.telemetry!==!1}),r=t.now();return t.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"}),{reporter:t,startedAt:r,attempt:0}}function ue(e,t){let r=ie(t.status);e.reporter.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:r}),e.reporter.performance({stage:"session_create",durationMs:e.reporter.now()-e.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:r,attempt:e.attempt})}function N(e,t){let{reporter:r}=e,o=Ue(t,"CHECKOUT_SESSION_CREATE_FAILED");if(r.performance({stage:"session_create",durationMs:r.now()-e.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:o.statusClass,attempt:e.attempt}),t instanceof A&&t.type==="validation_error"){r.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"});return}if(o.statusClass==="4xx"){r.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create",statusClass:"4xx"});return}r.error({...o,stage:"session_create",requestCategory:"session_create"})}function P(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}async function Ve(e){let{maxRetries:t=2,...r}=e,o=de(e),l=ce(o);if(!Number.isFinite(t)||!Number.isInteger(t)||t<0||t>=3)throw o.reporter.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),P(o.reporter),new Error(`Number of retries must be an integer between 0 and ${2}`);let s={...r,idempotencyKey:ne(r.idempotencyKey)},c=W(r.timeoutMs),n;for(let i=0;i<=t;i++){o.attempt=i;try{let a=await le(s,c.signal,l);return l.commit(),ue(o,a),c.clear(),P(o.reporter),a}catch(a){n=a;let d=a instanceof Error&&a.name==="AbortError",p=ze(a),u=a instanceof A&&a.code===De;if((d||p||u)&&!c.signal.aborted&&i<t){o.reporter.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:i+1});try{await te(i,c.signal)}catch(y){throw l.commit(),N(o,y),c.clear(),P(o.reporter),y}continue}throw l.commit(),N(o,a),c.clear(),P(o.reporter),a}}throw l.commit(),N(o,n),c.clear(),P(o.reporter),n??new Error("Unknown error during checkout session creation")}import{classifyTelemetryFailure as He,FloPayError as q,resolveBillingApiUrl as fe,SDK_VERSION as We}from"@flopay/shared";var me=Symbol.for("@flopay/js.telemetry.bridge.v1");function pe(e,t,r){let o=()=>t?.now()??r();Object.defineProperty(e,me,{configurable:!1,enumerable:!1,writable:!1,value:{error:s=>t?.error(s),log:s=>t?.log(s),performance:s=>t?.performance(s),terminal:s=>t?.terminal(s),now:o,elapsed:s=>Math.max(0,o()-s),setCheckoutContext:s=>t?.setCheckoutContext(s),beginCheckout:(s={})=>t?.beginCheckout(s)??o(),disable:()=>t?.disable(),subscribe:s=>t?.subscribe(s)??(()=>{}),flush:()=>t?.flush()??Promise.resolve()}})}function ye(e){return e[me]}var B=class{now(){return this.telemetryReporter?.now?.()??L()}constructor(t,r,o){this.provider=t,this.config=r,this.telemetryReporter=o??new v({billingApiUrl:fe(r.billingApiUrl),sdkVersion:We,enabled:r.telemetry!==!1}),pe(this,this.telemetryReporter,L)}cardCapture(t){return this.telemetryReporter?.log({name:"vault.capture.requested",stage:"vault_request",provider:"pcivault",paymentMethodCategory:"card"}),this.telemetryReporter?oe({sessionId:t?.sessionId,captureMethod:t?.captureMethod},this.telemetryReporter):new G({sessionId:t?.sessionId,captureMethod:t?.captureMethod,telemetry:!1})}async retrieveSession(t,r){if(!t)throw new q("sessionId is required to retrieve a session.","validation_error",{param:"sessionId"});let o=await this.retrieveUnifiedSession(t,r);if(!o.data.session)throw new q("Session not found","api_error");return o.data.session}async retrieveUnifiedSession(t,r){if(!t)throw new q("sessionId is required.","validation_error",{param:"sessionId"});let o=fe(r??this.config.billingApiUrl),l=this.now();this.telemetryReporter?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let s,c,n=a=>{if(s===void 0)return;let d=s,p=c;s=void 0,c=void 0,this.telemetryReporter?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:a,attempt:p}),this.telemetryReporter?.performance({stage:"session_first_byte",durationMs:d,durationMode:"machine",requestCategory:"session_read",statusClass:a,attempt:p})},i=re(o,{now:()=>this.telemetryReporter?.now()??L(),onFirstByte:(a,d)=>{s=a,c=d},onRetry:(a,d)=>{this.telemetryReporter?.log({name:"operation.retry",stage:a==="session_read"?"session_read":"processing",requestCategory:a,attempt:d})}});try{let a=await i.getUnifiedCheckoutSession(t);return n("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()-l,durationMode:"machine",requestCategory:"session_read",statusClass:"2xx"}),a}catch(a){let d=He(a,a instanceof q&&a.code==="checkout_processing_timeout"?"REQUEST_TIMEOUT":"NETWORK_REQUEST_FAILED");throw n(d.statusClass),this.telemetryReporter?.error({...d,stage:"session_read",provider:"flo",paymentMethodCategory:"unknown"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-l,durationMode:"machine",requestCategory:"session_read",statusClass:d.statusClass}),a}}getRawProvider(){return this.provider.getRawProvider()}destroy(){this.telemetryReporter?.log({name:"checkout.unmount",stage:"unmount"}),this.telemetryReporter?.destroy(),this.provider.destroy()}};function ge(e,t,r){let o=B;return new o(e,t,r)}import{FloPayError as Qe,resolveBillingApiUrl as X,SDK_VERSION as ve}from"@flopay/shared";import{FloPayError as he}from"@flopay/shared";import{loadStripe as Ye}from"@stripe/stripe-js";import{toStripeAppearance as Ge,toStripeAppearanceTheme as Je}from"@flopay/shared";var Ce=new WeakSet;function we(e){return e instanceof he&&Ce.has(e)}var I=class{constructor(){this.name="stripe";this.stripe=null}async initialize(t){if(typeof window>"u")return;let r=await Ye(t.publishableKey,{locale:t.locale??"auto"});if(!r){let o=new he("Failed to initialize Stripe. Check your publishable key.","authentication_error");throw Ce.add(o),o}this.stripe=r}getRawProvider(){return this.stripe}destroy(){this.stripe=null}};var be=new Map;function Z(e){return Array.isArray(e)?e.map(Z):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,Z(r)])):e}function Xe(e,t){return JSON.stringify([e,X(t?.billingApiUrl),t?.telemetry!==!1,t?.locale??"auto",t?.apiVersion??null,Z(t?.appearance??null)])}var z=new Map;async function Ze(e,t){if(!e){let n=new v({billingApiUrl:X(t?.billingApiUrl),sdkVersion:ve,enabled:t?.telemetry!==!1});throw n.error({errorCode:"CONFIGURATION_INVALID",stage:"sdk_initialize",paymentMethodCategory:"unknown"}),n.flush().catch(()=>{}).finally(()=>n.destroy()),new Qe("A publishable key is required to initialize FloPay.","validation_error",{param:"publishableKey"})}let r=Xe(e,t),o=be.get(r);if(o)return t?.telemetry!==!1&&ye(o)?.log({name:"sdk.cache.hit",stage:"sdk_initialize"}),o;let l=z.get(r);if(l)return l;let s={...t,publishableKey:e},c=(async()=>{let n=new v({billingApiUrl:X(s.billingApiUrl),sdkVersion:ve,enabled:s.telemetry!==!1}),i=n.now();n.log({name:"sdk.initialize.started",stage:"sdk_initialize"}),n.log({name:"sdk.cache.miss",stage:"sdk_initialize"}),n.log({name:"provider.load.started",stage:"provider_load",provider:"stripe"});let a=new I,d=n.now();try{await a.initialize(s)}catch(y){throw n.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:we(y)?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"unknown"}),n.destroy(),y}let p=n.now();n.log({name:"provider.ready",stage:"provider_ready",provider:"stripe"}),n.log({name:"provider.availability.checked",stage:"provider_ready",provider:"stripe"}),n.log({name:"sdk.initialize.ready",stage:"sdk_initialize"}),n.performance({stage:"sdk_initialize",durationMs:p-i,durationMode:"machine",provider:"stripe"}),n.performance({stage:"provider_ready",durationMs:p-d,durationMode:"machine",provider:"stripe"});let u=ge(a,s,n);return be.set(r,u),u})();z.set(r,c);try{return await c}finally{z.get(r)===c&&z.delete(r)}}import{FloPayError as $,THREE_DS_CHALLENGE_WINDOW_MS as Se}from"@flopay/shared";var et=1e3,tt=1e3,rt=15e3;function j(e){return new $("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function _e(){return new $("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function Pe(e){return e.replace(/\/+$/,"")}function ot(e){return e.status==="succeeded"||e.status==="authorized"||e.status==="declined"}function nt(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",r=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":case"authorized":case"pending":case"timeout":return{status:t,providerIntentId:r};case"declined":return{status:"declined",providerIntentId:r,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:r,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}async function Ae(e){if(typeof document>"u"||typeof window>"u")throw new $("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw j();let t=`${Pe(e.billingApiUrl)}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,r=async()=>{let a=new AbortController,d=()=>a.abort();e.signal?.aborted?a.abort():e.signal?.addEventListener("abort",d);let p=window.setTimeout(()=>a.abort(),rt);try{let u=await fetch(t,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:a.signal});if(!u.ok)return{status:"unknown"};let y=await u.json().catch(()=>null);return nt(y)}catch{return{status:"unknown"}}finally{window.clearTimeout(p),e.signal?.removeEventListener("abort",d)}},o,l=()=>e.pollCompletionEndpoint!==!1?r():(o??(o=r()),o),s=document.activeElement instanceof HTMLElement?document.activeElement:null,c=document.createElement("div");c.setAttribute("data-flopay-auto-3ds-overlay","1"),c.setAttribute("role","dialog"),c.setAttribute("aria-modal","true"),c.setAttribute("aria-label","Card authentication"),c.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 n=document.createElement("iframe");n.setAttribute("title","Card authentication"),n.setAttribute("allow","payment"),n.tabIndex=0,n.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(";");let i=null;try{i=new URL(e.billingApiUrl,window.location.href).origin}catch{i=null}try{let a=await new Promise((d,p)=>{let u=!1,y=0,k=0,b=0,R=!1,S=()=>{window.clearTimeout(y),window.clearInterval(k),window.clearTimeout(b),window.removeEventListener("message",M),n.removeEventListener("load",F),e.signal?.removeEventListener("abort",C)},x=async()=>{if(!(u||R)){R=!0;try{let f=await l();if(u||!ot(f))return;u=!0,S(),d(f)}finally{R=!1}}},F=()=>{e.pollCompletionEndpoint!==!1&&(window.clearTimeout(b),b=window.setTimeout(()=>{x()},250))},C=()=>{u||(u=!0,S(),p(j()))},M=f=>{if(f.source!==n.contentWindow||i&&f.origin!==i)return;let g=f.data;!g||typeof g!="object"||g.source!=="flopay-vault-3ds-return"||u||(u=!0,S(),d(null))};y=window.setTimeout(()=>{u||(u=!0,S(),p(_e()))},Se),e.pollCompletionEndpoint!==!1&&(k=window.setInterval(()=>{x()},tt)),n.addEventListener("load",F),window.addEventListener("message",M),e.signal?.addEventListener("abort",C),n.src=e.nextActionRedirectUrl,c.appendChild(n),document.body.appendChild(c),n.focus(),e.signal?.aborted&&C()});return a||await l()}finally{c.parentNode?.removeChild(c),s?.isConnected&&s.focus()}}function at(e){return new $("Card was declined.","api_error",{code:e.declineReason??"authorization_declined",...e.gatewayDeclineReason?{declineCode:e.gatewayDeclineReason}:{}})}async function it(e,t){let r=`${Pe(e.billingApiUrl)}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/status`,o=new AbortController,l=new AbortController,s=()=>{o.abort(e.signal?.reason),l.abort(e.signal?.reason)};e.signal?.aborted?s():e.signal?.addEventListener("abort",s,{once:!0});let c=Ae({billingApiUrl:e.billingApiUrl,sessionId:e.sessionId,nonce:e.nonce,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:o.signal,pollCompletionEndpoint:!1}),n=t.waitForCheckoutSessionCompletion(e.sessionId,{initialDelayMs:et,nonce:e.nonce,statusUrl:r,continueAfterActionRequired:!0,timeoutMs:Se+15e3,signal:l.signal});n.catch(()=>{}),c.catch(()=>{});try{let i=await Promise.race([c,n]);if("data"in i)return i;if(i.status==="declined")throw(e.createDeclineError??at)(i);if(i.status==="timeout")throw _e();return await n}catch(i){throw e.signal?.aborted||i instanceof Error&&i.name==="AbortError"?j(i):i}finally{e.signal?.removeEventListener("abort",s),o.abort(),l.abort()}}export{B as FloPay,xe as PaymentAPI,G as PciVaultCardCapture,Ie as SESSION_CREATE_TELEMETRY,I as StripeAdapter,Y as cacheSessionDisplayData,Te as clearSessionDisplayData,it as completeSavedCardNextAction,Ke as createCheckoutSession,Ve as createCheckoutSessionWithRetries,j as createSavedCardActionAbortedError,Ut as dropThirdPartyOnlyError,Ee as getSessionDisplayData,Ze as loadFloPay,Ae as runSavedCardChallenge,Ge as toStripeAppearance,Je as toStripeAppearanceTheme};
1
+ import{a as V,b as H,c as W,d as te,e as Y,f as Ee,g as Te,h as L,i as v,j as Ie,k as xe,l as re,m as G,n as oe}from"./chunk-6AT35Z4D.mjs";import{dropThirdPartyOnlyError as Ut}from"@flopay/shared";import{assertCaptureMethodEligible as Fe,buildProductPayload as Me,classifyTelemetryFailure as Ue,FloPayError as A,foldIntoProducts as Oe,IDEMPOTENCY_IN_PROGRESS_CODE as De,IDEMPOTENCY_KEY_HEADER as Le,resolveIdempotencyKey as ne,resolveSessionCurrency as Ne,SDK_VERSION as ae,telemetryStatusClass as ie,withTelemetryHttpDiagnostics as qe}from"@flopay/shared";var Q=5,se=new WeakSet;function Be(e){(typeof e=="object"&&e!==null||typeof e=="function")&&se.add(e)}function ze(e){return(typeof e=="object"&&e!==null||typeof e=="function")&&se.has(e)}function je(e,t){let r=t?.error,o=V(t?.code)??V(r?.code)??`http_${e}`,l=H(t?.message)??H(r?.message)??$e(o,e);return new A(l,"api_error",{code:o,statusCode:e})}function $e(e,t){switch(e){case"CouponLimitExceeded":return`Too many coupon codes \u2014 a checkout session accepts at most ${Q}.`;case"CouponCurrencyUnsupported":return"One of the applied coupons has no price configured for the cart currency.";default:return`Failed to create checkout session (HTTP ${t}).`}}async function le(e,t,r){let{billingApiUrl:o,checkoutBaseUrl:l,items:s=[],subscriptions:c=[],products:n,account:i,successUrl:a,cancelUrl:d,checkoutMode:p="confirm",captureMethod:u,couponCodes:y=[],checkoutMetadata:k,tagsData:b,redirectParams:R={},setCookie:S=!0,clientId:x,currency:F,utmMetadata:C,idempotencyKey:M}=e,f=ne(M);if(y.length>Q)throw new A(`Too many coupon codes \u2014 a checkout session accepts at most ${Q}.`,"validation_error",{code:"CouponLimitExceeded",param:"couponCodes"});let g=n??Oe(s,c);Fe({captureMethod:u,products:g});let w=Ne(F,s,c,g);if(!w)throw new A("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 E={clientId:x,checkoutVersion:ae,successUrl:a,cancelUrl:d,currency:w,checkoutMode:p,products:g.map(h=>Me(h,w)),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:y};u==="manual"&&(E.captureMethod=u),k!==void 0&&(E.checkoutMetadata=k),b&&(E.tagsData=b),C&&C.length>0&&(E.utmMetadata=C);let ke=`${o.replace(/\/+$/,"")}/v1/checkouts/sessions`,ee={"Content-Type":"application/json"};f&&(ee[Le]=f);let _,U,Re={method:"POST",headers:ee,body:JSON.stringify(E),signal:t},T;try{r?.startAttempt(),T=await fetch(ke,Re)}catch(h){throw Be(h),h}try{r?.record(T.status)}catch{}_=T.status;try{U=await T.json()}catch{}if(_>=400)throw qe(je(_,U),T);if(_===201){let h=U?.data?.uuid,K=U?.data?.nonce;if(!h)throw new Error("Checkout session created but no UUID was returned by the billing API");if(!K)throw new A("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"});(g.length>0||w)&&Y(h,{currency:w,products:g.map(m=>({code:m.code??m.providerItemId??m.providerPlanId,type:m.type,name:m.name??m.itemName??m.providerItemName??m.subscriptionName??m.providerPlanName??null,totalAmount:m.totalAmount,overrideAmount:m.overrideAmount,currency:m.currency??w}))});let O=new URL(`${l.replace(/\/+$/,"")}/secure`);O.searchParams.set("id",h);for(let[m,D]of Object.entries(R))O.searchParams.set(m,D);if(S&&typeof window<"u"&&typeof document<"u"){let m=JSON.stringify({origin_url:d}),D=window.location.hostname.split(".").slice(-2).join(".");document.cookie=`checkout_data=${encodeURIComponent(m)}; domain=.${D}; path=/; max-age=3600; SameSite=Lax; Secure;`,document.cookie=`flopay_checkout_token=${encodeURIComponent(K)}; domain=.${D}; path=/; max-age=3600; SameSite=Lax; Secure;`}return typeof window<"u"&&(window.location.href=O.toString()),{status:201,redirectUrl:O.toString(),nonce:K}}return _===204?(typeof window<"u"&&(window.location.href=a),{status:204}):{status:_}}async function Ke(e){let t=de(e),r=ce(t),o=W(e.timeoutMs);try{let l=await le(e,o.signal,r);return r.commit(),ue(t,l),l}catch(l){throw r.commit(),N(t,l),l}finally{o.clear(),P(t.reporter)}}function ce(e){let t=!1,r=e.startedAt,o;return{startAttempt(){r=e.reporter.now()},record(l){o={status:l,durationMs:Math.max(0,e.reporter.now()-r),attempt:e.attempt}},commit(){if(t||!o)return;t=!0;let l=ie(o.status);e.reporter.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:l,attempt:o.attempt}),e.reporter.performance({stage:"session_first_byte",durationMs:o.durationMs,durationMode:"machine",requestCategory:"session_create",statusClass:l,attempt:o.attempt})}}}function de(e){let t=new v({billingApiUrl:e.billingApiUrl,sdkVersion:ae,enabled:e.telemetry!==!1}),r=t.now();return t.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"}),{reporter:t,startedAt:r,attempt:0}}function ue(e,t){let r=ie(t.status);e.reporter.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:r}),e.reporter.performance({stage:"session_create",durationMs:e.reporter.now()-e.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:r,attempt:e.attempt})}function N(e,t){let{reporter:r}=e,o=Ue(t,"CHECKOUT_SESSION_CREATE_FAILED");if(r.performance({stage:"session_create",durationMs:r.now()-e.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:o.statusClass,attempt:e.attempt}),t instanceof A&&t.type==="validation_error"){r.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"});return}if(o.statusClass==="4xx"){r.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create",statusClass:"4xx"});return}r.error({...o,stage:"session_create",requestCategory:"session_create"})}function P(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}async function Ve(e){let{maxRetries:t=2,...r}=e,o=de(e),l=ce(o);if(!Number.isFinite(t)||!Number.isInteger(t)||t<0||t>=3)throw o.reporter.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),P(o.reporter),new Error(`Number of retries must be an integer between 0 and ${2}`);let s={...r,idempotencyKey:ne(r.idempotencyKey)},c=W(r.timeoutMs),n;for(let i=0;i<=t;i++){o.attempt=i;try{let a=await le(s,c.signal,l);return l.commit(),ue(o,a),c.clear(),P(o.reporter),a}catch(a){n=a;let d=a instanceof Error&&a.name==="AbortError",p=ze(a),u=a instanceof A&&a.code===De;if((d||p||u)&&!c.signal.aborted&&i<t){o.reporter.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:i+1});try{await te(i,c.signal)}catch(y){throw l.commit(),N(o,y),c.clear(),P(o.reporter),y}continue}throw l.commit(),N(o,a),c.clear(),P(o.reporter),a}}throw l.commit(),N(o,n),c.clear(),P(o.reporter),n??new Error("Unknown error during checkout session creation")}import{classifyTelemetryFailure as He,FloPayError as q,resolveBillingApiUrl as fe,SDK_VERSION as We}from"@flopay/shared";var me=Symbol.for("@flopay/js.telemetry.bridge.v1");function pe(e,t,r){let o=()=>t?.now()??r();Object.defineProperty(e,me,{configurable:!1,enumerable:!1,writable:!1,value:{error:s=>t?.error(s),log:s=>t?.log(s),performance:s=>t?.performance(s),terminal:s=>t?.terminal(s),now:o,elapsed:s=>Math.max(0,o()-s),setCheckoutContext:s=>t?.setCheckoutContext(s),beginCheckout:(s={})=>t?.beginCheckout(s)??o(),disable:()=>t?.disable(),subscribe:s=>t?.subscribe(s)??(()=>{}),flush:()=>t?.flush()??Promise.resolve()}})}function ye(e){return e[me]}var B=class{now(){return this.telemetryReporter?.now?.()??L()}constructor(t,r,o){this.provider=t,this.config=r,this.telemetryReporter=o??new v({billingApiUrl:fe(r.billingApiUrl),sdkVersion:We,enabled:r.telemetry!==!1}),pe(this,this.telemetryReporter,L)}cardCapture(t){return this.telemetryReporter?.log({name:"vault.capture.requested",stage:"vault_request",provider:"pcivault",paymentMethodCategory:"card"}),this.telemetryReporter?oe({sessionId:t?.sessionId,captureMethod:t?.captureMethod},this.telemetryReporter):new G({sessionId:t?.sessionId,captureMethod:t?.captureMethod,telemetry:!1})}async retrieveSession(t,r){if(!t)throw new q("sessionId is required to retrieve a session.","validation_error",{param:"sessionId"});let o=await this.retrieveUnifiedSession(t,r);if(!o.data.session)throw new q("Session not found","api_error");return o.data.session}async retrieveUnifiedSession(t,r){if(!t)throw new q("sessionId is required.","validation_error",{param:"sessionId"});let o=fe(r??this.config.billingApiUrl),l=this.now();this.telemetryReporter?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let s,c,n=a=>{if(s===void 0)return;let d=s,p=c;s=void 0,c=void 0,this.telemetryReporter?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:a,attempt:p}),this.telemetryReporter?.performance({stage:"session_first_byte",durationMs:d,durationMode:"machine",requestCategory:"session_read",statusClass:a,attempt:p})},i=re(o,{now:()=>this.telemetryReporter?.now()??L(),onFirstByte:(a,d)=>{s=a,c=d},onRetry:(a,d)=>{this.telemetryReporter?.log({name:"operation.retry",stage:a==="session_read"?"session_read":"processing",requestCategory:a,attempt:d})}});try{let a=await i.getUnifiedCheckoutSession(t);return n("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()-l,durationMode:"machine",requestCategory:"session_read",statusClass:"2xx"}),a}catch(a){let d=He(a,a instanceof q&&a.code==="checkout_processing_timeout"?"REQUEST_TIMEOUT":"NETWORK_REQUEST_FAILED");throw n(d.statusClass),this.telemetryReporter?.error({...d,stage:"session_read",provider:"flo",paymentMethodCategory:"unknown"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-l,durationMode:"machine",requestCategory:"session_read",statusClass:d.statusClass}),a}}getRawProvider(){return this.provider.getRawProvider()}destroy(){this.telemetryReporter?.log({name:"checkout.unmount",stage:"unmount"}),this.telemetryReporter?.destroy(),this.provider.destroy()}};function ge(e,t,r){let o=B;return new o(e,t,r)}import{FloPayError as Qe,resolveBillingApiUrl as X,SDK_VERSION as ve}from"@flopay/shared";import{FloPayError as he}from"@flopay/shared";import{loadStripe as Ye}from"@stripe/stripe-js";import{toStripeAppearance as Ge,toStripeAppearanceTheme as Je}from"@flopay/shared";var Ce=new WeakSet;function we(e){return e instanceof he&&Ce.has(e)}var I=class{constructor(){this.name="stripe";this.stripe=null}async initialize(t){if(typeof window>"u")return;let r=await Ye(t.publishableKey,{locale:t.locale??"auto"});if(!r){let o=new he("Failed to initialize Stripe. Check your publishable key.","authentication_error");throw Ce.add(o),o}this.stripe=r}getRawProvider(){return this.stripe}destroy(){this.stripe=null}};var be=new Map;function Z(e){return Array.isArray(e)?e.map(Z):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,Z(r)])):e}function Xe(e,t){return JSON.stringify([e,X(t?.billingApiUrl),t?.telemetry!==!1,t?.locale??"auto",t?.apiVersion??null,Z(t?.appearance??null)])}var z=new Map;async function Ze(e,t){if(!e){let n=new v({billingApiUrl:X(t?.billingApiUrl),sdkVersion:ve,enabled:t?.telemetry!==!1});throw n.error({errorCode:"CONFIGURATION_INVALID",stage:"sdk_initialize",paymentMethodCategory:"unknown"}),n.flush().catch(()=>{}).finally(()=>n.destroy()),new Qe("A publishable key is required to initialize FloPay.","validation_error",{param:"publishableKey"})}let r=Xe(e,t),o=be.get(r);if(o)return t?.telemetry!==!1&&ye(o)?.log({name:"sdk.cache.hit",stage:"sdk_initialize"}),o;let l=z.get(r);if(l)return l;let s={...t,publishableKey:e},c=(async()=>{let n=new v({billingApiUrl:X(s.billingApiUrl),sdkVersion:ve,enabled:s.telemetry!==!1}),i=n.now();n.log({name:"sdk.initialize.started",stage:"sdk_initialize"}),n.log({name:"sdk.cache.miss",stage:"sdk_initialize"}),n.log({name:"provider.load.started",stage:"provider_load",provider:"stripe"});let a=new I,d=n.now();try{await a.initialize(s)}catch(y){throw n.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:we(y)?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"unknown"}),n.destroy(),y}let p=n.now();n.log({name:"provider.ready",stage:"provider_ready",provider:"stripe"}),n.log({name:"provider.availability.checked",stage:"provider_ready",provider:"stripe"}),n.log({name:"sdk.initialize.ready",stage:"sdk_initialize"}),n.performance({stage:"sdk_initialize",durationMs:p-i,durationMode:"machine",provider:"stripe"}),n.performance({stage:"provider_ready",durationMs:p-d,durationMode:"machine",provider:"stripe"});let u=ge(a,s,n);return be.set(r,u),u})();z.set(r,c);try{return await c}finally{z.get(r)===c&&z.delete(r)}}import{FloPayError as $,THREE_DS_CHALLENGE_WINDOW_MS as Se}from"@flopay/shared";var et=1e3,tt=1e3,rt=15e3;function j(e){return new $("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function _e(){return new $("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function Pe(e){return e.replace(/\/+$/,"")}function ot(e){return e.status==="succeeded"||e.status==="authorized"||e.status==="declined"}function nt(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",r=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":case"authorized":case"pending":case"timeout":return{status:t,providerIntentId:r};case"declined":return{status:"declined",providerIntentId:r,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:r,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}async function Ae(e){if(typeof document>"u"||typeof window>"u")throw new $("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw j();let t=`${Pe(e.billingApiUrl)}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,r=async()=>{let a=new AbortController,d=()=>a.abort();e.signal?.aborted?a.abort():e.signal?.addEventListener("abort",d);let p=window.setTimeout(()=>a.abort(),rt);try{let u=await fetch(t,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:a.signal});if(!u.ok)return{status:"unknown"};let y=await u.json().catch(()=>null);return nt(y)}catch{return{status:"unknown"}}finally{window.clearTimeout(p),e.signal?.removeEventListener("abort",d)}},o,l=()=>e.pollCompletionEndpoint!==!1?r():(o??(o=r()),o),s=document.activeElement instanceof HTMLElement?document.activeElement:null,c=document.createElement("div");c.setAttribute("data-flopay-auto-3ds-overlay","1"),c.setAttribute("role","dialog"),c.setAttribute("aria-modal","true"),c.setAttribute("aria-label","Card authentication"),c.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 n=document.createElement("iframe");n.setAttribute("title","Card authentication"),n.setAttribute("allow","payment"),n.tabIndex=0,n.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(";");let i=null;try{i=new URL(e.billingApiUrl,window.location.href).origin}catch{i=null}try{let a=await new Promise((d,p)=>{let u=!1,y=0,k=0,b=0,R=!1,S=()=>{window.clearTimeout(y),window.clearInterval(k),window.clearTimeout(b),window.removeEventListener("message",M),n.removeEventListener("load",F),e.signal?.removeEventListener("abort",C)},x=async()=>{if(!(u||R)){R=!0;try{let f=await l();if(u||!ot(f))return;u=!0,S(),d(f)}finally{R=!1}}},F=()=>{e.pollCompletionEndpoint!==!1&&(window.clearTimeout(b),b=window.setTimeout(()=>{x()},250))},C=()=>{u||(u=!0,S(),p(j()))},M=f=>{if(f.source!==n.contentWindow||i&&f.origin!==i)return;let g=f.data;!g||typeof g!="object"||g.source!=="flopay-vault-3ds-return"||u||(u=!0,S(),d(null))};y=window.setTimeout(()=>{u||(u=!0,S(),p(_e()))},Se),e.pollCompletionEndpoint!==!1&&(k=window.setInterval(()=>{x()},tt)),n.addEventListener("load",F),window.addEventListener("message",M),e.signal?.addEventListener("abort",C),n.src=e.nextActionRedirectUrl,c.appendChild(n),document.body.appendChild(c),n.focus(),e.signal?.aborted&&C()});return a||await l()}finally{c.parentNode?.removeChild(c),s?.isConnected&&s.focus()}}function at(e){return new $("Card was declined.","api_error",{code:e.declineReason??"authorization_declined",...e.gatewayDeclineReason?{declineCode:e.gatewayDeclineReason}:{}})}async function it(e,t){let r=`${Pe(e.billingApiUrl)}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/status`,o=new AbortController,l=new AbortController,s=()=>{o.abort(e.signal?.reason),l.abort(e.signal?.reason)};e.signal?.aborted?s():e.signal?.addEventListener("abort",s,{once:!0});let c=Ae({billingApiUrl:e.billingApiUrl,sessionId:e.sessionId,nonce:e.nonce,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:o.signal,pollCompletionEndpoint:!1}),n=t.waitForCheckoutSessionCompletion(e.sessionId,{initialDelayMs:et,nonce:e.nonce,statusUrl:r,continueAfterActionRequired:!0,timeoutMs:Se+15e3,signal:l.signal});n.catch(()=>{}),c.catch(()=>{});try{let i=await Promise.race([c,n]);if("data"in i)return i;if(i.status==="declined")throw(e.createDeclineError??at)(i);if(i.status==="timeout")throw _e();return await n}catch(i){throw e.signal?.aborted||i instanceof Error&&i.name==="AbortError"?j(i):i}finally{e.signal?.removeEventListener("abort",s),o.abort(),l.abort()}}export{B as FloPay,xe as PaymentAPI,G as PciVaultCardCapture,Ie as SESSION_CREATE_TELEMETRY,I as StripeAdapter,Y as cacheSessionDisplayData,Te as clearSessionDisplayData,it as completeSavedCardNextAction,Ke as createCheckoutSession,Ve as createCheckoutSessionWithRetries,j as createSavedCardActionAbortedError,Ut as dropThirdPartyOnlyError,Ee as getSessionDisplayData,Ze as loadFloPay,Ae as runSavedCardChallenge,Ge as toStripeAppearance,Je as toStripeAppearanceTheme};