@flopay/js 1.14.11 → 1.14.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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-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};
1
+ import{a as Y,b as G,c as J,d as ne,e as Q,f as Oe,g as Ue,h as X,i as ie,j as se,k as ae,l as le,m as ce,n as z,o as T,p as Le,q as Be,r as de,s as Z,t as ue}from"./chunk-2ZB6JO3E.mjs";import{dropThirdPartyOnlyError as Kt}from"@flopay/shared";import{assertCaptureMethodEligible as Ne,buildProductPayload as qe,classifyTelemetryFailure as ze,FloPayError as O,foldIntoProducts as je,IDEMPOTENCY_IN_PROGRESS_CODE as Ve,IDEMPOTENCY_KEY_HEADER as $e,resolveIdempotencyKey as me,resolveSessionCurrency as Ke,SDK_VERSION as pe,telemetryStatusClass as ye,withTelemetryHttpDiagnostics as He}from"@flopay/shared";var te=5,fe=new WeakSet;function We(e){(typeof e=="object"&&e!==null||typeof e=="function")&&fe.add(e)}function Ye(e){return(typeof e=="object"&&e!==null||typeof e=="function")&&fe.has(e)}function Ge(e,t){let r=t?.error,o=Y(t?.code)??Y(r?.code)??`http_${e}`,s=G(t?.message)??G(r?.message)??Je(o,e);return new O(s,"api_error",{code:o,statusCode:e})}function Je(e,t){switch(e){case"CouponLimitExceeded":return`Too many coupon codes \u2014 a checkout session accepts at most ${te}.`;case"CouponCurrencyUnsupported":return"One of the applied coupons has no price configured for the cart currency.";default:return`Failed to create checkout session (HTTP ${t}).`}}async function ge(e,t,r){let{billingApiUrl:o,checkoutBaseUrl:s,items:i=[],subscriptions:d=[],products:a,account:c,successUrl:n,cancelUrl:l,checkoutMode:m="confirm",captureMethod:h,couponCodes:w=[],checkoutMetadata:p,tagsData:g,redirectParams:I={},setCookie:f=!0,clientId:x,currency:k,utmMetadata:R,idempotencyKey:U}=e,F=me(U);if(w.length>te)throw new O(`Too many coupon codes \u2014 a checkout session accepts at most ${te}.`,"validation_error",{code:"CouponLimitExceeded",param:"couponCodes"});let S=a??je(i,d);Ne({captureMethod:h,products:S});let _=Ke(k,i,d,S);if(!_)throw new O("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 C={clientId:x,checkoutVersion:pe,successUrl:n,cancelUrl:l,currency:_,checkoutMode:m,products:S.map(v=>qe(v,_)),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:w};h==="manual"&&(C.captureMethod=h),p!==void 0&&(C.checkoutMetadata=p),g&&(C.tagsData=g),R&&R.length>0&&(C.utmMetadata=R);let q=`${o.replace(/\/+$/,"")}/v1/checkouts/sessions`,L={"Content-Type":"application/json"};F&&(L[$e]=F);let b,E,B={method:"POST",headers:L,body:JSON.stringify(C),signal:t},P;try{r?.startAttempt(),P=await fetch(q,B)}catch(v){throw We(v),v}try{r?.record(P.status)}catch{}b=P.status;try{E=await P.json()}catch{}if(b>=400)throw He(Ge(b,E),P);if(b===201){let v=E?.data?.uuid,D=E?.data?.nonce;if(!v)throw new Error("Checkout session created but no UUID was returned by the billing API");if(!D)throw new O("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"});(S.length>0||_)&&Q(v,{currency:_,products:S.map(u=>({code:u.code??u.providerItemId??u.providerPlanId,type:u.type,name:u.name??u.itemName??u.providerItemName??u.subscriptionName??u.providerPlanName??null,totalAmount:u.totalAmount,overrideAmount:u.overrideAmount,currency:u.currency??_}))});let y=new URL(`${s.replace(/\/+$/,"")}/secure`);y.searchParams.set("id",v);for(let[u,A]of Object.entries(I))y.searchParams.set(u,A);if(f&&typeof window<"u"&&typeof document<"u"){let u=JSON.stringify({origin_url:l}),A=window.location.hostname.split(".").slice(-2).join(".");document.cookie=`checkout_data=${encodeURIComponent(u)}; domain=.${A}; path=/; max-age=3600; SameSite=Lax; Secure;`,document.cookie=`flopay_checkout_token=${encodeURIComponent(D)}; domain=.${A}; path=/; max-age=3600; SameSite=Lax; Secure;`}return typeof window<"u"&&(window.location.href=y.toString()),{status:201,redirectUrl:y.toString(),nonce:D}}return b===204?(typeof window<"u"&&(window.location.href=n),{status:204}):{status:b}}async function Qe(e){let t=Ce(e),r=he(t),o=J(e.timeoutMs);try{let s=await ge(e,o.signal,r);return r.commit(),ve(t,s),s}catch(s){throw r.commit(),j(t,s),s}finally{o.clear(),M(t.reporter)}}function he(e){let t=!1,r=e.startedAt,o;return{startAttempt(){r=e.reporter.now()},record(s){o={status:s,durationMs:Math.max(0,e.reporter.now()-r),attempt:e.attempt}},commit(){if(t||!o)return;t=!0;let s=ye(o.status);e.reporter.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:s,attempt:o.attempt}),e.reporter.performance({stage:"session_first_byte",durationMs:o.durationMs,durationMode:"machine",requestCategory:"session_create",statusClass:s,attempt:o.attempt})}}}function Ce(e){let t=new T({billingApiUrl:e.billingApiUrl,sdkVersion:pe,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 ve(e,t){let r=ye(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 j(e,t){let{reporter:r}=e,o=ze(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 O&&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 M(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}async function Xe(e){let{maxRetries:t=2,...r}=e,o=Ce(e),s=he(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"}),M(o.reporter),new Error(`Number of retries must be an integer between 0 and ${2}`);let i={...r,idempotencyKey:me(r.idempotencyKey)},d=J(r.timeoutMs),a;for(let c=0;c<=t;c++){o.attempt=c;try{let n=await ge(i,d.signal,s);return s.commit(),ve(o,n),d.clear(),M(o.reporter),n}catch(n){a=n;let l=n instanceof Error&&n.name==="AbortError",m=Ye(n),h=n instanceof O&&n.code===Ve;if((l||m||h)&&!d.signal.aborted&&c<t){o.reporter.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:c+1});try{await ne(c,d.signal)}catch(w){throw s.commit(),j(o,w),d.clear(),M(o.reporter),w}continue}throw s.commit(),j(o,n),d.clear(),M(o.reporter),n}}throw s.commit(),j(o,a),d.clear(),M(o.reporter),a??new Error("Unknown error during checkout session creation")}import{classifyTelemetryFailure as Ze,FloPayError as V,resolveBillingApiUrl as Se,SDK_VERSION as et}from"@flopay/shared";var we=Symbol.for("@flopay/js.telemetry.bridge.v1");function _e(e,t,r){let o=()=>t?.now()??r();Object.defineProperty(e,we,{configurable:!1,enumerable:!1,writable:!1,value:{error:i=>t?.error(i),log:i=>t?.log(i),performance:i=>t?.performance(i),terminal:i=>t?.terminal(i),now:o,elapsed:i=>Math.max(0,o()-i),setCheckoutContext:i=>t?.setCheckoutContext(i),beginCheckout:(i={})=>t?.beginCheckout(i)??o(),disable:()=>t?.disable(),subscribe:i=>t?.subscribe(i)??(()=>{}),flush:()=>t?.flush()??Promise.resolve()}})}function be(e){return e[we]}var $=class{now(){return this.telemetryReporter?.now?.()??z()}constructor(t,r,o){this.provider=t,this.config=r,this.telemetryReporter=o??new T({billingApiUrl:Se(r.billingApiUrl),sdkVersion:et,enabled:r.telemetry!==!1}),_e(this,this.telemetryReporter,z)}cardCapture(t){return this.telemetryReporter?.log({name:"vault.capture.requested",stage:"vault_request",provider:"pcivault",paymentMethodCategory:"card"}),this.telemetryReporter?ue({sessionId:t?.sessionId,captureMethod:t?.captureMethod},this.telemetryReporter):new Z({sessionId:t?.sessionId,captureMethod:t?.captureMethod,telemetry:!1})}async retrieveSession(t,r){if(!t)throw new V("sessionId is required to retrieve a session.","validation_error",{param:"sessionId"});let o=await this.retrieveUnifiedSession(t,r);if(!o.data.session)throw new V("Session not found","api_error");return o.data.session}async retrieveUnifiedSession(t,r){if(!t)throw new V("sessionId is required.","validation_error",{param:"sessionId"});let o=Se(r??this.config.billingApiUrl),s=this.now();this.telemetryReporter?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let i,d,a=n=>{if(i===void 0)return;let l=i,m=d;i=void 0,d=void 0,this.telemetryReporter?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:n,attempt:m}),this.telemetryReporter?.performance({stage:"session_first_byte",durationMs:l,durationMode:"machine",requestCategory:"session_read",statusClass:n,attempt:m})},c=de(o,{now:()=>this.telemetryReporter?.now()??z(),onFirstByte:(n,l)=>{i=n,d=l},onRetry:(n,l)=>{this.telemetryReporter?.log({name:"operation.retry",stage:n==="session_read"?"session_read":"processing",requestCategory:n,attempt:l})}});try{let n=await c.getUnifiedCheckoutSession(t);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()-s,durationMode:"machine",requestCategory:"session_read",statusClass:"2xx"}),n}catch(n){let l=Ze(n,n instanceof V&&n.code==="checkout_processing_timeout"?"REQUEST_TIMEOUT":"NETWORK_REQUEST_FAILED");throw a(l.statusClass),this.telemetryReporter?.error({...l,stage:"session_read",provider:"flo",paymentMethodCategory:"unknown"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-s,durationMode:"machine",requestCategory:"session_read",statusClass:l.statusClass}),n}}getRawProvider(){return this.provider.getRawProvider()}destroy(){this.telemetryReporter?.log({name:"checkout.unmount",stage:"unmount"}),this.telemetryReporter?.destroy(),this.provider.destroy()}};function Pe(e,t,r){let o=$;return new o(e,t,r)}import{FloPayError as nt,resolveBillingApiUrl as re,SDK_VERSION as Ee}from"@flopay/shared";import{FloPayError as Ae}from"@flopay/shared";import{loadStripe as tt}from"@stripe/stripe-js";import{toStripeAppearance as rt,toStripeAppearanceTheme as ot}from"@flopay/shared";var ke=new WeakSet;function Re(e){return e instanceof Ae&&ke.has(e)}var N=class{constructor(){this.name="stripe";this.stripe=null}async initialize(t){if(typeof window>"u")return;let r=await tt(t.publishableKey,{locale:t.locale??"auto"});if(!r){let o=new Ae("Failed to initialize Stripe. Check your publishable key.","authentication_error");throw ke.add(o),o}this.stripe=r}getRawProvider(){return this.stripe}destroy(){this.stripe=null}};var Te=new Map;function oe(e){return Array.isArray(e)?e.map(oe):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,oe(r)])):e}function it(e,t){return JSON.stringify([e,re(t?.billingApiUrl),t?.telemetry!==!1,t?.locale??"auto",t?.apiVersion??null,oe(t?.appearance??null)])}var K=new Map;async function st(e,t){if(!e){let a=new T({billingApiUrl:re(t?.billingApiUrl),sdkVersion:Ee,enabled:t?.telemetry!==!1});throw a.error({errorCode:"CONFIGURATION_INVALID",stage:"sdk_initialize",paymentMethodCategory:"unknown"}),a.flush().catch(()=>{}).finally(()=>a.destroy()),new nt("A publishable key is required to initialize FloPay.","validation_error",{param:"publishableKey"})}let r=it(e,t),o=Te.get(r);if(o)return t?.telemetry!==!1&&be(o)?.log({name:"sdk.cache.hit",stage:"sdk_initialize"}),o;let s=K.get(r);if(s)return s;let i={...t,publishableKey:e},d=(async()=>{let a=new T({billingApiUrl:re(i.billingApiUrl),sdkVersion:Ee,enabled:i.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 n=new N,l=a.now();try{await n.initialize(i)}catch(w){throw a.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:Re(w)?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"unknown"}),a.destroy(),w}let m=a.now();a.log({name:"provider.ready",stage:"provider_ready",provider:"stripe"}),a.log({name:"provider.availability.checked",stage:"provider_ready",provider:"stripe"}),a.log({name:"sdk.initialize.ready",stage:"sdk_initialize"}),a.performance({stage:"sdk_initialize",durationMs:m-c,durationMode:"machine",provider:"stripe"}),a.performance({stage:"provider_ready",durationMs:m-l,durationMode:"machine",provider:"stripe"});let h=Pe(n,i,a);return Te.set(r,h),h})();K.set(r,d);try{return await d}finally{K.get(r)===d&&K.delete(r)}}import{FloPayError as W,THREE_DS_CHALLENGE_WINDOW_MS as xe}from"@flopay/shared";var at=4,lt=1e3,ct=1e3,dt=15e3;function ut(e){let t=!!e?.gateways?.stripe,r=!!e?.gateways?.worldpayCorporateGateway;return t===r?"unknown":t?"stripe":"worldpay"}function mt(e,t,r){try{return typeof e?.beginThreeDsChallenge!="function"?void 0:e.beginThreeDsChallenge(t,{provider:ut(r)})}catch{return}}function H(e){return new W("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function Fe(){return new W("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function De(e){return e.replace(/\/+$/,"")}function pt(e){return e.status==="succeeded"||e.status==="authorized"||e.status==="declined"}function yt(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 Me(e){if(typeof document>"u"||typeof window>"u")throw new W("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});let t=X(e.telemetry);t.record("handoff_planned");let r=ie(e.nextActionRedirectUrl);r==="missing"?t.record("action_missing",{reason:"missing_url"}):r==="invalid"&&t.record("action_invalid",{reason:"invalid_url"});let o=p=>{let g=se(p);if(g==="buyer_cancel"){t.record("cancel_requested",{reason:g,evidenceBasis:"signal_reason"}),t.terminal("cancel",{reason:g,evidenceBasis:"signal_reason"});return}t.record("abort_observed",{reason:g,evidenceBasis:"signal_reason"}),t.terminal("abort",{reason:g,evidenceBasis:"signal_reason"})},s=p=>{(p.status==="succeeded"||p.status==="authorized"||p.status==="declined"||p.status==="timeout")&&t.reconcile(p.status)};if(e.signal?.aborted)throw o(e.signal.reason),H();let i=`${De(e.billingApiUrl)}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,d=async()=>{let p=new AbortController,g=()=>p.abort();e.signal?.aborted?p.abort():e.signal?.addEventListener("abort",g);let I=window.setTimeout(()=>p.abort(),dt);try{let f=await fetch(i,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json",...t.attemptId?{"x-flopay-challenge-attempt":t.attemptId}:{}},body:"{}",signal:p.signal});if(!f.ok)return{status:"unknown"};let x=await f.json().catch(()=>null),k=yt(x);return s(k),k}catch{return{status:"unknown"}}finally{window.clearTimeout(I),e.signal?.removeEventListener("abort",g)}},a,c=()=>e.pollCompletionEndpoint!==!1?d():(a??(a=d()),a),n=document.activeElement instanceof HTMLElement?document.activeElement:null,l=document.createElement("div");l.setAttribute("data-flopay-auto-3ds-overlay","1"),l.setAttribute("role","dialog"),l.setAttribute("aria-modal","true"),l.setAttribute("aria-label","Card authentication"),l.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 m=document.createElement("iframe");m.setAttribute("title","Card authentication"),m.setAttribute("allow","payment"),m.tabIndex=0,m.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 h=null;try{h=new URL(e.billingApiUrl,window.location.href).origin}catch{h=null}let w=ce(e.nextActionRedirectUrl);try{let p=await new Promise((g,I)=>{let f=!1,x=0,k=0,R=0,U=!1,F=!1,S=!1,_=0,C=()=>{window.clearTimeout(x),window.clearInterval(k),window.clearTimeout(R),window.removeEventListener("message",v),window.removeEventListener("pagehide",L),document.removeEventListener("securitypolicyviolation",b),m.removeEventListener("load",E),e.signal?.removeEventListener("abort",B)},q=async()=>{if(!(f||U)){U=!0;try{let y=await c();if(f||!pt(y))return;f=!0,C(),t.terminal("status_poll",{evidenceBasis:"server_status"}),g(y)}finally{U=!1}}},L=()=>{t.record("pagehide_observed",{evidenceBasis:"page_lifecycle_event"})},b=y=>{if(S)return;let u=le(y,w);u&&(S=!0,t.record("policy_violation",{reason:u,evidenceBasis:"parent_csp_event"}))},E=()=>{F||(F=!0,t.record("iframe_load",{evidenceBasis:"iframe_load_event"})),e.pollCompletionEndpoint!==!1&&(window.clearTimeout(R),R=window.setTimeout(()=>{q()},250))},B=()=>{f||(f=!0,C(),o(e.signal?.reason),I(H()))},P=y=>{f||_>=at||(_+=1,t.record("return_rejected",{reason:y,evidenceBasis:"message_origin_check"}))},v=y=>{let u=y.data,A=!!u&&typeof u=="object"&&u.source==="flopay-vault-3ds-return";if(y.source!==m.contentWindow){A&&P("untrusted_source");return}if(h&&y.origin!==h){A&&P("untrusted_origin");return}A&&(f||(f=!0,C(),t.record("trusted_return",{evidenceBasis:"message_origin_check"}),t.terminal("trusted_return",{evidenceBasis:"message_origin_check"}),g(null)))};x=window.setTimeout(()=>{f||(f=!0,C(),F||t.record("load_unconfirmed",{evidenceBasis:"no_load_signal"}),t.record("timer_expired",{reason:"window_elapsed",evidenceBasis:"timer"}),t.terminal("timer",{reason:"window_elapsed",evidenceBasis:"timer"}),I(Fe()))},xe),e.pollCompletionEndpoint!==!1&&(k=window.setInterval(()=>{q()},ct)),m.addEventListener("load",E),window.addEventListener("message",v),window.addEventListener("pagehide",L),document.addEventListener("securitypolicyviolation",b),e.signal?.addEventListener("abort",B),m.src=e.nextActionRedirectUrl,t.record("render_attempted");try{l.appendChild(m),document.body.appendChild(l)}catch(y){throw f=!0,C(),t.record("render_failed"),y}t.record("container_attached"),t.record("navigation_assigned");let D=ae(l);D&&t.record("container_visibility",{reason:D,evidenceBasis:"parent_computed_style"}),m.focus(),e.signal?.aborted&&B()});return p||await c()}finally{l.parentNode?.removeChild(l),t.record("teardown"),n?.isConnected&&n.focus()}}function Ie(e,t){try{let r=t.data.session?.status;r==="complete"?e.reconcile("succeeded"):r==="authorized"&&e.reconcile("authorized")}catch{}}function ft(e){return new W("Card was declined.","api_error",{code:e.declineReason??"authorization_declined",...e.gatewayDeclineReason?{declineCode:e.gatewayDeclineReason}:{}})}async function gt(e,t){let r=`${De(e.billingApiUrl)}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/status`,o=new AbortController,s=new AbortController,i=()=>{o.abort(e.signal?.reason),s.abort(e.signal?.reason)};e.signal?.aborted?i():e.signal?.addEventListener("abort",i,{once:!0});let d=X(e.telemetry),a=Me({billingApiUrl:e.billingApiUrl,sessionId:e.sessionId,nonce:e.nonce,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:o.signal,pollCompletionEndpoint:!1,...e.telemetry?{telemetry:e.telemetry}:{}}),c=t.waitForCheckoutSessionCompletion(e.sessionId,{initialDelayMs:lt,nonce:e.nonce,statusUrl:r,continueAfterActionRequired:!0,timeoutMs:xe+15e3,signal:s.signal,...d.attemptId?{challengeAttemptId:d.attemptId}:{}});c.catch(()=>{}),a.catch(()=>{});try{let n=await Promise.race([a,c]);if("data"in n)return d.terminal("status_poll",{evidenceBasis:"server_status"}),Ie(d,n),n;if(n.status==="declined")throw(e.createDeclineError??ft)(n);if(n.status==="timeout")throw Fe();let l=await c;return Ie(d,l),l}catch(n){throw e.signal?.aborted||n instanceof Error&&n.name==="AbortError"?H(n):n}finally{e.signal?.removeEventListener("abort",i),o.abort(),s.abort()}}export{$ as FloPay,Be as PaymentAPI,Z as PciVaultCardCapture,Le as SESSION_CREATE_TELEMETRY,N as StripeAdapter,mt as beginSavedCardChallengeTelemetry,Q as cacheSessionDisplayData,Ue as clearSessionDisplayData,gt as completeSavedCardNextAction,Qe as createCheckoutSession,Xe as createCheckoutSessionWithRetries,H as createSavedCardActionAbortedError,Kt as dropThirdPartyOnlyError,Oe as getSessionDisplayData,st as loadFloPay,Me as runSavedCardChallenge,rt as toStripeAppearance,ot as toStripeAppearanceTheme};
@@ -1,5 +1,6 @@
1
1
  import type { AdvertisedPaymentMethod, CheckoutGateways, CheckoutSessionMode, CreateSessionIntentRequest, DetachedCheckoutSession, InlineSessionDraft, NormalizedCheckoutSession, ProcessPaymentParams, SessionIntentDeclineRequest, SessionIntentResult, TelemetryPaymentMethodCategory, TelemetryRequestCategory, VaultCaptureBlock } from '@flopay/shared';
2
2
  import type { SessionDisplayCacheData } from './session-display-cache.js';
3
+ import type { BeginThreeDsChallengeInput, ThreeDsChallengeAttempt } from './three-ds-challenge.js';
3
4
  /** Raw billing API response wrapper. */
4
5
  interface BillingResponse<T> {
5
6
  data: T;
@@ -409,6 +410,13 @@ export declare class PaymentAPI {
409
410
  * what the hosted vault records for an abandoned challenge (TeamFloPay/sdk#394).
410
411
  */
411
412
  reportThreeDsAbandoned(checkoutSessionId: string): void;
413
+ /**
414
+ * @internal Begin (or continue) one 3DS challenge attempt on this client's own telemetry
415
+ * reporter, so a saved-card caller can hand it to the shared challenge runner (#525). The
416
+ * attempt carries no checkout id. `undefined` when this client has no reporter (telemetry off,
417
+ * internal hooks) or the recorder cannot start: telemetry never changes the payment flow.
418
+ */
419
+ beginThreeDsChallenge(checkoutSessionId: string, input?: BeginThreeDsChallengeInput): ThreeDsChallengeAttempt | undefined;
412
420
  waitForCheckoutSessionCompletion(checkoutSessionId: string, options?: {
413
421
  initialDelayMs?: number;
414
422
  timeoutMs?: number;
@@ -428,6 +436,11 @@ export declare class PaymentAPI {
428
436
  paymentMethodCategory?: TelemetryPaymentMethodCategory;
429
437
  /** Cancels polling when the owning UI lifecycle ends. */
430
438
  signal?: AbortSignal;
439
+ /**
440
+ * Opaque 3DS challenge attempt this poll reconciles. The recovery reporter continues that
441
+ * attempt's timeline with `recovery_read_completed`; it is never sent on the request.
442
+ */
443
+ challengeAttemptId?: string;
431
444
  }): Promise<NormalizedCheckoutSession>;
432
445
  private reportRecoveryCompleted;
433
446
  private resolveCheckoutSessionStatus;
@@ -56,6 +56,16 @@ export declare class PciVaultCardCapture implements CardCaptureAdapter {
56
56
  * (TeamFloPay/backend#1674).
57
57
  */
58
58
  private threeDsReturnHandler;
59
+ /** Lifecycle telemetry of the open challenge overlay; it never decides the challenge. */
60
+ private actionChallenge;
61
+ /**
62
+ * Recorder of the latest challenge attempt, kept after its overlay is gone. A trusted return
63
+ * (or a buyer close) dismisses the overlay before the widget's `/status` poll reports, and that
64
+ * later `complete`/`decline` is still this attempt's authoritative provider outcome. Cleared
65
+ * once an outcome is delivered, by the next `submitting` (a new submission owns what follows),
66
+ * by the next challenge, and on unmount.
67
+ */
68
+ private lastChallengeTelemetry;
59
69
  /**
60
70
  * Element that held focus when the challenge overlay opened, restored on
61
71
  * teardown. A keyboard or screen-reader buyer would otherwise be stranded on
@@ -217,6 +227,14 @@ export declare class PciVaultCardCapture implements CardCaptureAdapter {
217
227
  * widget's authentication window.
218
228
  */
219
229
  private abandonActionRequiredOverlay;
230
+ /** Begin the overlay's challenge attempt on the reporter, if it supports challenge records. */
231
+ private beginActionChallengeAttempt;
232
+ /**
233
+ * The widget reported an outcome. While the challenge is open its `/status` poll ends the
234
+ * browser window. `complete`/`decline` are also the authoritative outcome, recorded apart, and
235
+ * still recorded when a trusted return or a buyer close already dismissed the overlay.
236
+ */
237
+ private endActionChallengeFromWidget;
220
238
  private hideActionRequiredOverlay;
221
239
  /**
222
240
  * Size the hosted-widget iframe to the height reported by the form inside it.
@@ -1,6 +1,7 @@
1
- import type { NormalizedCheckoutSession } from '@flopay/shared';
1
+ import type { CheckoutSession, NormalizedCheckoutSession } from '@flopay/shared';
2
2
  import { FloPayError } from '@flopay/shared';
3
3
  import type { PaymentAPI } from './payment-api.js';
4
+ import type { ThreeDsChallengeAttempt } from './three-ds-challenge.js';
4
5
  /**
5
6
  * Outcome the backend's `/3ds/complete` sync resolver returns to the SDK.
6
7
  * Mirrors `ThreeDsResolveOutcome` on the backend without importing it. The
@@ -63,6 +64,8 @@ export interface SavedCardChallengeInput {
63
64
  * (and rejects the promise) immediately.
64
65
  */
65
66
  signal?: AbortSignal;
67
+ /** Lifecycle recorder for this challenge attempt; telemetry never changes the flow. */
68
+ telemetry?: ThreeDsChallengeAttempt;
66
69
  }
67
70
  /** Input for {@link completeSavedCardNextAction}. */
68
71
  export interface SavedCardNextActionInput {
@@ -74,6 +77,8 @@ export interface SavedCardNextActionInput {
74
77
  nextActionRedirectUrl: string;
75
78
  /** Cancels the challenge (component unmount, route change). */
76
79
  signal?: AbortSignal;
80
+ /** Lifecycle recorder for this challenge attempt; telemetry never changes the flow. */
81
+ telemetry?: ThreeDsChallengeAttempt;
77
82
  /**
78
83
  * Builds the error thrown for a `/3ds/complete` decline, so each framework
79
84
  * keeps its own decline mapping. Defaults to a `FloPayError` whose `code` is
@@ -81,6 +86,14 @@ export interface SavedCardNextActionInput {
81
86
  */
82
87
  createDeclineError?: (decline: SavedCardChallengeDecline) => Error;
83
88
  }
89
+ /**
90
+ * Begin the lifecycle recorder for one saved-card challenge on a caller's own `PaymentAPI`
91
+ * (#525): the React and Vue automatic and saved-payment flows hand the result to
92
+ * {@link completeSavedCardNextAction} as `telemetry`. The client's reporter decides delivery, so a
93
+ * merchant opt-out (`telemetry: false`) records nothing. Returns `undefined` whenever recording
94
+ * cannot start; it never throws into the payment flow.
95
+ */
96
+ export declare function beginSavedCardChallengeTelemetry(api: Partial<Pick<PaymentAPI, 'beginThreeDsChallenge'>> | null | undefined, checkoutSessionId: string, session?: Pick<CheckoutSession, 'gateways'> | null): ThreeDsChallengeAttempt | undefined;
84
97
  /** The buyer cancelled (or the owning UI unmounted) during a saved-card challenge. */
85
98
  export declare function createSavedCardActionAbortedError(cause?: unknown): FloPayError;
86
99
  /**
@@ -1,4 +1,5 @@
1
1
  import type { BuildTelemetryErrorEventInput, BuildTelemetryLogEventInput, BuildTelemetryPerformanceEventInput, BuildTelemetryTerminalEventInput, TelemetryCheckoutMode, TelemetryLayout, TelemetrySdkPackage } from '@flopay/shared';
2
+ import type { BeginThreeDsChallengeInput, ThreeDsChallengeAttempt } from './three-ds-challenge.js';
2
3
  export interface TelemetryReporterOptions {
3
4
  billingApiUrl: string;
4
5
  /** Package that owns every event in this package-homogeneous reporter. */
@@ -38,6 +39,7 @@ export declare class TelemetryReporter {
38
39
  private ingestionDisabled;
39
40
  private readonly queue;
40
41
  private sequence;
42
+ private threeDsChallengeCount;
41
43
  private flushTimer;
42
44
  private flushInFlight;
43
45
  private readonly reportedFailures;
@@ -53,6 +55,13 @@ export declare class TelemetryReporter {
53
55
  error(input: TelemetryReporterErrorInput): void;
54
56
  performance(input: TelemetryReporterPerformanceInput): void;
55
57
  terminal(input: TelemetryReporterTerminalInput): void;
58
+ /**
59
+ * @internal Begin (or continue, from a UUID another reporter began) one 3DS challenge attempt.
60
+ * Its records are `three_ds.challenge` lifecycle events with their own per-checkout budget;
61
+ * page-exit, cancel, abort and terminal records are delivered at once.
62
+ */
63
+ beginThreeDsChallenge(input?: BeginThreeDsChallengeInput): ThreeDsChallengeAttempt;
64
+ private recordThreeDsChallenge;
56
65
  /** @internal Read the reporter's monotonic clock without Resource Timing. */
57
66
  now(): number;
58
67
  /** @internal Observe the closed taxonomy without exposing queued event payloads. */
@@ -0,0 +1,76 @@
1
+ import type { ThreeDsChallengePhase, ThreeDsChallengeReason, ThreeDsEvidenceBasis, ThreeDsProvider, ThreeDsProviderOutcome, ThreeDsTerminalSource } from '@flopay/shared';
2
+ /**
3
+ * Bounded observation a producer may attach to a lifecycle record. Only closed values: the
4
+ * reporter drops anything else, and never accepts a URL, identifier or free text.
5
+ */
6
+ interface ThreeDsChallengeDetail {
7
+ reason?: ThreeDsChallengeReason;
8
+ evidenceBasis?: ThreeDsEvidenceBasis;
9
+ }
10
+ /**
11
+ * One challenge attempt's lifecycle recorder. It is created when the authentication handoff is
12
+ * planned and handed to every caller that touches the attempt (create, recovery, handoff,
13
+ * reconciliation), so all their records share one bounded attempt id.
14
+ *
15
+ * Recording is best-effort and must never throw into, delay or change the payment flow.
16
+ */
17
+ export interface ThreeDsChallengeAttempt {
18
+ /** Bounded opaque UUID v4; never a checkout, session or provider identifier. */
19
+ readonly attemptId: string;
20
+ /** Record one ordered lifecycle phase (sequence and elapsed time are assigned by the attempt). */
21
+ record(phase: ThreeDsChallengePhase, detail?: ThreeDsChallengeDetail): void;
22
+ /** Record the browser's one terminal; every later call is ignored (idempotent). */
23
+ terminal(source: ThreeDsTerminalSource, detail?: ThreeDsChallengeDetail): void;
24
+ /** Record an authoritative provider outcome, separately from the browser terminal. */
25
+ reconcile(outcome: ThreeDsProviderOutcome): void;
26
+ }
27
+ export interface BeginThreeDsChallengeInput {
28
+ provider?: ThreeDsProvider;
29
+ /** Continue an attempt another reporter (for example the recovery path's) already began. */
30
+ attemptId?: string;
31
+ }
32
+ /** The closed fields one challenge record carries to the reporter. */
33
+ export interface ThreeDsChallengeRecordFields {
34
+ attemptId: string;
35
+ phase: ThreeDsChallengePhase;
36
+ attemptSequence: number;
37
+ elapsedMs: number;
38
+ provider: ThreeDsProvider;
39
+ reason?: ThreeDsChallengeReason;
40
+ evidenceBasis?: ThreeDsEvidenceBasis;
41
+ terminalSource?: ThreeDsTerminalSource;
42
+ providerOutcome?: ThreeDsProviderOutcome;
43
+ }
44
+ /** Where an attempt delivers its records (the owning reporter). */
45
+ export interface ThreeDsChallengeSink {
46
+ now(): number;
47
+ newAttemptId(): string;
48
+ /** `urgent` records (page exit, cancel, abort, terminal) start delivery at once. */
49
+ emit(record: ThreeDsChallengeRecordFields, urgent: boolean): void;
50
+ }
51
+ /** Create the reporter-backed recorder for one (new or continued) challenge attempt. */
52
+ export declare function createThreeDsChallengeAttempt(sink: ThreeDsChallengeSink, input?: BeginThreeDsChallengeInput): ThreeDsChallengeAttempt;
53
+ /**
54
+ * Wrap any attempt (possibly absent, possibly throwing) so challenge code can record without a
55
+ * guard at every call site. Telemetry failures never alter the flow.
56
+ */
57
+ export declare function safeThreeDsChallenge(attempt: ThreeDsChallengeAttempt | undefined): {
58
+ attemptId: string | null;
59
+ record: ThreeDsChallengeAttempt['record'];
60
+ terminal: ThreeDsChallengeAttempt['terminal'];
61
+ reconcile: ThreeDsChallengeAttempt['reconcile'];
62
+ };
63
+ /** Classify a provider-hosted action URL without ever retaining it. */
64
+ export declare function classifyThreeDsActionUrl(url: unknown): 'valid' | 'missing' | 'invalid';
65
+ /** Map an abort reason to the closed exit reasons; anything else stays `unspecified`. */
66
+ export declare function threeDsAbortReason(reason: unknown): 'buyer_cancel' | 'component_unmount' | 'navigation' | 'unspecified';
67
+ /** Parent-observable presentation of an SDK-owned container: never a claim about issuer UI. */
68
+ export declare function observeThreeDsContainerVisibility(element: Element): 'hidden' | 'visible' | null;
69
+ /**
70
+ * Read a parent-page CSP violation without retaining its URI. It is attributable only when it
71
+ * blocked a frame from the challenge's own origin.
72
+ */
73
+ export declare function attributableThreeDsPolicyViolation(event: Event, challengeOrigin: string | null): 'frame_src' | 'child_src' | null;
74
+ /** The origin of a valid challenge URL, used only to attribute a CSP violation. */
75
+ export declare function threeDsChallengeOrigin(url: string): string | null;
76
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flopay/js",
3
- "version": "1.14.11",
3
+ "version": "1.14.12",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "publishConfig": {
@@ -31,8 +31,8 @@
31
31
  "dist"
32
32
  ],
33
33
  "dependencies": {
34
- "@flopay/shared": "1.14.11",
35
- "@stripe/stripe-js": "^10.2.1"
34
+ "@flopay/shared": "1.14.12",
35
+ "@stripe/stripe-js": "^10.3.0"
36
36
  },
37
37
  "devDependencies": {
38
38
  "jsdom": "^29.1.1",
@@ -1 +0,0 @@
1
- var je="flopay_session_display:";var N=new Map;function V(n){return`${je}${n}`}function $(){if(typeof window>"u")return null;try{return window.sessionStorage}catch{return null}}function Y(n,e,t){if(!n)return;let r=t?.ttlMs??36e5,s={data:e,expiresAt:Date.now()+r},o=$();if(o)try{o.setItem(V(n),JSON.stringify(s));return}catch{}N.set(n,s)}function ie(n){if(!n)return null;let e=$();if(e)try{let r=e.getItem(V(n));if(r){let s=JSON.parse(r);if(s&&typeof s.expiresAt=="number"&&s.expiresAt>Date.now())return s.data;e.removeItem(V(n))}}catch{}let t=N.get(n);if(t){if(t.expiresAt>Date.now())return t.data;N.delete(n)}return null}function ae(n){if(!n)return;N.delete(n);let e=$();if(e)try{e.removeItem(V(n))}catch{}}import{ASYNC_AUTO_CHECKOUT_CAPABILITY as ot,assertCaptureMethodEligible as he,buildProductPayload as re,CHECKOUT_PROCESSING_TIMEOUT_MESSAGE as it,CHECKOUT_SESSION_BUYER_EMAIL_REQUIRED as at,classifyPaymentRejection as ut,classifyTelemetryFailure as F,FLO_SDK_CAPABILITIES_HEADER as ct,FLO_SDK_VERSION_HEADER as H,FloPayError as y,foldIntoProducts as Q,IDEMPOTENCY_IN_PROGRESS_CODE as lt,IDEMPOTENCY_KEY_HEADER as ye,isCardHolderNamePlaceholder as Me,isDetachedSessionEligible as dt,isUuidV4 as ge,isValidEmail as fe,markSessionResponseReceived as U,normalizeCheckoutFailureOutcome as Ce,PAYPAL_VAULTED_PAYMENT_METHOD_TYPE as J,randomUuidV4 as mt,readTelemetryHttpDiagnostics as pt,resolveIdempotencyKey as ht,resolveSessionCurrency as X,SDK_VERSION as E,STORED_PAYMENT_METHOD_UNSUPPORTED_CODE as ve,STORED_PAYMENT_METHOD_UNSUPPORTED_MESSAGE as Te,telemetryStatusClass as A,withTelemetryHttpDiagnostics as we}from"@flopay/shared";function ue(n){return typeof n=="string"&&n.trim()?n:void 0}function ce(n){if(typeof n=="string")return n.trim()?n:void 0;if(Array.isArray(n))return n.filter(t=>typeof t=="string"&&t.trim().length>0).join("; ")||void 0}function I(n=12e3){let e=Number.isFinite(n)&&n>=0?n:12e3,t=new AbortController,r=setTimeout(()=>t.abort(),e);return{signal:t.signal,clear:()=>clearTimeout(r)}}function Ke(){return Object.assign(new Error("The operation was aborted."),{name:"AbortError"})}function z(n,e){let t=150*2**n,r=Math.round(t*(.75+Math.random()*.5));return new Promise((s,o)=>{let i,a=()=>e.removeEventListener("abort",u),u=()=>{i!==void 0&&clearTimeout(i),a(),o(Ke())};if(e.aborted){u();return}i=setTimeout(()=>{a(),s()},r),e.addEventListener("abort",u,{once:!0})})}import{buildTelemetryErrorEvent as le,buildTelemetryLogEvent as Ge,buildTelemetryPerformanceEvent as $e,buildTelemetryTerminalEvent as Ye,serializeTelemetryBatch as We,TELEMETRY_MAX_BATCH_BYTES as Qe}from"@flopay/shared";var Je="/v1/sdk-telemetry/events",W=16,Xe=64,Ze=1500,de=1e3,et=64,tt="00000000-0000-4000-8000-000000000000",rt={technical_error:8,lifecycle:32,expected_outcome:32,performance:24};function P(){try{return globalThis.crypto.randomUUID()}catch{let n=new Uint8Array(16);try{globalThis.crypto.getRandomValues(n)}catch{for(let t=0;t<n.length;t+=1)n[t]=Math.floor(Math.random()*256)}n[6]=(n[6]??0)&15|64,n[8]=(n[8]??0)&63|128;let e=[...n].map(t=>t.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}}function nt(n){try{return new TextEncoder().encode(n).byteLength}catch{return n.length}}function st(n){return JSON.stringify([n.code,n.failureCategory,n.reason,n.stage,n.provider,n.attempt,n.statusClass,n.requestCategory,n.paymentMethodCategory,n.walletType,n.operationOutcome,n.checkoutMode,n.layout,n.inAppBrowser,n.appFamily,n.popupCapability,n.presentationMode,n.terminalReason])}function S(){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(/\/+$/,"")}${Je}`,this.sdkPackage=e.sdkPackage??"@flopay/js",this.sdkVersion=e.sdkVersion,this.correlationId=P(),this.merchantEnabled=e.enabled!==!1,this.clock=e.clock??S,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(Ge({...this.checkoutContext,...e,eventId:P(),sequence:this.sequence++}))}error(e){if(this.notify({...e,class:"technical_error"}),!this.canCollect())return;let t=le({...this.checkoutContext,...e,eventId:tt,sequence:0}),r=st(t),s=this.now();this.pruneReportedFailures(s);let o=this.reportedFailures.get(r);if(o!==void 0&&s>=o&&s-o<de){this.log({name:"operation.deduplicated",stage:e.stage,provider:e.provider,paymentMethodCategory:e.paymentMethodCategory,attempt:e.attempt,inAppBrowser:e.inAppBrowser,appFamily:e.appFamily,popupCapability:e.popupCapability,presentationMode:e.presentationMode,terminalReason:e.terminalReason});return}this.rememberReportedFailure(r,s),this.enqueue(le({...this.checkoutContext,...e,eventId:P(),sequence:this.sequence++}))}performance(e){this.canCollect()&&this.enqueue($e({...this.checkoutContext,...e,eventId:P(),sequence:this.sequence++}))}terminal(e){if(this.canCollect()&&(this.enqueue(Ye({...this.checkoutContext,...e,eventId:P(),sequence:this.sequence++})),e.outcome!=="action_required"&&this.checkoutStartedAt!==null)){let t=this.checkoutStartedAt;this.checkoutStartedAt=null,this.performance({...e,stage:"total_journey",durationMs:Math.max(0,this.now()-t),durationMode:"total"})}}now(){try{return this.clock()}catch{return S()}}subscribe(e){return this.destroyed?()=>{}:(this.observers.add(e),()=>this.observers.delete(e))}notify(e){if(!this.destroyed)for(let t of this.observers)try{t(e)}catch{}}pruneReportedFailures(e){for(let[t,r]of this.reportedFailures)(e<r||e-r>=de)&&this.reportedFailures.delete(t)}rememberReportedFailure(e,t){for(;this.reportedFailures.size>=et;){let r=this.reportedFailures.keys().next();if(r.done)break;this.reportedFailures.delete(r.value)}this.reportedFailures.set(e,t)}setCheckoutContext(e){this.checkoutContext={checkoutMode:e.checkoutMode,layout:e.layout}}beginCheckout(e={}){return this.canCollect()?(this.drainQueue(),this.setCheckoutContext(e),this.sequence=0,this.reportedFailures.clear(),this.eventCounts={technical_error:0,lifecycle:0,expected_outcome:0,performance:0},this.checkoutStartedAt=this.now(),this.checkoutStartedAt):0}enqueue(e){if(this.canCollect()&&!(this.queue.length>=Xe||this.eventCounts[e.class]>=rt[e.class])){if(this.eventCounts[e.class]+=1,this.queue.push(e),this.queue.length>=W){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,W);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,W);this.sendBatch(e)}}async sendBatch(e){if(!this.browserTransportAvailable||this.ingestionDisabled)return;let t=We(e,{correlationId:this.correlationId,sdkPackage:this.sdkPackage,sdkVersion:this.sdkVersion,batchId:P()});if(nt(t)>Qe)return;let r=typeof AbortController>"u"?null:new AbortController,s=null;try{let o=fetch(this.endpoint,{method:"POST",headers:{"content-type":"text/plain;charset=UTF-8"},body:t,credentials:"omit",keepalive:!0,referrerPolicy:"no-referrer",signal:r?.signal}).then(async u=>{if(u.status!==202)return null;let c=null;try{c=await u.json()}catch{}return c?.status==="disabled"?"disabled":null}).catch(()=>null),i=new Promise(u=>{s=setTimeout(()=>{r?.abort(),u(null)},Ze)});await Promise.race([o,i])==="disabled"&&this.disableFromIngestion()}catch{}finally{s&&clearTimeout(s)}}disableFromIngestion(){this.ingestionDisabled=!0,this.queue.splice(0),this.reportedFailures.clear(),this.clearFlushTimer()}scheduleFlush(){this.flushTimer||this.destroyed||this.ingestionDisabled||(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush()},0))}clearFlushTimer(){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null)}},me=Symbol.for("@flopay/js.telemetry.reporter-factory.v1"),pe=globalThis;pe[me]===void 0&&Object.defineProperty(pe,me,{configurable:!0,enumerable:!1,writable:!1,value:n=>new R(n)});function yt(n){return n==="on_session"||n==="off_session"}function gt(n){if(!n||typeof n!="object")return!1;let e=n;return typeof e.paymentMethodType=="string"&&typeof e.reason=="string"}function ft(n){let e=n.vaultOutcome;if(!(!e||e.code!==at))return typeof e.message=="string"&&e.message.trim()!==""?e.message:void 0}var Ct="x-flopay-process-result-source",vt="status";function be(n){return n?.result==="DECLINE"||n?.result==="ERROR"}var Tt=50,M=new Map;function bt(n,e){return M.get(n)?.has(e)===!0}function St(n,e){let t=M.get(n)??new Set;if(t.add(e),M.delete(n),M.set(n,t),M.size>Tt){let r=M.keys().next().value;r!==void 0&&M.delete(r)}}function Rt(n){let e=n?.threeDSecureActionResultTokenId;if(typeof e=="string"&&e.length>0)return e;if(n?.gateway==="paypal"&&n.type!=="paypal_setup_token"&&typeof n.id=="string"&&n.id.length>0)return n.id}var Se=0,Re=500,B=15e3,_e=15e3,_t=3e3,kt=1e4,At=1e4;function q(n){return typeof n=="object"&&n!==null}function k(n,e){return ue(n?.[e])}function ke(n,e){return ce(n?.[e])}function Et(n,e){let t=n?.[e];return typeof t=="number"&&Number.isFinite(t)?t:void 0}function ee(n,e){return e?new Promise((t,r)=>{let s=()=>{clearTimeout(o),r(e.reason??Object.assign(new Error("The operation was aborted."),{name:"AbortError"}))},o=setTimeout(()=>{e.removeEventListener("abort",s),t()},n);e.aborted?s():e.addEventListener("abort",s,{once:!0})}):new Promise(t=>setTimeout(t,n))}function Z(n){return n instanceof Error&&n.name==="AbortError"}function b(){return new y(it,"api_error",{code:"checkout_processing_timeout"})}async function _(n,e){let t=await n.json().catch(()=>null),r=q(t?.error)?t.error:null,s=ke(t,"message")??ke(r,"message")??e,o=k(t,"code")??k(t,"gatewayErrorCode")??k(r,"code")??`http_${n.status}`;return we(new y(s,"api_error",{code:o,statusCode:n.status}),n)}async function Mt(n){if(n.status!==403)return!1;let e=await n.clone().json().catch(()=>null),t=q(e?.error)?e.error:null;return(k(e,"code")??k(t,"code"))==="verification_required"}function wt(n){if(!(!q(n)||typeof n.required!="boolean"))return{required:n.required,provider:"turnstile"}}async function It(n){let e=n.status===400?await n.clone().json().catch(()=>null):null;return ut(n.status,e)}function Ae(n){return n===400||n===422}var K=2;async function j(n,e,t=K,r,s){let o;for(let i=0;;i++)try{return s?.(i),await fetch(n,e)}catch(a){if(e?.signal?.aborted||a instanceof Error&&a.name==="AbortError")throw a;if(o=a,i>=t)throw o;try{r?.(i+1)}catch{}await ee(150*2**i,e?.signal??void 0)}}var Pt=Symbol.for("@flopay/js.session-create.telemetry.v1");function Dt(n){return n[Pt]}function Ot(n){return"now"in n||"onFirstByte"in n||"onSessionCreateFailure"in n||"onRetry"in n}function Ie(n){let e=Me(n.firstName,n.lastName);return{userId:n.userId,firstName:e?null:n.firstName??null,lastName:e?null:n.lastName??null,email:n.email,country:n.country??null,gender:n.gender??null,city:n.city??null,state:n.state??null,zip:n.zip??null,addressLine1:n.addressLine1??null,addressLine2:n.addressLine2??null}}function Pe(n,e){e.checkoutMetadata!==void 0&&(n.checkoutMetadata=e.checkoutMetadata),e.tagsData&&(n.tagsData=e.tagsData),e.utmMetadata&&e.utmMetadata.length>0&&(n.utmMetadata=e.utmMetadata),e.avsCheck!==void 0&&(n.avsCheck=e.avsCheck),e.checkoutType&&(n.checkoutType=e.checkoutType),e.checkoutLayout&&(n.checkoutLayout=e.checkoutLayout),e.avsConfig&&(n.avsConfig=e.avsConfig)}function xt(n,e){let t={clientId:n.clientId,checkoutVersion:E,successUrl:n.successUrl,cancelUrl:n.cancelUrl,currency:e,checkoutMode:"full",deferDataAttachment:!0};return n.captureMethod==="manual"&&(t.captureMethod=n.captureMethod),n.account.country&&(t.accountData={country:n.account.country}),Pe(t,n),t}function Ee(n,e,t){return{currency:e,products:t.map(r=>re(r,e)),couponCodes:n.couponCodes??[],accountData:Ie(n.account)}}function Ft(n,e,t){return{currency:e,products:t.map(r=>re(r,e)),couponCodes:n.couponCodes??[]}}function Ut(n){let e={},t=Me(n.firstName,n.lastName);for(let[r,s]of Object.entries(n)){if(t&&r.endsWith("Name")||typeof s!="string")continue;let o=s.trim();o&&(e[r]=o)}return{accountData:e}}var w=class w{constructor(e,t={}){this.baseUrl=e.replace(/\/+$/,"");let r=Ot(t);this.telemetryHooks=r?t:void 0,this.directTelemetry=r||t.telemetry===!1?void 0:new R({billingApiUrl:this.baseUrl,sdkVersion:E})}destroy(){this.directTelemetry?.destroy()}reportDirectFailure(e,t,r,s,o="unknown"){let i=F(e,t);this.directTelemetry?.error({...i,stage:r,requestCategory:s,paymentMethodCategory:o})}reportAccountSnapshotFailure(e,t){let r=F(e,"NETWORK_REQUEST_FAILED");if(t==="best_effort"&&r.errorCode==="REQUEST_TIMEOUT"){this.directTelemetry?.log({name:"operation.fallback",stage:"processing",requestCategory:"account_snapshot",statusClass:"timeout"});return}this.directTelemetry?.error({...r,stage:"processing",requestCategory:"account_snapshot",paymentMethodCategory:"unknown"})}telemetryTimestamp(){try{return this.telemetryHooks?.now?.()??this.directTelemetry?.now()??S()}catch{return S()}}beginDirectTelemetryCheckout(e){!this.directTelemetry||this.directTelemetryCheckoutId===e||(this.directTelemetryCheckoutId=e,this.directTelemetry.beginCheckout())}beginDirectTelemetryOperation(){this.directTelemetry&&(this.directTelemetryCheckoutId=void 0,this.directTelemetry.beginCheckout())}adoptDirectTelemetryCheckout(e){e&&(this.directTelemetryCheckoutId=e)}async getCheckoutSession(e,t){return this.fetchCheckoutSession(e,t)}async fetchCheckoutSession(e,t,r=!0,s){this.beginDirectTelemetryCheckout(e);let o=this.telemetryTimestamp(),i=o,a=0;this.directTelemetry?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let u={[H]:E};t&&(u["x-checkout-session-token"]=t);let c=!1;try{let d=await j(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}`,{headers:u,signal:s},K,m=>{this.telemetryHooks?.onRetry?.("session_read",m),this.directTelemetry?.log({name:"operation.retry",stage:"session_read",requestCategory:"session_read",attempt:m})},m=>{a=m,i=this.telemetryTimestamp()});c=!0;let h=Math.max(0,this.telemetryTimestamp()-i);try{this.telemetryHooks?.onFirstByte?.(h,a)}catch{}let l=`${Math.floor(d.status/100)}xx`;if(this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:l,attempt:a}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:h,durationMode:"machine",requestCategory:"session_read",statusClass:l,attempt:a}),!d.ok)throw await _(d,"Failed to get checkout session");let g=await d.json();return this.directTelemetry?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:l}),this.directTelemetry?.performance({stage:"session_complete",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"session_read",statusClass:l}),{...g,data:this.mergeCachedDisplayData(g.data)}}catch(d){throw c&&U(d),r&&this.directTelemetry?.error({...F(d,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"}),d}}cacheSessionDisplayData(e,t,r){Y(e,t,r)}clearSessionDisplayData(e){ae(e)}async getVaultCapture(e,t){let r=`${this.baseUrl}\0${e}\0${t??""}`,s=w.activeVaultCaptureRequests.get(r);if(s!==void 0)return s;let o=this.requestVaultCapture(e,t);w.activeVaultCaptureRequests.set(r,o);try{return await o}finally{w.activeVaultCaptureRequests.get(r)===o&&w.activeVaultCaptureRequests.delete(r)}}async requestVaultCapture(e,t){let r=new AbortController,s=setTimeout(()=>r.abort(),At);this.beginDirectTelemetryCheckout(e);let o=this.telemetryTimestamp();this.directTelemetry?.log({name:"vault.capture.requested",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card"});let i={"Content-Type":"application/json"};t&&(i["x-checkout-session-token"]=t);try{let a=await j(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/vault/capture`,{method:"POST",headers:i,signal:r.signal},K,c=>{this.telemetryHooks?.onRetry?.("vault_capture",c),this.directTelemetry?.log({name:"operation.retry",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card",attempt:c})});if(await Mt(a))return this.directTelemetry?.performance({stage:"vault_request",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"4xx"}),{verification:{required:!0,provider:"turnstile"}};if(!a.ok)throw await _(a,"Failed to load the secure card form");let u=await a.json();return this.directTelemetry?.performance({stage:"vault_request",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"2xx"}),this.toVaultBlock(u)}catch(a){let u=r.signal.aborted?new y("Timed out while loading the secure card form. Please try again.","api_error",{code:"vault_capture_timeout"}):a;throw this.reportDirectFailure(u,"VAULT_LOAD_FAILED","vault_request","vault_capture","card"),u}finally{clearTimeout(s)}}async getUnifiedCheckoutSession(e,t){let r=await this.getCheckoutSession(e,t);return this.normalizeCheckoutSessionResponse(r)}async getUnifiedCheckoutSessionForRecovery(e,t,r){let s=await this.fetchCheckoutSession(e,t,!1,r);return this.normalizeCheckoutSessionResponse(s)}normalizeCheckoutSessionResponse(e){try{let t=this.normalizeRawSession(e.data),r=e.vault;return r&&t.data.session&&(t.data.session.vault=this.toVaultBlock(r)),t}catch(t){throw U(t)}}async processPayment(e,t,r){this.beginDirectTelemetryCheckout(t.sessionId);let s=t.paymentMethodCategory??"unknown";if(!t.nonce)throw this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"process_payment",paymentMethodCategory:s}),new y("processPayment requires `nonce` \u2014 pass the value returned from session creation.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let o=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.processing.started",stage:"processing",requestCategory:"process_payment",paymentMethodCategory:s});let{nonce:i,paymentMethodCategory:a,...u}=t,c=Rt(t.tokenizedData),d,h;try{d=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(t.sessionId)}/process`,{method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":i},body:JSON.stringify(u)}),h=d}catch(l){if(Z(l))throw this.reportDirectFailure(l,"PAYMENT_PROCESSING_FAILED","processing","process_payment",s),l;d=await this.reconcileProcessPayment(t.sessionId,{...r,nonce:i,paymentMethodCategory:s,submittedIntentId:c})}if(!d.ok&&d.status!==202){let l=await It(d);return l?this.directTelemetry?.terminal({outcome:l,stage:"processing",requestCategory:"process_payment",statusClass:"4xx",paymentMethodCategory:s}):this.directTelemetry?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",requestCategory:"process_payment",statusClass:A(d.status),failureCategory:d.status>=500?"server_error":void 0,paymentMethodCategory:s,...pt(h)}),d}try{let l=await this.resolveProcessResponse(d,t.sessionId,{...r,nonce:i,paymentMethodCategory:s,submittedIntentId:c});return this.directTelemetry?.log({name:"payment.processing.completed",stage:"processing",requestCategory:"process_payment",statusClass:A(l.status),paymentMethodCategory:s}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"process_payment",statusClass:A(l.status),paymentMethodCategory:s}),l}catch(l){throw l instanceof y&&l.code==="checkout_processing_timeout"||this.reportDirectFailure(l,"PAYMENT_PROCESSING_FAILED","processing","process_payment",s),l}}async patchAccountSnapshot(e,t,r,s){this.beginDirectTelemetryCheckout(e);let o=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.state_transition",stage:"processing",requestCategory:"account_snapshot"});let i=s?.timeoutMs??kt,a=new AbortController,u=()=>a.abort();s?.signal&&(s.signal.aborted?a.abort():s.signal.addEventListener("abort",u,{once:!0}));let c=setTimeout(()=>a.abort(),i);try{let d;try{d=await j(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/account`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":t},body:JSON.stringify(r),signal:a.signal},K,h=>{this.telemetryHooks?.onRetry?.("account_snapshot",h),this.directTelemetry?.log({name:"operation.retry",stage:"processing",requestCategory:"account_snapshot",attempt:h})})}finally{clearTimeout(c),s?.signal?.removeEventListener("abort",u)}if(!d.ok)throw await _(d,"Failed to persist account snapshot");this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"account_snapshot",statusClass:"2xx"})}catch(d){throw this.reportAccountSnapshotFailure(d,s?.telemetryMode??"blocking"),d}}async createSessionIntent(e,t,r,s){if(!t)throw new y("createSessionIntent requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let o=r,i=o.paymentMethodType,a=typeof i=="string"&&i.trim().toLowerCase()==="card",u=typeof i=="string"&&i.length>0&&!a&&(typeof o.paymentMethodId=="string"||o.paymentMethodId===null),c=o.provider==="stripe"&&(o.paymentMethodCategory==="wallet"||o.paymentMethodCategory==="apm")&&(o.intentKind==="payment"||o.intentKind==="setup"),d=o.provider==="paypal"&&o.paymentMethodCategory==="wallet"&&o.paymentMethodId===null&&(o.paymentMethodType==="paypal"&&o.intentKind==="payment"||o.paymentMethodType===J&&(o.intentKind==="payment"||o.intentKind==="setup"));if(!u||!c&&!d)throw new y("Only wallet, APM, and PayPal session intents are supported.","validation_error",{code:"InvalidSessionIntentRequest"});let h=o.authorizationAttemptId;if(h!==void 0&&!ge(h))throw new y("authorizationAttemptId must be a v4 UUID identifying one buyer authorization attempt.","validation_error",{code:"InvalidAuthorizationAttemptId",param:"authorizationAttemptId"});let l=ge(h)?h:mt();this.beginDirectTelemetryCheckout(e);let g=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.intent.started",stage:"processing",requestCategory:"intent_create"});let m={"Content-Type":"application/json","x-checkout-session-token":t,[ye]:s?.idempotencyKey||l},C=!1;try{let f=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents`,{method:"POST",headers:m,body:JSON.stringify({...r,authorizationAttemptId:l}),signal:s?.signal});if(!f.ok){C=!0;let G=await _(f,"Failed to create checkout intent"),Be=F(G,"PAYMENT_PROCESSING_FAILED");throw Ae(G.statusCode)?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"intent_create",statusClass:"4xx"}):this.directTelemetry?.error({...Be,stage:"processing",requestCategory:"intent_create"}),G}let v=await f.json();if(f.status===202&&q(v)&&v.type==="checkout_processing")return C=!0,await this.settleProcessingSessionIntent(v,f,e,t,r);let T=v.data;if(!T||typeof T!="object")throw new y("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});let p=T,oe=p.paymentMethodType,Ne=(p.paymentMethodCategory==="wallet"||p.paymentMethodCategory==="apm")&&typeof oe=="string"&&oe.trim().toLowerCase()!=="card"&&(typeof p.paymentMethodId=="string"||p.paymentMethodId===null)&&typeof p.providerObjectId=="string",Ve=p.provider==="stripe"&&(p.intentKind==="payment"||p.intentKind==="setup")&&typeof p.clientSecret=="string",ze=p.provider==="paypal"&&p.paymentMethodCategory==="wallet"&&p.paymentMethodId===null&&(p.paymentMethodType==="paypal"&&p.intentKind==="payment"&&(p.providerObjectType==="order"||p.providerObjectType==="subscription")||p.paymentMethodType===J&&p.intentKind==="payment"&&p.providerObjectType==="order"||p.paymentMethodType===J&&p.intentKind==="setup"&&p.providerObjectType==="setup_token")&&p.clientSecret===null,He=p.provider===r.provider&&p.paymentMethodCategory===r.paymentMethodCategory&&p.paymentMethodType===r.paymentMethodType&&p.paymentMethodId===r.paymentMethodId&&p.intentKind===r.intentKind;if(!Ne||!Ve&&!ze||!He)throw new y("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});return this.directTelemetry?.log({name:"payment.intent.completed",stage:"processing",requestCategory:"intent_create",statusClass:A(f.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-g),durationMode:"machine",requestCategory:"intent_create",statusClass:A(f.status)}),p}catch(f){throw C||this.reportDirectFailure(f,"PAYMENT_PROCESSING_FAILED","processing","intent_create"),f}}async settleProcessingSessionIntent(e,t,r,s,o){let i=this.toCheckoutProcessingPending(e,t,r);try{return{settled:!0,response:await this.resolveCheckoutProcessing(i,r,{nonce:s,paymentMethodCategory:o.provider==="paypal"?"paypal":o.paymentMethodCategory})}}catch(a){throw a instanceof y&&a.code==="checkout_processing_timeout"?new y(a.message,a.type,{code:a.code,statusCode:202,sessionId:i.sessionId,cause:a}):a}}async reportSessionIntentDecline(e,t,r,s){if(!t)throw new y("reportSessionIntentDecline requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let o=r,i=o.providerDeclineReason,a=o.paymentMethodType,u=o.providerIntentId,c=typeof i=="string"&&/^[a-z0-9][a-z0-9_.:-]{0,63}$/i.test(i)&&!/^(?:pm|pi|seti|tok|src|cus|sess|sk|pk)_/i.test(i),d=typeof a=="string"&&a.length>0&&a.trim().toLowerCase()!=="card"&&c,h=o.provider==="stripe"&&(o.paymentMethodCategory==="wallet"||o.paymentMethodCategory==="apm")&&(u===void 0||typeof u=="string"&&/^pi_[a-z0-9_]{1,252}$/i.test(u)),l=o.provider==="paypal"&&o.paymentMethodCategory==="wallet"&&o.paymentMethodType==="paypal"&&u===void 0;if(!d||!h&&!l)throw new y("Invalid non-card decline classification.","validation_error",{code:"InvalidSessionIntentDeclineRequest"});let g=l?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:i}:{provider:"stripe",paymentMethodCategory:o.paymentMethodCategory,paymentMethodType:o.paymentMethodType,providerDeclineReason:i,...typeof u=="string"?{providerIntentId:u}:{}},m=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents/decline`,{method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":t},body:JSON.stringify(g),signal:s?.signal});if(!m.ok)throw await _(m,"Failed to report checkout decline")}async getPaymentsByEmail(e,t){this.beginDirectTelemetryOperation();let r=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved"});let s=t?.page??1,o=t?.limit??1,i=new URLSearchParams({email:e,page:String(s),limit:String(o),sortField:"createdAt",sortDirection:"DESC"});try{let a=await fetch(`${this.baseUrl}/v1/payments?${i.toString()}`,{method:"GET",signal:t?.signal,keepalive:!0});if(!a.ok)throw we(new y("Failed to fetch payments","api_error",{statusCode:a.status}),a);let u=await a.json();return this.directTelemetry?.log({name:"operation.recovery.completed",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),this.directTelemetry?.performance({stage:"recovery",durationMs:Math.max(0,this.telemetryTimestamp()-r),durationMode:"machine",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),u}catch(a){throw this.reportDirectFailure(a,"RECOVERY_FAILED","recovery","other","saved"),a}}async createAndFetchSession(e){if(dt(e)){let o=e.account.email?.trim();if(o&&!fe(o))throw new y("Buyer email must be valid when supplied.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"});return(await this.createDetachedSession(e)).claimed}this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp(),r=I(e.timeoutMs??12e3),s={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});try{let o=await this.createAndFetchSessionRequest(e,r.signal,s);return this.adoptDirectTelemetryCheckout(o.data.session?.id),this.directTelemetry?.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:s.statusClass}),this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:"session_create",statusClass:s.statusClass,attempt:s.attempt}),o}catch(o){throw this.reportSessionCreateFailure(o,t,s),o}finally{r.clear()}}async createAndFetchSessionRequest(e,t,r){let s=e.products??Q(e.items,e.subscriptions);he({captureMethod:e.captureMethod,products:s});let o=X(e.currency,e.items,e.subscriptions,s);if(!o)throw new y("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:E,successUrl:e.successUrl,cancelUrl:e.cancelUrl,currency:o,checkoutMode:e.checkoutMode??"full",products:s.map(c=>re(c,o)),accountData:Ie(e.account),couponCodes:e.couponCodes??[]};e.captureMethod==="manual"&&(i.captureMethod=e.captureMethod),e.tokenizedData&&(i.tokenizedData=e.tokenizedData),Pe(i,e);let a=await this.postCheckoutSessionCreate(i,e,t,r),u=!1;try{let c=await a.json();if(c.data&&"gateways"in c.data){this.autoCacheDisplayData(c.data.uuid,e);let l=this.mergeCachedDisplayData(c.data),g=this.normalizeRawSession(l);return c.vault&&g.data.session&&(g.data.session.vault=this.toVaultBlock(c.vault)),{...g,autoProcessingError:c.autoProcessingError,autoProcessingAttempted:c.autoProcessingAttempted,autoProcessingPending:c.autoProcessingPending}}let d=c.data?.uuid;if(!d)throw new y("No session ID returned","api_error",{code:"InvalidCheckoutSessionResponse"});return this.autoCacheDisplayData(d,e),this.adoptDirectTelemetryCheckout(d),u=!0,{...await this.getUnifiedCheckoutSession(d),autoProcessingError:c.autoProcessingError,autoProcessingAttempted:c.autoProcessingAttempted,autoProcessingPending:c.autoProcessingPending}}catch(c){throw u?c:U(c)}}async postCheckoutSessionCreate(e,t,r,s){let o={"Content-Type":"application/json",[H]:E},i=ht(t.idempotencyKey);i&&(o[ye]=i),t.checkoutMode==="auto"&&(o[ct]=ot);let a,u=!1,c=Dt(t),d=(l,g,m)=>{u||(u=!0,this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:m,attempt:l}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:Math.max(0,this.telemetryTimestamp()-g),durationMode:"machine",requestCategory:"session_create",statusClass:m,attempt:l}))},h=l=>{try{this.telemetryHooks?.onRetry?.("session_create",l),this.directTelemetry?.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:l})}catch{}};for(let l=0;l<3;l++){s.attempt=l;let g=this.telemetryTimestamp();try{c?.onAttempt?.(l)}catch{}try{a=await fetch(`${this.baseUrl}/v1/checkouts/sessions?expand=true`,{method:"POST",headers:o,body:JSON.stringify(e),signal:r})}catch(f){if(s.statusClass=r.aborted||f instanceof Error&&f.name==="AbortError"?"timeout":"network_error",r.aborted||f instanceof Error&&f.name==="AbortError"||l>=2)throw f;let v=l+1;h(v),await z(l,r);continue}let m=A(a.status);if(s.statusClass=m,a.status===204)throw d(l,g,m),new y("Session auto-completed \u2014 payment method already on file","api_error",{code:"session_auto_completed"});if(a.ok){d(l,g,m);break}let C=await _(a,"Failed to create checkout session");if(C.code===lt&&l<2){h(l+1),await z(l,r);continue}throw d(l,g,m),C}if(!a)throw new TypeError("Checkout-session creation exhausted its retry budget.");return a}async createDetachedSession(e){this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp(),r=I(e.timeoutMs??12e3),s={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let o=e.products??Q(e.items,e.subscriptions);try{he({captureMethod:e.captureMethod,products:o})}catch(v){throw r.clear(),this.reportSessionCreateFailure(v,t,s),v}let i=X(e.currency,e.items,e.subscriptions,o);if(!i)throw r.clear(),this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),new y("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{Ee(e,i,o)}catch(v){throw r.clear(),this.reportSessionCreateFailure(v,t,s),v}let a,u,c=!1;try{let v=await this.postCheckoutSessionCreate(xt(e,i),e,r.signal,s);if(c=!0,u=await v.json(),!u.data||!("gateways"in u.data))throw new y("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(u.data)),u.vault&&a.data.session&&(a.data.session.vault=this.toVaultBlock(u.vault))}catch(v){throw r.clear(),c&&U(v),this.reportSessionCreateFailure(v,t,s),v}let d=a.data.session?.id??u.data.uuid??"",h=a.data.session?.clientSecret??u.data.nonce??"";if(!d||!h){r.clear();let v=new y("Checkout session shell was created without a session id or nonce.","api_error",{code:"InvalidCheckoutSessionResponse"});throw this.reportSessionCreateFailure(v,t,s),v}r.clear(),this.adoptDirectTelemetryCheckout(d),this.directTelemetry?.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",statusClass:s.statusClass,paymentMethodCategory:"card"}),this.directTelemetry?.performance({stage:"session_shell",durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:"session_create",statusClass:s.statusClass,attempt:s.attempt,paymentMethodCategory:"card"});let l=!e.account.email?.trim(),g=I(e.timeoutMs??12e3),m=this.claimCheckoutSession(d,h,l?Ft(e,i,o):Ee(e,i,o),{params:e,startedAt:t,deadline:g,createAttempt:s.attempt}),C=l?void 0:m,f=(v={})=>{if(C!==void 0)return C;let T={...e,account:{...e.account,...v,email:v.email?.trim()||e.account.email?.trim()}};return fe(T.account.email)?(C=m.then(()=>{let p=this.telemetryTimestamp();return this.claimCheckoutSession(d,h,Ut(T.account),{params:T,startedAt:p,deadline:I(e.timeoutMs??12e3),createAttempt:0})}),C.catch(()=>{}),C):Promise.reject(new y("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}))};return m.catch(()=>{}),{shell:a,sessionId:d,nonce:h,claimed:m,claim:f}}async claimCheckoutSession(e,t,r,s){let o=s?.startedAt??this.telemetryTimestamp(),i=this.telemetryTimestamp(),a=s?.deadline??I(12e3),u=JSON.stringify(r),c="unknown",d=0,h=!1;this.directTelemetry?.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"});try{let l;for(d=0;d<3;d++){try{l=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/claim`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":t,[H]:E},body:u,signal:a.signal})}catch(C){let f=a.signal.aborted||C instanceof Error&&C.name==="AbortError";if(c=f?"timeout":"network_error",f||d>=2)throw C;try{this.telemetryHooks?.onRetry?.("session_claim",d+1),this.directTelemetry?.log({name:"operation.retry",stage:"session_claim",requestCategory:"session_claim",attempt:d+1})}catch{}await z(d,a.signal);continue}if(c=A(l.status),l.ok)break;throw await _(l,"Failed to attach checkout session data")}if(!l)throw new TypeError("Checkout-session claim exhausted its retry budget.");h=!0;let g=await l.json();if(!g.data?.gateways)throw new y("The billing API returned no checkout session with gateways after claiming it.","api_error",{code:"InvalidCheckoutSessionResponse"});s?.params&&this.autoCacheDisplayData(g.data.uuid??e,s.params);let m=this.normalizeRawSession(this.mergeCachedDisplayData(g.data));return g.vault&&m.data.session&&(m.data.session.vault=this.toVaultBlock(g.vault)),this.directTelemetry?.log({name:"session.claim.completed",stage:"session_claim",requestCategory:"session_claim",statusClass:c}),this.directTelemetry?.performance({stage:"session_claim",durationMs:Math.max(0,this.telemetryTimestamp()-i),durationMode:"machine",requestCategory:"session_claim",statusClass:c,attempt:d}),this.directTelemetry?.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:c}),this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"session_create",statusClass:c,attempt:s?.createAttempt??d}),m}catch(l){throw h&&U(l),this.reportSessionCreateFailure(l,i,{attempt:d,statusClass:c},"session_claim"),l}finally{a.clear()}}reportSessionCreateFailure(e,t,r,s="session_create"){if(!(e instanceof y&&e.code==="session_auto_completed"))try{this.telemetryHooks?.onSessionCreateFailure?.(e)}catch{}let o=F(e,"CHECKOUT_SESSION_CREATE_FAILED");if(this.directTelemetry?.performance({stage:s,durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:s==="session_claim"?"session_claim":"session_create",statusClass:o.statusClass,attempt:r.attempt}),e instanceof y&&e.type==="validation_error"||e instanceof y&&Ae(e.statusCode)){this.directTelemetry?.terminal({outcome:"validation_rejected",stage:s,requestCategory:s==="session_claim"?"session_claim":"session_create",...e.type==="validation_error"?{}:{statusClass:"4xx"}});return}e instanceof y&&e.code==="session_auto_completed"||this.directTelemetry?.error({...o,stage:s,requestCategory:s==="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,t){this.beginDirectTelemetryCheckout(e);let r=this.telemetryTimestamp(),s=t?.paymentMethodCategory??"saved";this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:s});let o=t?.timeoutMs??B,i=Date.now()+o,a=new AbortController,u=!1,c,d=setTimeout(()=>{c=setTimeout(()=>{u=!0,a.abort()},_e)},o),h=()=>a.abort(t?.signal?.reason);t?.signal?.aborted?h():t?.signal?.addEventListener("abort",h,{once:!0});let l=this.clampRetryAfterMs(t?.initialDelayMs??Se),g=0;try{if(t?.statusUrl){let m=await this.waitForCheckoutStatus(e,{initialDelayMs:l,timeoutMs:o,nonce:t.nonce,statusUrl:t.statusUrl,pollAfterAction:t.continueAfterActionRequired,signal:a.signal});if(m){let C=await this.resolveCheckoutSessionStatus(e,m,t.nonce,a.signal,()=>u);return this.reportRecoveryCompleted(r,s),C}}for(;;){let m=i-Date.now();if(m<=0)throw b();if(l>0){try{g+=1,this.telemetryHooks?.onRetry?.("session_read",g),this.directTelemetry?.log({name:"operation.retry",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:s,attempt:g})}catch{}if(await ee(Math.min(l,m),a.signal),Date.now()>=i)throw b()}let C=await this.getUnifiedCheckoutSessionForRecovery(e,t?.nonce,a.signal),f=C.data.session?.status;if(f==="authorized"||f==="complete"||f==="expired")return this.reportRecoveryCompleted(r,s),C;if(Date.now()>=i)throw b();l=this.clampRetryAfterMs(Math.max(l*2,Re))}}catch(m){let C=u&&Z(m)?b():m;throw this.reportDirectFailure(C,"RECOVERY_FAILED","recovery","session_read",s),C}finally{clearTimeout(d),clearTimeout(c),t?.signal?.removeEventListener("abort",h)}}reportRecoveryCompleted(e,t){let r={stage:"recovery",requestCategory:"session_read",paymentMethodCategory:t};this.directTelemetry?.log({name:"operation.recovery.completed",...r}),this.directTelemetry?.performance({...r,durationMs:Math.max(0,this.telemetryTimestamp()-e),durationMode:"machine"})}async resolveCheckoutSessionStatus(e,t,r,s,o){let i=t.latestTransactionAttempt;if(this.rememberReportedFailure(e,t),i?.result==="DECLINE"){let c=i.code===ve;throw new y(c?Te:"Payment was declined. Please choose another payment method.","api_error",{code:i.code??i.declineReason??"authorization_declined",statusCode:400})}if(i?.result==="ERROR"||t.status==="voided")throw new y("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,r,s)}catch(c){if(!o?.()||!Z(c))throw c;a={providers:[],mode:"tokenize",data:{},raw:t}}let u=a.data.session;return u&&i?.result==="SUCCESS"?{...a,data:{...a.data,session:{...u,status:"complete"}}}:u&&i?.result==="AUTHORIZED"?{...a,data:{...a.data,session:{...u,status:"authorized",paymentId:t.paymentId??void 0,authorizationExpiresAt:t.authorizationExpiresAt??void 0}}}:u&&t.status==="completed"?{...a,data:{...a.data,session:{...u,status:"complete"}}}:u&&t.status==="authorized"?{...a,data:{...a.data,session:{...u,status:"authorized",paymentId:t.paymentId??void 0,authorizationExpiresAt:t.authorizationExpiresAt??void 0}}}:u&&t.status==="expired"?{...a,data:{...a.data,session:{...u,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,t){let r=t.timeoutMs??B,s=Date.now()+r,o=this.clampRetryAfterMs(t.initialDelayMs);for(;;){let i=s-Date.now();if(i<=0||o>0&&(await ee(Math.min(o,i),t.signal),Date.now()>=s))throw b();let a=s-Date.now();if(a<=0)throw b();let u=new AbortController,c,d=t.signal?new Promise((T,p)=>{c=p}):null,h=()=>{u.abort(t.signal?.reason),c?.(t.signal?.reason??Object.assign(new Error("The operation was aborted."),{name:"AbortError"}))};t.signal?.aborted?h():t.signal?.addEventListener("abort",h,{once:!0});let l,g=t.signal?null:new Promise((T,p)=>{l=setTimeout(()=>{p(b()),u.abort()},a+_e)}),m;try{let T=this.fetchCheckoutStatus(e,t.nonce,t.statusUrl,u.signal);m=await Promise.race([T,g,d].filter(p=>p!==null))}finally{l!==void 0&&clearTimeout(l),t.signal?.removeEventListener("abort",h)}if(!m)return null;let C=be(m.latestTransactionAttempt)&&!this.isOwnFailedAttempt(e,m,t.submittedIntentId);if(m.status==="completed"||m.status==="authorized"||m.status==="expired"||m.status==="voided")return C?{...m,latestTransactionAttempt:null}:m;let f=m.latestTransactionAttempt?.result,v=t.pollAfterAction===!0&&f==="ACTION_REQUIRED";if(!C&&f!==void 0&&f!=="PENDING"&&!v)return m;o=this.clampRetryAfterMs(Math.max(o*2,Re))}}isOwnFailedAttempt(e,t,r){let s=t.latestTransactionAttempt?.providerIntentId??null;return r!==void 0?s===r:s===null?!0:!bt(t.uuid||e,s)}rememberReportedFailure(e,t){let r=t.latestTransactionAttempt;!be(r)||!r.providerIntentId||St(t.uuid||e,r.providerIntentId)}async fetchCheckoutStatus(e,t,r,s){let o=`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/status`,i=o;if(r)try{let d=new URL(r,`${this.baseUrl}/`),h=new URL(o);d.origin===h.origin&&(i=d.toString())}catch{}let a={[H]:E};t&&(a["x-checkout-session-token"]=t);let u=await j(i,{headers:a,signal:s});if(u.status===404||u.status===405)return null;if(!u.ok)throw await _(u,"Failed to get checkout session status");let c=await u.json();return q(c.data)&&"latestTransactionAttempt"in c.data?c.data:null}normalizeRawSession(e){let t=e.gateways??{},r=[],s={session:this.toCheckoutSession(e)},o=t.stripe;if(o?.publishableKey){r.push("stripe");let u=[e.stripeClientSecret,o.stripeClientSecret].find(c=>typeof c=="string"&&c.length>0);s.stripe={clientSecret:u??"",publishableKey:o.publishableKey??void 0,paypalPublishableKey:o.paypalPublishableKey??void 0,environment:o.environment,enabledPaymentMethods:Array.isArray(o.enabledPaymentMethods)?o.enabledPaymentMethods.filter(c=>typeof c=="string"):void 0}}let i=t.paypal;return i?.publishableKey&&(r.push("paypal"),s.paypal={publishableKey:i.publishableKey,environment:i.environment,providerObjectType:i.providerObjectType,approvalPresentation:i.approvalPresentation}),{providers:r,mode:"tokenize",...e.checkoutMetadata===void 0?{}:{checkoutMetadata:e.checkoutMetadata},data:s,raw:{data:e}}}toCheckoutSession(e){let t=e.products??[],r=typeof e.totalAmount=="number"&&Number.isFinite(e.totalAmount),s=t.reduce((c,d)=>c+(d.overrideAmount??d.totalAmount??0),0),o=r?e.totalAmount:s,i=Math.round(o*100),a=e.currency??t[0]?.currency??"USD",u="payment";return e.checkoutMode==="setup"?u="setup":t.some(c=>c.type==="subscription")&&(u="subscription"),{id:e.uuid,clientSecret:e.nonce,mode:u,status:this.toCheckoutSessionStatus(e.status),amount:i,currency:a,captureMethod:e.captureMethod,paymentId:e.paymentId,authorizationExpiresAt:e.authorizationExpiresAt,failureOutcome:Ce(e.outcome)??Ce(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}:{},...yt(e.futureUse)?{futureUse:e.futureUse}:{},...Array.isArray(e.futureUseUnsupported)?{futureUseUnsupported:e.futureUseUnsupported.filter(gt)}:{},buyerIdentified:e.buyerIdentified,providerPaymentMethodId:typeof e.providerPaymentMethodId=="string"?e.providerPaymentMethodId:null,products:t.map(c=>({...c,totalAmount:typeof c.totalAmount=="number"?c.totalAmount:void 0,overrideAmount:typeof c.overrideAmount=="number"?c.overrideAmount:null,currency:typeof c.currency=="string"?c.currency:void 0,metadata:c.metadata??null})),successUrl:e.successUrl,cancelUrl:e.cancelUrl,coupons:e.coupons,subtotalAmount:e.subtotalAmount,discountAmount:e.discountAmount,totalAmount:e.totalAmount,createdAt:e.createdAt,gateways:e.gateways,accountData:e.accountData,tagsData:e.tagsData}}toVaultBlock(e){let t=wt(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,...t?{verification:t}:{}}}toCheckoutSessionStatus(e){return e==="completed"?"complete":e==="authorized"?"authorized":e==="expired"?"expired":"open"}async resolveProcessResponse(e,t,r){if(e.status!==202)return e;let s=await e.json().catch(()=>null),o=this.toCheckoutProcessingPending(s,e,t);return this.resolveCheckoutProcessing(o,t,r)}async resolveCheckoutProcessing(e,t,r){let s=r?.pollTimeoutMs??B,o=Date.now()+s;if(e.statusUrl){let a=await this.waitForCheckoutStatus(e.sessionId,{initialDelayMs:e.retryAfterMs,timeoutMs:s,nonce:r?.nonce,statusUrl:e.statusUrl,submittedIntentId:r?.submittedIntentId});if(a)return this.toProcessResponseFromStatus(a,t,r?.nonce)}let i=await this.waitForCheckoutSessionCompletion(e.sessionId,{initialDelayMs:e.retryAfterMs,timeoutMs:o-Date.now(),nonce:r?.nonce,paymentMethodCategory:r?.paymentMethodCategory});return this.toProcessResponseFromSession(i,t)}async toProcessResponseFromStatus(e,t,r){let s=e.latestTransactionAttempt?.result,o={[Ct]:vt},i={"Content-Type":"application/json",...o};if(e.status==="completed"||s==="SUCCESS")return new Response(null,{status:204,statusText:"No Content",headers:o});if(e.status==="authorized"||s==="AUTHORIZED")return new Response(JSON.stringify({status:"authorized",paymentId:e.paymentId??void 0,sessionId:e.uuid||t,authorizationExpiresAt:e.authorizationExpiresAt??void 0}),{status:200,headers:i});if(e.status==="expired"){let a=await this.resolveCheckoutSessionStatus(t,e,r);return this.toProcessResponseFromSession(a,t)}if(this.rememberReportedFailure(t,e),s==="DECLINE"){let a=e.latestTransactionAttempt,u=a?.code===ve,c=a?.declineReason??void 0;return new Response(JSON.stringify({type:c??"authorization_declined",message:u?Te:"Payment was declined. Please choose another payment method.",code:a?.code??c??"authorization_declined",...c?{declineCode:c}:{}}),{status:400,headers:i})}if(s==="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(s==="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(s==="ERROR"||e.status==="voided")return new Response(JSON.stringify({type:"unknown",code:e.latestTransactionAttempt?.code??"payment_processing_error",message:ft(e)??"Payment could not be completed. Please try again."}),{status:500,headers:i});throw b()}async reconcileProcessPayment(e,t){let r=t?.pollTimeoutMs??B,s=Date.now()+r,o=null;try{o=await this.waitForCheckoutStatus(e,{initialDelayMs:0,timeoutMs:r,nonce:t?.nonce,submittedIntentId:t?.submittedIntentId})}catch(u){if(this.reportDirectFailure(u,"RECOVERY_FAILED","recovery","session_read",t?.paymentMethodCategory??"saved"),u instanceof y&&u.code==="checkout_processing_timeout")throw u}if(o)return this.toProcessResponseFromStatus(o,e,t?.nonce);let i=s-Date.now();if(i<=0)throw b();let a=await this.waitForCheckoutSessionCompletion(e,{initialDelayMs:0,timeoutMs:i,nonce:t?.nonce,paymentMethodCategory:t?.paymentMethodCategory});return this.toProcessResponseFromSession(a,e)}toProcessResponseFromSession(e,t){if(e.data.session?.status==="complete")return new Response(null,{status:204,statusText:"No Content"});if(e.data.session?.status==="authorized"){let r=e.data.session;return new Response(JSON.stringify({status:"authorized",paymentId:r.paymentId,sessionId:r.id||t,authorizationExpiresAt:r.authorizationExpiresAt}),{status:200,headers:{"Content-Type":"application/json"}})}if(e.data.session?.status==="expired"){let r=e.data.session.failureOutcome==="authorization_expired"||e.data.session.captureMethod==="manual";throw new y(r?"Authorization has expired.":"Checkout session has expired.","api_error",{code:r?"authorization_expired":"checkout_session_expired"})}throw b()}toCheckoutProcessingPending(e,t,r){let s=t.headers.get("Retry-After"),o=s===null||s.trim()===""?void 0:Number(s),i=o!==void 0&&Number.isFinite(o)?o*1e3:void 0;return{type:"checkout_processing",sessionId:k(e,"sessionId")??r,retryAfterMs:this.clampRetryAfterMs(Et(e,"retryAfterMs")??i??Se),statusUrl:k(e,"statusUrl"),sessionUrl:k(e,"sessionUrl")}}clampRetryAfterMs(e){return Math.max(0,Math.min(e,_t))}autoCacheDisplayData(e,t){if(!e)return;let r=t.products??Q(t.items,t.subscriptions);if(r.length===0&&!t.currency)return;let s=t.products!==void 0,o=X(t.currency,s?void 0:t.items,s?void 0:t.subscriptions,r);Y(e,{currency:o??void 0,products:r.map(i=>({code:i.code??i.providerItemId??i.providerPlanId,type:i.type,name:i.name??i.itemName??i.providerItemName??i.subscriptionName??i.providerPlanName??null,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency??o??void 0}))})}mergeCachedDisplayData(e){let t=ie(e.uuid),r=new Map,s=i=>i?`code:${i}`:void 0;for(let i of t?.products??[]){let a=s(i.code);a&&r.set(a,i)}let o=(e.products??[]).map(i=>{let a=s(i.code),u=a?r.get(a):void 0;return{...i,name:i.name??u?.name??null,totalAmount:i.totalAmount??u?.totalAmount,overrideAmount:i.overrideAmount??u?.overrideAmount,currency:i.currency??u?.currency}});return{...e,currency:e.currency??t?.currency,products:o}}};w.activeVaultCaptureRequests=new Map;var te=w;function mr(n,e){let t=te;return new t(n,e)}import{buildTelemetryErrorEvent as qt,buildTelemetryLogEvent as Lt,buildTelemetryTerminalEvent as Fe,FloPayError as De,resolveBillingApiUrl as Oe,SDK_VERSION as xe,THREE_DS_CHALLENGE_WINDOW_MS as Nt}from"@flopay/shared";var se="flopay-vault",Vt=3e4,zt=Nt+Vt,Ht="Card authentication timed out.",Ue={ready:["vault.widget.ready","vault_ready"],submitting:["vault.submission.started","vault_submit"],blocked:["operation.state_transition","vault_submit"],action_required:["vault.action.required","three_ds_handoff"]};function Bt(n){return n.class==="lifecycle"?n.name:n.class==="technical_error"?n.code:n.class==="expected_outcome"?n.outcome:"sdk.performance"}function D(n){let e={class:n.class,stage:n.stage};"code"in n&&(e.code=n.code),"provider"in n&&n.provider&&(e.provider=n.provider),"paymentMethodCategory"in n&&n.paymentMethodCategory&&(e.paymentMethodCategory=n.paymentMethodCategory),"outcome"in n&&(e.outcome=n.outcome),"durationMs"in n&&n.durationMs!==void 0&&(e.durationMs=n.durationMs),"durationMode"in n&&n.durationMode&&(e.durationMode=n.durationMode);try{globalThis.Sentry?.addBreadcrumb?.({category:"flopay.telemetry",level:n.class==="technical_error"?"error":"info",message:Bt(n),data:e})}catch{}}function L(n,e){return Lt({eventId:"11111111-1111-4111-8111-111111111111",name:n,stage:e,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}var jt=new Set(["authorization_declined","authentication_required","authorization_expired","capture_failed"]);function Kt(n){return typeof n=="string"&&jt.has(n)?n:"unknown"}var Gt=new Set(["verification_failed","verification_expired"]);function $t(n){return n==null?!0:typeof n=="string"&&Gt.has(n)}var Yt="vault_mount";function Wt(n){return n.failureStage===Yt}function qe(n,e){return n&&!Wt(e)?{errorCode:"VAULT_SUBMIT_FAILED",stage:"vault_submit",failureCategory:"provider_runtime",reason:Kt(e.failureOutcome)}:{errorCode:"VAULT_LOAD_FAILED",stage:"vault_mount",failureCategory:"provider_runtime"}}function Le(n,e,t="checkout"){return t==="card_setup"?n.type==="decline"?"card_setup_declined":"card_setup_succeeded":n.type==="decline"?"payment_declined":n.outcome==="authorized"||e==="manual"?"payment_authorized":"payment_succeeded"}function Qt(n,e,t,r="checkout"){let{type:s}=n;if(s==="complete"||s==="decline")return Fe({eventId:"22222222-2222-4222-8222-222222222222",outcome:Le(n,t,r),sequence:0,provider:"pcivault",paymentMethodCategory:"card"});if(s==="error"){let a=qe(e,n);return qt({eventId:"33333333-3333-4333-8333-333333333333",...a,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}let[o,i]=Ue[s];return L(o,i)}function Jt(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===se&&(e.type==="ready"||e.type==="submitting"||e.type==="blocked"||e.type==="complete"||e.type==="decline"||e.type==="error"||e.type==="action_required")}function Xt(n){if(typeof n!="object"||n===null)return;let e=n;if(typeof e.code!="string"||e.code.trim()==="")return;let t=typeof e.message=="string"&&e.message.trim()!==""?e.message:void 0;return t?{code:e.code,message:t}:{code:e.code}}function Zt(n){if(typeof n!="object"||n===null)return;let e=n,t=e.status;if(!(typeof e.id!="string"||e.id.trim()===""||typeof e.brand!="string"||e.brand.trim()===""||typeof e.lastFour!="string"||!/^\d{4}$/.test(e.lastFour)||typeof e.expiryMonth!="number"||!Number.isInteger(e.expiryMonth)||e.expiryMonth<1||e.expiryMonth>12||typeof e.expiryYear!="number"||!Number.isInteger(e.expiryYear)||e.expiryYear<1970||e.expiryYear>9999||t!=="pending"&&t!=="active"&&t!=="deleted"))return{id:e.id,brand:e.brand,lastFour:e.lastFour,expiryMonth:e.expiryMonth,expiryYear:e.expiryYear,status:t}}function er(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===se&&e.type==="validation"&&Array.isArray(e.messages)}function tr(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===se&&e.type==="resize"&&typeof e.height=="number"&&Number.isFinite(e.height)}var ne=class{constructor(e={},t){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=!t&&e.telemetry!==!1,this.telemetryReporter=t?.reporter??(this.ownsTelemetryReporter?new R({billingApiUrl:Oe(e.billingApiUrl),sdkVersion:xe}):void 0)}async mount(e,t){this.ownsTelemetryReporter&&!this.telemetryReporter&&(this.telemetryReporter=new R({billingApiUrl:Oe(this.config.billingApiUrl),sdkVersion:xe}));let r=this.telemetryReporter;if(this.config.operation==="card_setup"&&r&&this.setupTelemetryReporter!==r){this.setupTelemetryReporter=r;try{r.beginCheckout({checkoutMode:"setup"})}catch{}}if(this.mountStartedAt=this.telemetryReporter?.now?.()??S(),this.vaultReadyReported=!1,this.submissionStarted=!1,this.submissionStartedAt=null,typeof window>"u"||typeof document>"u")throw this.reportVaultLoadFailure(),new De("The vault card form is only available in the browser.","api_error",{code:"card_capture_no_window"});if(!t?.html?.trim())throw this.reportVaultLoadFailure(),new De("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=t.verificationRequired===!0,this.messageToken=t.messageToken??null,this.expectedOrigin=t.expectedOrigin??this.config.expectedOrigin??null,this.theme=t.theme,t.submitLabel!==void 0&&(this.submitLabel=t.submitLabel);try{this.attachMessageListener(),this.injectWidget(e,t.html)}catch(s){throw this.reportVaultLoadFailure(),s}this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),this.postSubmitLabel(),D(L("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?.()??S())-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,t){let r=this.listeners.get(e);return r||(r=new Set,this.listeners.set(e,r)),r.add(t),()=>{this.listeners.get(e)?.delete(t)}}unmount(){this.hideActionRequiredOverlay(),this.messageHandler&&(window.removeEventListener("message",this.messageHandler),this.messageHandler=null),this.container&&(this.container.replaceChildren(),this.container=null),this.messageToken=null,this.expectedOrigin=null,this.ownsTelemetryReporter&&(this.telemetryReporter?.destroy(),this.telemetryReporter=void 0)}injectWidget(e,t){e.innerHTML=t;let r=Array.from(e.querySelectorAll("script"));for(let s of r){let o=document.createElement("script");for(let i of Array.from(s.attributes))o.setAttribute(i.name,i.value);o.text=s.text,s.replaceWith(o)}}attachMessageListener(){if(this.messageHandler)return;let e=t=>{if(this.expectedOrigin&&t.origin!==this.expectedOrigin)return;let r=t.data;if(tr(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;this.applyHeight(r.height);return}if(er(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;let c=r.messages.filter(d=>typeof d=="string"&&d.trim()).join(" ");this.emit("validation",{sessionId:this.config.sessionId,message:c||void 0});return}if(!Jt(r)||this.messageToken&&r.messageToken!==this.messageToken)return;let s=this.config.sessionId,o=typeof r.sessionId=="string"?r.sessionId:void 0;if(s&&o&&o!==s||(r.type==="complete"||r.type==="decline")&&s&&o!==s)return;let i=Zt(r.paymentMethod),a=Xt(r.vaultOutcome),u={...r.sessionId??this.config.sessionId?{sessionId:r.sessionId??this.config.sessionId}:{},...r.outcome?{outcome:r.outcome}:{},...r.paymentId?{paymentId:r.paymentId}:{},...r.authorizationExpiresAt?{authorizationExpiresAt:r.authorizationExpiresAt}:{},...r.failureOutcome?{failureOutcome:r.failureOutcome}:{},...r.intentId?{intentId:r.intentId}:{},...r.declineReason?{declineReason:r.declineReason}:{},...r.message?{message:r.message}:{},...a?{vaultOutcome:a}:{},...i?{paymentMethod:i}:{}};r.type==="submitting"&&(this.submissionStarted=!0,this.submissionStartedAt=this.telemetryReporter?.now?.()??S()),this.isVerificationStateError(r)?(D(L("operation.state_transition","vault_mount")),this.telemetryReporter?.log({name:"operation.state_transition",stage:"vault_mount",provider:"pcivault",paymentMethodCategory:"card"})):(D(Qt(r,this.submissionStarted,this.config.captureMethod,this.config.operation)),this.reportOutcome(r)),r.type==="ready"&&(this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),this.postSubmitLabel()),r.type==="action_required"&&r.nextActionRedirectUrl&&this.showActionRequiredOverlay(r.nextActionRedirectUrl),(r.type==="complete"||r.type==="decline"||r.type==="error"||r.type==="submitting")&&this.hideActionRequiredOverlay(),r.type!=="action_required"&&this.emit(r.type,u)};this.messageHandler=e,window.addEventListener("message",e)}isVerificationStateError(e){return e.type==="error"&&this.verificationRequired&&!this.submissionStarted&&$t(e.failureOutcome)}reportOutcome(e){let t=this.telemetryReporter;if(!t)return;let{type:r}=e;if(r==="ready"&&!this.vaultReadyReported&&(this.vaultReadyReported=!0,t.performance({stage:"vault_ready",durationMs:Math.max(0,t.now()-this.mountStartedAt),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card",requestCategory:"provider_sdk"})),r==="complete"||r==="decline"){t.log({name:"vault.terminal",stage:"completion",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:Le(e,this.config.captureMethod,this.config.operation),provider:"pcivault",paymentMethodCategory:"card"});return}if(r==="error"){let i=qe(this.submissionStarted,e);t.log({name:"vault.terminal",stage:i.stage,provider:"pcivault",paymentMethodCategory:"card"}),t.error({...i,provider:"pcivault",paymentMethodCategory:"card"});return}if(r==="action_required"){t.log({name:"vault.action.required",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"}),t.log({name:"vault.three_ds.handoff",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"});let i=this.submissionStartedAt;this.submissionStartedAt=null,i!==null&&t.performance({stage:"three_ds_handoff",durationMs:Math.max(0,t.now()-i),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:"action_required",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"});return}let[s,o]=Ue[r];t.log({name:s,stage:o,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,t){this.cardFieldOrder=e,this.cardAutoFocus=t,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,t=this.config.sessionId,{messageToken:r,expectedOrigin:s}=this;e===void 0||!t||!r||!s||this.postToHostedWindow({source:"flopay-vault-host",type:"submitLabel",sessionId:t,messageToken:r,label:e},s)}hostedWindow(){return this.container?.querySelector("iframe")?.contentWindow??null}postToHostedWindow(e,t){let r=this.hostedWindow();if(r)try{r.postMessage(e,t)}catch{}}directiveTargetOrigin(){return this.expectedOrigin??"*"}emit(e,t){for(let r of this.listeners.get(e)??[])r(t)}showActionRequiredOverlay(e){if(typeof document>"u")return;if(this.actionOverlay){let i=this.actionOverlay.querySelector("iframe");i instanceof HTMLIFrameElement&&i.src!==e&&(i.src=e),this.armActionRequiredTimeout();return}this.actionOverlayPreviousFocus=document.activeElement instanceof HTMLElement?document.activeElement:null;let t=document.createElement("div");t.setAttribute("data-flopay-action-required","1"),t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-label","Card authentication"),t.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let r=document.createElement("iframe");r.setAttribute("title","Card authentication"),r.setAttribute("allow","payment"),r.tabIndex=0,r.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";"),r.src=e,t.appendChild(r);let s=document.createElement("button");s.type="button",s.setAttribute("aria-label","Close card authentication"),s.textContent="\xD7",s.style.cssText=["position:fixed","top:20px","right:20px","width:40px","height:40px","border:0","border-radius:9999px","background:#fff","color:#0f172a","font-size:28px","line-height:40px","cursor:pointer","box-shadow:0 4px 14px rgba(0,0,0,0.25)"].join(";"),s.addEventListener("click",()=>this.abandonActionRequiredOverlay()),t.appendChild(s),t.addEventListener("click",i=>{i.target===t&&this.abandonActionRequiredOverlay()});let o=i=>{if(i.source!==r.contentWindow)return;let a=i.data;!a||typeof a!="object"||a.source!=="flopay-vault-3ds-return"||(D(L("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",o),this.threeDsReturnHandler=o,document.body.appendChild(t),this.actionOverlay=t,r.focus(),this.armActionRequiredTimeout(),D(L("vault.three_ds.handoff","three_ds_handoff"))}armActionRequiredTimeout(){this.actionOverlayTimer&&clearTimeout(this.actionOverlayTimer),this.actionOverlayTimer=setTimeout(()=>{this.actionOverlayTimer=null,this.actionOverlay&&this.timeOutActionRequiredOverlay()},zt)}reportChallengeAbandoned(){D(Fe({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:Ht})}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 t=this.container?.querySelector("iframe");if(!t)return;let r=Math.max(0,Math.min(Math.ceil(e),2e3));t.style.height=`${r}px`}};function gr(n,e){let t=ne;return new t(n,{reporter:e})}export{ue as a,ce as b,I as c,z as d,Y as e,ie as f,ae as g,S as h,R as i,Pt as j,te as k,mr as l,ne as m,gr as n};