@flopay/js 1.14.15 → 1.16.0

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 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}`,a=G(t?.message)??G(r?.message)??Je(o,e);return new O(a,"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:a,items:i=[],subscriptions:d=[],products:s,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=s??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(`${a.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 a=await ge(e,o.signal,r);return r.commit(),ve(t,a),a}catch(a){throw r.commit(),j(t,a),a}finally{o.clear(),M(t.reporter)}}function he(e){let t=!1,r=e.startedAt,o;return{startAttempt(){r=e.reporter.now()},record(a){o={status:a,durationMs:Math.max(0,e.reporter.now()-r),attempt:e.attempt}},commit(){if(t||!o)return;t=!0;let a=ye(o.status);e.reporter.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:a,attempt:o.attempt}),e.reporter.performance({stage:"session_first_byte",durationMs:o.durationMs,durationMode:"machine",requestCategory:"session_create",statusClass:a,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),a=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),s;for(let c=0;c<=t;c++){o.attempt=c;try{let n=await ge(i,d.signal,a);return a.commit(),ve(o,n),d.clear(),M(o.reporter),n}catch(n){s=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 a.commit(),j(o,w),d.clear(),M(o.reporter),w}continue}throw a.commit(),j(o,n),d.clear(),M(o.reporter),n}}throw a.commit(),j(o,s),d.clear(),M(o.reporter),s??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),a=this.now();this.telemetryReporter?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let i,d,s=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 s("2xx"),this.telemetryReporter?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:"2xx"}),this.telemetryReporter?.log({name:"checkout.data.ready",stage:"checkout_data_ready"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-a,durationMode:"machine",requestCategory:"session_read",statusClass:"2xx"}),n}catch(n){let l=Ze(n,n instanceof V&&n.code==="checkout_processing_timeout"?"REQUEST_TIMEOUT":"NETWORK_REQUEST_FAILED");throw s(l.statusClass),this.telemetryReporter?.error({...l,stage:"session_read",provider:"flo",paymentMethodCategory:"unknown"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-a,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 s=new T({billingApiUrl:re(t?.billingApiUrl),sdkVersion:Ee,enabled:t?.telemetry!==!1});throw s.error({errorCode:"CONFIGURATION_INVALID",stage:"sdk_initialize",paymentMethodCategory:"unknown"}),s.flush().catch(()=>{}).finally(()=>s.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 a=K.get(r);if(a)return a;let i={...t,publishableKey:e},d=(async()=>{let s=new T({billingApiUrl:re(i.billingApiUrl),sdkVersion:Ee,enabled:i.telemetry!==!1}),c=s.now();s.log({name:"sdk.initialize.started",stage:"sdk_initialize"}),s.log({name:"sdk.cache.miss",stage:"sdk_initialize"}),s.log({name:"provider.load.started",stage:"provider_load",provider:"stripe"});let n=new N,l=s.now();try{await n.initialize(i)}catch(w){throw s.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:Re(w)?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"unknown"}),s.destroy(),w}let m=s.now();s.log({name:"provider.ready",stage:"provider_ready",provider:"stripe"}),s.log({name:"provider.availability.checked",stage:"provider_ready",provider:"stripe"}),s.log({name:"sdk.initialize.ready",stage:"sdk_initialize"}),s.performance({stage:"sdk_initialize",durationMs:m-c,durationMode:"machine",provider:"stripe"}),s.performance({stage:"provider_ready",durationMs:m-l,durationMode:"machine",provider:"stripe"});let h=Pe(n,i,s);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"})},a=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 a(k),k}catch{return{status:"unknown"}}finally{window.clearTimeout(I),e.signal?.removeEventListener("abort",g)}},s,c=()=>e.pollCompletionEndpoint!==!1?d():(s??(s=d()),s),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,a=new AbortController,i=()=>{o.abort(e.signal?.reason),a.abort(e.signal?.reason)};e.signal?.aborted?i():e.signal?.addEventListener("abort",i,{once:!0});let d=X(e.telemetry),s=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:a.signal,...d.attemptId?{challengeAttemptId:d.attemptId}:{}});c.catch(()=>{}),s.catch(()=>{});try{let n=await Promise.race([s,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(),a.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
+ 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-QFFZVSUD.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}`,a=G(t?.message)??G(r?.message)??Je(o,e);return new O(a,"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:a,items:i=[],subscriptions:d=[],products:s,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=s??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(`${a.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 a=await ge(e,o.signal,r);return r.commit(),ve(t,a),a}catch(a){throw r.commit(),j(t,a),a}finally{o.clear(),M(t.reporter)}}function he(e){let t=!1,r=e.startedAt,o;return{startAttempt(){r=e.reporter.now()},record(a){o={status:a,durationMs:Math.max(0,e.reporter.now()-r),attempt:e.attempt}},commit(){if(t||!o)return;t=!0;let a=ye(o.status);e.reporter.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:a,attempt:o.attempt}),e.reporter.performance({stage:"session_first_byte",durationMs:o.durationMs,durationMode:"machine",requestCategory:"session_create",statusClass:a,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),a=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),s;for(let c=0;c<=t;c++){o.attempt=c;try{let n=await ge(i,d.signal,a);return a.commit(),ve(o,n),d.clear(),M(o.reporter),n}catch(n){s=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 a.commit(),j(o,w),d.clear(),M(o.reporter),w}continue}throw a.commit(),j(o,n),d.clear(),M(o.reporter),n}}throw a.commit(),j(o,s),d.clear(),M(o.reporter),s??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),a=this.now();this.telemetryReporter?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let i,d,s=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 s("2xx"),this.telemetryReporter?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:"2xx"}),this.telemetryReporter?.log({name:"checkout.data.ready",stage:"checkout_data_ready"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-a,durationMode:"machine",requestCategory:"session_read",statusClass:"2xx"}),n}catch(n){let l=Ze(n,n instanceof V&&n.code==="checkout_processing_timeout"?"REQUEST_TIMEOUT":"NETWORK_REQUEST_FAILED");throw s(l.statusClass),this.telemetryReporter?.error({...l,stage:"session_read",provider:"flo",paymentMethodCategory:"unknown"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-a,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 s=new T({billingApiUrl:re(t?.billingApiUrl),sdkVersion:Ee,enabled:t?.telemetry!==!1});throw s.error({errorCode:"CONFIGURATION_INVALID",stage:"sdk_initialize",paymentMethodCategory:"unknown"}),s.flush().catch(()=>{}).finally(()=>s.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 a=K.get(r);if(a)return a;let i={...t,publishableKey:e},d=(async()=>{let s=new T({billingApiUrl:re(i.billingApiUrl),sdkVersion:Ee,enabled:i.telemetry!==!1}),c=s.now();s.log({name:"sdk.initialize.started",stage:"sdk_initialize"}),s.log({name:"sdk.cache.miss",stage:"sdk_initialize"}),s.log({name:"provider.load.started",stage:"provider_load",provider:"stripe"});let n=new N,l=s.now();try{await n.initialize(i)}catch(w){throw s.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:Re(w)?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"unknown"}),s.destroy(),w}let m=s.now();s.log({name:"provider.ready",stage:"provider_ready",provider:"stripe"}),s.log({name:"provider.availability.checked",stage:"provider_ready",provider:"stripe"}),s.log({name:"sdk.initialize.ready",stage:"sdk_initialize"}),s.performance({stage:"sdk_initialize",durationMs:m-c,durationMode:"machine",provider:"stripe"}),s.performance({stage:"provider_ready",durationMs:m-l,durationMode:"machine",provider:"stripe"});let h=Pe(n,i,s);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"})},a=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 a(k),k}catch{return{status:"unknown"}}finally{window.clearTimeout(I),e.signal?.removeEventListener("abort",g)}},s,c=()=>e.pollCompletionEndpoint!==!1?d():(s??(s=d()),s),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,a=new AbortController,i=()=>{o.abort(e.signal?.reason),a.abort(e.signal?.reason)};e.signal?.aborted?i():e.signal?.addEventListener("abort",i,{once:!0});let d=X(e.telemetry),s=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:a.signal,...d.attemptId?{challengeAttemptId:d.attemptId}:{}});c.catch(()=>{}),s.catch(()=>{});try{let n=await Promise.race([s,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(),a.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,4 +1,4 @@
1
- import type { AdvertisedPaymentMethod, CheckoutGateways, CheckoutSessionMode, CreateSessionIntentRequest, DetachedCheckoutSession, InlineSessionDraft, NormalizedCheckoutSession, ProcessPaymentParams, SessionIntentDeclineRequest, SessionIntentResult, TelemetryPaymentMethodCategory, TelemetryRequestCategory, VaultCaptureBlock } from '@flopay/shared';
1
+ import type { AdvertisedPaymentMethod, CheckoutGateways, CheckoutSessionMode, CreateSessionIntentRequest, DetachedCheckoutSession, InlineSessionDraft, NormalizedCheckoutSession, PaymentMethodLayout, PaymentMethodLayoutRules, ProcessPaymentParams, SessionIntentDeclineRequest, SessionIntentResult, TelemetryPaymentMethodCategory, TelemetryRequestCategory, VaultCaptureBlock } from '@flopay/shared';
2
2
  import type { SessionDisplayCacheData } from './session-display-cache.js';
3
3
  import type { BeginThreeDsChallengeInput, ThreeDsChallengeAttempt } from './three-ds-challenge.js';
4
4
  /** Raw billing API response wrapper. */
@@ -301,6 +301,17 @@ export declare class PaymentAPI {
301
301
  reportSessionIntentDecline(sessionId: string, nonce: string, request: SessionIntentDeclineRequest, options?: {
302
302
  signal?: AbortSignal;
303
303
  }): Promise<void>;
304
+ /**
305
+ * `POST /v1/checkouts/sessions/{id}/payment-method-layout` (billing API, backend#2721):
306
+ * applies the merchant's layout rules to this buyer and returns the order to show the
307
+ * payment method groups in. The billing API picks the buyer country (the session's, else
308
+ * the buyer's IP country, which it never returns); the SDK sends none. Resolves `null` when
309
+ * the billing API predates the route or answers without an order, so the caller falls back
310
+ * to the merchant's default order.
311
+ */
312
+ resolvePaymentMethodLayout(sessionId: string, nonce: string, rules: PaymentMethodLayoutRules, options?: {
313
+ signal?: AbortSignal;
314
+ }): Promise<PaymentMethodLayout | null>;
304
315
  /**
305
316
  * Fetch user's prior payments by email.
306
317
  * Used to determine if saved card UX should be shown.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flopay/js",
3
- "version": "1.14.15",
3
+ "version": "1.16.0",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "publishConfig": {
@@ -31,7 +31,7 @@
31
31
  "dist"
32
32
  ],
33
33
  "dependencies": {
34
- "@flopay/shared": "1.14.15",
34
+ "@flopay/shared": "1.16.0",
35
35
  "@stripe/stripe-js": "^10.3.0"
36
36
  },
37
37
  "devDependencies": {
@@ -1 +0,0 @@
1
- var et="flopay_session_display:";var N=new Map;function V(r){return`${et}${r}`}function Y(){if(typeof window>"u")return null;try{return window.sessionStorage}catch{return null}}function W(r,e,t){if(!r)return;let n=t?.ttlMs??36e5,s={data:e,expiresAt:Date.now()+n},i=Y();if(i)try{i.setItem(V(r),JSON.stringify(s));return}catch{}N.set(r,s)}function ae(r){if(!r)return null;let e=Y();if(e)try{let n=e.getItem(V(r));if(n){let s=JSON.parse(n);if(s&&typeof s.expiresAt=="number"&&s.expiresAt>Date.now())return s.data;e.removeItem(V(r))}}catch{}let t=N.get(r);if(t){if(t.expiresAt>Date.now())return t.data;N.delete(r)}return null}function le(r){if(!r)return;N.delete(r);let e=Y();if(e)try{e.removeItem(V(r))}catch{}}import{ASYNC_AUTO_CHECKOUT_CAPABILITY as vt,assertCaptureMethodEligible as Re,buildProductPayload as ne,CHECKOUT_PROCESSING_TIMEOUT_MESSAGE as Tt,CHECKOUT_SESSION_BUYER_EMAIL_REQUIRED as bt,classifyPaymentRejection as _t,classifyTelemetryFailure as F,FLO_SDK_CAPABILITIES_HEADER as St,FLO_SDK_VERSION_HEADER as H,FloPayError as C,foldIntoProducts as J,IDEMPOTENCY_IN_PROGRESS_CODE as Rt,IDEMPOTENCY_KEY_HEADER as Ae,isCardHolderNamePlaceholder as Le,isDetachedSessionEligible as At,isUuidV4 as Ee,isValidEmail as ke,markSessionResponseReceived as U,normalizeCheckoutFailureOutcome as we,PAYPAL_VAULTED_PAYMENT_METHOD_TYPE as X,randomUuidV4 as Et,readTelemetryHttpDiagnostics as kt,resolveIdempotencyKey as wt,resolveSessionCurrency as Z,SDK_VERSION as w,STORED_PAYMENT_METHOD_UNSUPPORTED_CODE as Me,STORED_PAYMENT_METHOD_UNSUPPORTED_MESSAGE as Ie,telemetryStatusClass as k,withTelemetryHttpDiagnostics as Ne}from"@flopay/shared";function ce(r){return typeof r=="string"&&r.trim()?r:void 0}function ue(r){if(typeof r=="string")return r.trim()?r:void 0;if(Array.isArray(r))return r.filter(t=>typeof t=="string"&&t.trim().length>0).join("; ")||void 0}function D(r=12e3){let e=Number.isFinite(r)&&r>=0?r:12e3,t=new AbortController,n=setTimeout(()=>t.abort(),e);return{signal:t.signal,clear:()=>clearTimeout(n)}}function tt(){return Object.assign(new Error("The operation was aborted."),{name:"AbortError"})}function B(r,e){let t=150*2**r,n=Math.round(t*(.75+Math.random()*.5));return new Promise((s,i)=>{let o,a=()=>e.removeEventListener("abort",l),l=()=>{o!==void 0&&clearTimeout(o),a(),i(tt())};if(e.aborted){l();return}o=setTimeout(()=>{a(),s()},n),e.addEventListener("abort",l,{once:!0})})}import{buildTelemetryErrorEvent as Ce,buildTelemetryLogEvent as ve,buildTelemetryPerformanceEvent as at,buildTelemetryTerminalEvent as lt,serializeTelemetryBatch as ct,TELEMETRY_MAX_BATCH_BYTES as ut}from"@flopay/shared";import{isThreeDsChallengeAttemptId as me}from"@flopay/shared";var rt=32,de=Symbol.for("@flopay/js.three-ds-challenge.attempts.v1");function nt(){let r=globalThis,e=r[de];if(e instanceof Map)return e;let t=new Map;try{Object.defineProperty(r,de,{configurable:!0,enumerable:!1,writable:!1,value:t})}catch{}return t}function st(r,e){let t=nt(),n=t.get(r);if(n)return n;for(;t.size>=rt;){let i=t.keys().next();if(i.done)break;t.delete(i.value)}let s={nextSequence:0,startedAt:e,terminated:!1,reconciled:new Set,provider:"unknown"};return t.set(r,s),s}var it=new Set(["pagehide_observed","cancel_requested","abort_observed","browser_terminal"]),ot=new Set(["teardown","recovery_read_completed","provider_reconciled"]);function he(r,e={}){let t=me(e.attemptId)?e.attemptId.toLowerCase():r.newAttemptId(),n=()=>{try{let a=r.now();return Number.isFinite(a)?a:0}catch{return 0}},s=st(t,n());(e.provider==="stripe"||e.provider==="worldpay")&&(s.provider=e.provider);let i=s.provider,o=(a,l)=>{if(s.terminated&&!ot.has(a))return;let c={attemptId:t,phase:a,attemptSequence:s.nextSequence,elapsedMs:Math.max(0,n()-s.startedAt),provider:i};s.nextSequence+=1,l.reason!==void 0&&(c.reason=l.reason),l.evidenceBasis!==void 0&&(c.evidenceBasis=l.evidenceBasis),l.terminalSource!==void 0&&(c.terminalSource=l.terminalSource),l.providerOutcome!==void 0&&(c.providerOutcome=l.providerOutcome);try{r.emit(c,it.has(a))}catch{}};return{attemptId:t,record(a,l={}){a==="browser_terminal"||a==="provider_reconciled"||o(a,{reason:l.reason,evidenceBasis:l.evidenceBasis})},terminal(a,l={}){s.terminated||(o("browser_terminal",{terminalSource:a,reason:l.reason,evidenceBasis:l.evidenceBasis}),s.terminated=!0)},reconcile(a){s.reconciled.has(a)||(s.reconciled.add(a),o("provider_reconciled",{providerOutcome:a,evidenceBasis:"provider_fact"}))}}}function pe(r){let e=null;try{e=me(r?.attemptId)?r?.attemptId??null:null}catch{e=null}return{attemptId:e,record(t,n){try{r?.record(t,n)}catch{}},terminal(t,n){try{r?.terminal(t,n)}catch{}},reconcile(t){try{r?.reconcile(t)}catch{}}}}function Q(r){if(typeof r!="string"||r.trim()==="")return"missing";try{let e=new URL(r);return e.protocol==="https:"||e.protocol==="http:"?"valid":"invalid"}catch{return"invalid"}}function br(r){return r==="buyer_cancel"||r==="component_unmount"||r==="navigation"?r:"unspecified"}function ye(r){try{if(typeof window>"u"||typeof window.getComputedStyle!="function")return null;for(let e=r;e;e=e.parentElement){let t=window.getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden"||t.visibility==="collapse"||t.opacity==="0")return"hidden"}return"visible"}catch{return null}}function ge(r,e){if(!e)return null;try{let t=r,n=String(t.effectiveDirective||t.violatedDirective||"").trim().split(/\s+/)[0],s=null;return n==="frame-src"&&(s="frame_src"),n==="child-src"&&(s="child_src"),!s||typeof t.blockedURI!="string"?null:new URL(t.blockedURI).origin===e?s:null}catch{return null}}function fe(r){try{return Q(r)==="valid"?new URL(r).origin:null}catch{return null}}var dt="/v1/sdk-telemetry/events",z=16,Te=64,mt=1500,be=1e3,ht=64,pt="00000000-0000-4000-8000-000000000000",yt={technical_error:8,lifecycle:32,expected_outcome:32,performance:24},gt=48;function S(){try{return globalThis.crypto.randomUUID()}catch{let r=new Uint8Array(16);try{globalThis.crypto.getRandomValues(r)}catch{for(let t=0;t<r.length;t+=1)r[t]=Math.floor(Math.random()*256)}r[6]=(r[6]??0)&15|64,r[8]=(r[8]??0)&63|128;let e=[...r].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 ft(r){try{return new TextEncoder().encode(r).byteLength}catch{return r.length}}function Ct(r){return JSON.stringify([r.code,r.failureCategory,r.reason,r.stage,r.provider,r.attempt,r.statusClass,r.requestCategory,r.paymentMethodCategory,r.walletType,r.operationOutcome,r.checkoutMode,r.layout,r.inAppBrowser,r.appFamily,r.popupCapability,r.presentationMode,r.terminalReason])}function _(){return globalThis.performance?.now()??0}var R=class{constructor(e){this.ingestionDisabled=!1;this.queue=[];this.sequence=0;this.threeDsChallengeCount=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(/\/+$/,"")}${dt}`,this.sdkPackage=e.sdkPackage??"@flopay/js",this.sdkVersion=e.sdkVersion,this.correlationId=S(),this.merchantEnabled=e.enabled!==!1,this.clock=e.clock??_,this.browserTransportAvailable=typeof window<"u"&&typeof document<"u",this.browserTransportAvailable&&(window.addEventListener("pagehide",this.pageExitHandler),document.addEventListener("visibilitychange",this.visibilityHandler))}log(e){this.notify({...e,class:"lifecycle"}),this.canCollect()&&this.enqueue(ve({...this.checkoutContext,...e,eventId:S(),sequence:this.sequence++}))}error(e){if(this.notify({...e,class:"technical_error"}),!this.canCollect())return;let t=Ce({...this.checkoutContext,...e,eventId:pt,sequence:0}),n=Ct(t),s=this.now();this.pruneReportedFailures(s);let i=this.reportedFailures.get(n);if(i!==void 0&&s>=i&&s-i<be){this.log({name:"operation.deduplicated",stage:e.stage,provider:e.provider,paymentMethodCategory:e.paymentMethodCategory,attempt:e.attempt,inAppBrowser:e.inAppBrowser,appFamily:e.appFamily,popupCapability:e.popupCapability,presentationMode:e.presentationMode,terminalReason:e.terminalReason});return}this.rememberReportedFailure(n,s),this.enqueue(Ce({...this.checkoutContext,...e,eventId:S(),sequence:this.sequence++}))}performance(e){this.canCollect()&&this.enqueue(at({...this.checkoutContext,...e,eventId:S(),sequence:this.sequence++}))}terminal(e){if(this.canCollect()&&(this.enqueue(lt({...this.checkoutContext,...e,eventId:S(),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"})}}beginThreeDsChallenge(e={}){return he({now:()=>this.now(),newAttemptId:S,emit:(t,n)=>this.recordThreeDsChallenge(t,n)},e)}recordThreeDsChallenge(e,t){if(!this.canCollect()||this.threeDsChallengeCount>=gt)return;let n=ve({...this.checkoutContext,...e,name:"three_ds.challenge",stage:"three_ds_handoff",eventId:S(),sequence:this.sequence++});if(!(this.queue.length>=Te)){if(this.threeDsChallengeCount+=1,this.queue.push(n),t){this.drainQueue();return}if(this.queue.length>=z){this.flush();return}this.scheduleFlush()}}now(){try{return this.clock()}catch{return _()}}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,n]of this.reportedFailures)(e<n||e-n>=be)&&this.reportedFailures.delete(t)}rememberReportedFailure(e,t){for(;this.reportedFailures.size>=ht;){let n=this.reportedFailures.keys().next();if(n.done)break;this.reportedFailures.delete(n.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.threeDsChallengeCount=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>=Te||this.eventCounts[e.class]>=yt[e.class])){if(this.eventCounts[e.class]+=1,this.queue.push(e),this.queue.length>=z){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,z);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,z);this.sendBatch(e)}}async sendBatch(e){if(!this.browserTransportAvailable||this.ingestionDisabled)return;let t=ct(e,{correlationId:this.correlationId,sdkPackage:this.sdkPackage,sdkVersion:this.sdkVersion,batchId:S()});if(ft(t)>ut)return;let n=typeof AbortController>"u"?null:new AbortController,s=null;try{let i=fetch(this.endpoint,{method:"POST",headers:{"content-type":"text/plain;charset=UTF-8"},body:t,credentials:"omit",keepalive:!0,referrerPolicy:"no-referrer",signal:n?.signal}).then(async l=>{if(l.status!==202)return null;let c=null;try{c=await l.json()}catch{}return c?.status==="disabled"?"disabled":null}).catch(()=>null),o=new Promise(l=>{s=setTimeout(()=>{n?.abort(),l(null)},mt)});await Promise.race([i,o])==="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)}},_e=Symbol.for("@flopay/js.telemetry.reporter-factory.v1"),Se=globalThis;Se[_e]===void 0&&Object.defineProperty(Se,_e,{configurable:!0,enumerable:!1,writable:!1,value:r=>new R(r)});function Mt(r){return r==="on_session"||r==="off_session"}function It(r){if(!r||typeof r!="object")return!1;let e=r;return typeof e.paymentMethodType=="string"&&typeof e.reason=="string"}function Dt(r){let e=r.vaultOutcome;if(!(!e||e.code!==bt))return typeof e.message=="string"&&e.message.trim()!==""?e.message:void 0}var Pt="x-flopay-process-result-source",Ot="status";function De(r){return r?.result==="DECLINE"||r?.result==="ERROR"}var xt=50,M=new Map;function Ft(r,e){return M.get(r)?.has(e)===!0}function Ut(r,e){let t=M.get(r)??new Set;if(t.add(e),M.delete(r),M.set(r,t),M.size>xt){let n=M.keys().next().value;n!==void 0&&M.delete(n)}}function qt(r){let e=r?.threeDSecureActionResultTokenId;if(typeof e=="string"&&e.length>0)return e;if(r?.gateway==="paypal"&&r.type!=="paypal_setup_token"&&typeof r.id=="string"&&r.id.length>0)return r.id}var Pe=0,Oe=500,j=15e3,xe=15e3,Lt=3e3,Nt=1e4,Vt=1e4;function q(r){return typeof r=="object"&&r!==null}function E(r,e){return ce(r?.[e])}function Fe(r,e){return ue(r?.[e])}function Bt(r,e){let t=r?.[e];return typeof t=="number"&&Number.isFinite(t)?t:void 0}function te(r,e){return e?new Promise((t,n)=>{let s=()=>{clearTimeout(i),n(e.reason??Object.assign(new Error("The operation was aborted."),{name:"AbortError"}))},i=setTimeout(()=>{e.removeEventListener("abort",s),t()},r);e.aborted?s():e.addEventListener("abort",s,{once:!0})}):new Promise(t=>setTimeout(t,r))}function ee(r){return r instanceof Error&&r.name==="AbortError"}function b(){return new C(Tt,"api_error",{code:"checkout_processing_timeout"})}async function A(r,e){let t=await r.json().catch(()=>null),n=q(t?.error)?t.error:null,s=Fe(t,"message")??Fe(n,"message")??e,i=E(t,"code")??E(t,"gatewayErrorCode")??E(n,"code")??`http_${r.status}`;return Ne(new C(s,"api_error",{code:i,statusCode:r.status}),r)}async function zt(r){if(r.status!==403)return!1;let e=await r.clone().json().catch(()=>null),t=q(e?.error)?e.error:null;return(E(e,"code")??E(t,"code"))==="verification_required"}function Ht(r){if(!(!q(r)||typeof r.required!="boolean"))return{required:r.required,provider:"turnstile"}}async function jt(r){let e=r.status===400?await r.clone().json().catch(()=>null):null;return _t(r.status,e)}function Ue(r){return r===400||r===422}var G=2;async function K(r,e,t=G,n,s){let i;for(let o=0;;o++)try{return s?.(o),await fetch(r,e)}catch(a){if(e?.signal?.aborted||a instanceof Error&&a.name==="AbortError")throw a;if(i=a,o>=t)throw i;try{n?.(o+1)}catch{}await te(150*2**o,e?.signal??void 0)}}var Kt=Symbol.for("@flopay/js.session-create.telemetry.v1");function Gt(r){return r[Kt]}function $t(r){return"now"in r||"onFirstByte"in r||"onSessionCreateFailure"in r||"onRetry"in r}function Ve(r){let e=Le(r.firstName,r.lastName);return{userId:r.userId,firstName:e?null:r.firstName??null,lastName:e?null:r.lastName??null,email:r.email,country:r.country??null,gender:r.gender??null,city:r.city??null,state:r.state??null,zip:r.zip??null,addressLine1:r.addressLine1??null,addressLine2:r.addressLine2??null}}function Be(r,e){e.checkoutMetadata!==void 0&&(r.checkoutMetadata=e.checkoutMetadata),e.tagsData&&(r.tagsData=e.tagsData),e.utmMetadata&&e.utmMetadata.length>0&&(r.utmMetadata=e.utmMetadata),e.avsCheck!==void 0&&(r.avsCheck=e.avsCheck),e.checkoutType&&(r.checkoutType=e.checkoutType),e.checkoutLayout&&(r.checkoutLayout=e.checkoutLayout),e.avsConfig&&(r.avsConfig=e.avsConfig)}function Yt(r,e){let t={clientId:r.clientId,checkoutVersion:w,successUrl:r.successUrl,cancelUrl:r.cancelUrl,currency:e,checkoutMode:"full",deferDataAttachment:!0};return r.captureMethod==="manual"&&(t.captureMethod=r.captureMethod),r.account.country&&(t.accountData={country:r.account.country}),Be(t,r),t}function qe(r,e,t){return{currency:e,products:t.map(n=>ne(n,e)),couponCodes:r.couponCodes??[],accountData:Ve(r.account)}}function Wt(r,e,t){return{currency:e,products:t.map(n=>ne(n,e)),couponCodes:r.couponCodes??[]}}function Qt(r){let e={},t=Le(r.firstName,r.lastName);for(let[n,s]of Object.entries(r)){if(t&&n.endsWith("Name")||typeof s!="string")continue;let i=s.trim();i&&(e[n]=i)}return{accountData:e}}var I=class I{constructor(e,t={}){this.baseUrl=e.replace(/\/+$/,"");let n=$t(t);this.telemetryHooks=n?t:void 0,this.directTelemetry=n||t.telemetry===!1?void 0:new R({billingApiUrl:this.baseUrl,sdkVersion:w})}destroy(){this.directTelemetry?.destroy()}reportDirectFailure(e,t,n,s,i="unknown"){let o=F(e,t);this.directTelemetry?.error({...o,stage:n,requestCategory:s,paymentMethodCategory:i})}reportAccountSnapshotFailure(e,t){let n=F(e,"NETWORK_REQUEST_FAILED");if(t==="best_effort"&&n.errorCode==="REQUEST_TIMEOUT"){this.directTelemetry?.log({name:"operation.fallback",stage:"processing",requestCategory:"account_snapshot",statusClass:"timeout"});return}this.directTelemetry?.error({...n,stage:"processing",requestCategory:"account_snapshot",paymentMethodCategory:"unknown"})}telemetryTimestamp(){try{return this.telemetryHooks?.now?.()??this.directTelemetry?.now()??_()}catch{return _()}}beginDirectTelemetryCheckout(e){!this.directTelemetry||this.directTelemetryCheckoutId===e||(this.directTelemetryCheckoutId=e,this.directTelemetry.beginCheckout())}beginDirectTelemetryOperation(){this.directTelemetry&&(this.directTelemetryCheckoutId=void 0,this.directTelemetry.beginCheckout())}adoptDirectTelemetryCheckout(e){e&&(this.directTelemetryCheckoutId=e)}async getCheckoutSession(e,t){return this.fetchCheckoutSession(e,t)}async fetchCheckoutSession(e,t,n=!0,s){this.beginDirectTelemetryCheckout(e);let i=this.telemetryTimestamp(),o=i,a=0;this.directTelemetry?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let l={[H]:w};t&&(l["x-checkout-session-token"]=t);let c=!1;try{let u=await K(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}`,{headers:l,signal:s},G,m=>{this.telemetryHooks?.onRetry?.("session_read",m),this.directTelemetry?.log({name:"operation.retry",stage:"session_read",requestCategory:"session_read",attempt:m})},m=>{a=m,o=this.telemetryTimestamp()});c=!0;let h=Math.max(0,this.telemetryTimestamp()-o);try{this.telemetryHooks?.onFirstByte?.(h,a)}catch{}let d=`${Math.floor(u.status/100)}xx`;if(this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:d,attempt:a}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:h,durationMode:"machine",requestCategory:"session_read",statusClass:d,attempt:a}),!u.ok)throw await A(u,"Failed to get checkout session");let g=await u.json();return this.directTelemetry?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:d}),this.directTelemetry?.performance({stage:"session_complete",durationMs:Math.max(0,this.telemetryTimestamp()-i),durationMode:"machine",requestCategory:"session_read",statusClass:d}),{...g,data:this.mergeCachedDisplayData(g.data)}}catch(u){throw c&&U(u),n&&this.directTelemetry?.error({...F(u,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"}),u}}cacheSessionDisplayData(e,t,n){W(e,t,n)}clearSessionDisplayData(e){le(e)}async getVaultCapture(e,t){let n=`${this.baseUrl}\0${e}\0${t??""}`,s=I.activeVaultCaptureRequests.get(n);if(s!==void 0)return s;let i=this.requestVaultCapture(e,t);I.activeVaultCaptureRequests.set(n,i);try{return await i}finally{I.activeVaultCaptureRequests.get(n)===i&&I.activeVaultCaptureRequests.delete(n)}}async requestVaultCapture(e,t){let n=new AbortController,s=setTimeout(()=>n.abort(),Vt);this.beginDirectTelemetryCheckout(e);let i=this.telemetryTimestamp();this.directTelemetry?.log({name:"vault.capture.requested",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card"});let o={"Content-Type":"application/json"};t&&(o["x-checkout-session-token"]=t);try{let a=await K(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/vault/capture`,{method:"POST",headers:o,signal:n.signal},G,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 zt(a))return this.directTelemetry?.performance({stage:"vault_request",durationMs:Math.max(0,this.telemetryTimestamp()-i),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"4xx"}),{verification:{required:!0,provider:"turnstile"}};if(!a.ok)throw await A(a,"Failed to load the secure card form");let l=await a.json();return this.directTelemetry?.performance({stage:"vault_request",durationMs:Math.max(0,this.telemetryTimestamp()-i),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"2xx"}),this.toVaultBlock(l)}catch(a){let l=n.signal.aborted?new C("Timed out while loading the secure card form. Please try again.","api_error",{code:"vault_capture_timeout"}):a;throw this.reportDirectFailure(l,"VAULT_LOAD_FAILED","vault_request","vault_capture","card"),l}finally{clearTimeout(s)}}async getUnifiedCheckoutSession(e,t){let n=await this.getCheckoutSession(e,t);return this.normalizeCheckoutSessionResponse(n)}async getUnifiedCheckoutSessionForRecovery(e,t,n){let s=await this.fetchCheckoutSession(e,t,!1,n);return this.normalizeCheckoutSessionResponse(s)}normalizeCheckoutSessionResponse(e){try{let t=this.normalizeRawSession(e.data),n=e.vault;return n&&t.data.session&&(t.data.session.vault=this.toVaultBlock(n)),t}catch(t){throw U(t)}}async processPayment(e,t,n){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 C("processPayment requires `nonce` \u2014 pass the value returned from session creation.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let i=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.processing.started",stage:"processing",requestCategory:"process_payment",paymentMethodCategory:s});let{nonce:o,paymentMethodCategory:a,...l}=t,c=qt(t.tokenizedData),u,h;try{u=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(t.sessionId)}/process`,{method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":o},body:JSON.stringify(l)}),h=u}catch(d){if(ee(d))throw this.reportDirectFailure(d,"PAYMENT_PROCESSING_FAILED","processing","process_payment",s),d;u=await this.reconcileProcessPayment(t.sessionId,{...n,nonce:o,paymentMethodCategory:s,submittedIntentId:c})}if(!u.ok&&u.status!==202){let d=await jt(u);return d?this.directTelemetry?.terminal({outcome:d,stage:"processing",requestCategory:"process_payment",statusClass:"4xx",paymentMethodCategory:s}):this.directTelemetry?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",requestCategory:"process_payment",statusClass:k(u.status),failureCategory:u.status>=500?"server_error":void 0,paymentMethodCategory:s,...kt(h)}),u}try{let d=await this.resolveProcessResponse(u,t.sessionId,{...n,nonce:o,paymentMethodCategory:s,submittedIntentId:c});return this.directTelemetry?.log({name:"payment.processing.completed",stage:"processing",requestCategory:"process_payment",statusClass:k(d.status),paymentMethodCategory:s}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-i),durationMode:"machine",requestCategory:"process_payment",statusClass:k(d.status),paymentMethodCategory:s}),d}catch(d){throw d instanceof C&&d.code==="checkout_processing_timeout"||this.reportDirectFailure(d,"PAYMENT_PROCESSING_FAILED","processing","process_payment",s),d}}async patchAccountSnapshot(e,t,n,s){this.beginDirectTelemetryCheckout(e);let i=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.state_transition",stage:"processing",requestCategory:"account_snapshot"});let o=s?.timeoutMs??Nt,a=new AbortController,l=()=>a.abort();s?.signal&&(s.signal.aborted?a.abort():s.signal.addEventListener("abort",l,{once:!0}));let c=setTimeout(()=>a.abort(),o);try{let u;try{u=await K(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/account`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":t},body:JSON.stringify(n),signal:a.signal},G,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",l)}if(!u.ok)throw await A(u,"Failed to persist account snapshot");this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-i),durationMode:"machine",requestCategory:"account_snapshot",statusClass:"2xx"})}catch(u){throw this.reportAccountSnapshotFailure(u,s?.telemetryMode??"blocking"),u}}async createSessionIntent(e,t,n,s){if(!t)throw new C("createSessionIntent requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let i=n,o=i.paymentMethodType,a=typeof o=="string"&&o.trim().toLowerCase()==="card",l=typeof o=="string"&&o.length>0&&!a&&(typeof i.paymentMethodId=="string"||i.paymentMethodId===null),c=i.provider==="stripe"&&(i.paymentMethodCategory==="wallet"||i.paymentMethodCategory==="apm")&&(i.intentKind==="payment"||i.intentKind==="setup"),u=i.provider==="paypal"&&i.paymentMethodCategory==="wallet"&&i.paymentMethodId===null&&(i.paymentMethodType==="paypal"&&i.intentKind==="payment"||i.paymentMethodType===X&&(i.intentKind==="payment"||i.intentKind==="setup"));if(!l||!c&&!u)throw new C("Only wallet, APM, and PayPal session intents are supported.","validation_error",{code:"InvalidSessionIntentRequest"});let h=i.authorizationAttemptId;if(h!==void 0&&!Ee(h))throw new C("authorizationAttemptId must be a v4 UUID identifying one buyer authorization attempt.","validation_error",{code:"InvalidAuthorizationAttemptId",param:"authorizationAttemptId"});let d=Ee(h)?h:Et();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,[Ae]:s?.idempotencyKey||d},y=!1;try{let f=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents`,{method:"POST",headers:m,body:JSON.stringify({...n,authorizationAttemptId:d}),signal:s?.signal});if(!f.ok){y=!0;let $=await A(f,"Failed to create checkout intent"),Ze=F($,"PAYMENT_PROCESSING_FAILED");throw Ue($.statusCode)?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"intent_create",statusClass:"4xx"}):this.directTelemetry?.error({...Ze,stage:"processing",requestCategory:"intent_create"}),$}let v=await f.json();if(f.status===202&&q(v)&&v.type==="checkout_processing")return y=!0,await this.settleProcessingSessionIntent(v,f,e,t,n);let T=v.data;if(!T||typeof T!="object")throw new C("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});let p=T,oe=p.paymentMethodType,We=(p.paymentMethodCategory==="wallet"||p.paymentMethodCategory==="apm")&&typeof oe=="string"&&oe.trim().toLowerCase()!=="card"&&(typeof p.paymentMethodId=="string"||p.paymentMethodId===null)&&typeof p.providerObjectId=="string",Qe=p.provider==="stripe"&&(p.intentKind==="payment"||p.intentKind==="setup")&&typeof p.clientSecret=="string",Je=p.provider==="paypal"&&p.paymentMethodCategory==="wallet"&&p.paymentMethodId===null&&(p.paymentMethodType==="paypal"&&p.intentKind==="payment"&&(p.providerObjectType==="order"||p.providerObjectType==="subscription")||p.paymentMethodType===X&&p.intentKind==="payment"&&p.providerObjectType==="order"||p.paymentMethodType===X&&p.intentKind==="setup"&&p.providerObjectType==="setup_token")&&p.clientSecret===null,Xe=p.provider===n.provider&&p.paymentMethodCategory===n.paymentMethodCategory&&p.paymentMethodType===n.paymentMethodType&&p.paymentMethodId===n.paymentMethodId&&p.intentKind===n.intentKind;if(!We||!Qe&&!Je||!Xe)throw new C("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});return this.directTelemetry?.log({name:"payment.intent.completed",stage:"processing",requestCategory:"intent_create",statusClass:k(f.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-g),durationMode:"machine",requestCategory:"intent_create",statusClass:k(f.status)}),p}catch(f){throw y||this.reportDirectFailure(f,"PAYMENT_PROCESSING_FAILED","processing","intent_create"),f}}async settleProcessingSessionIntent(e,t,n,s,i){let o=this.toCheckoutProcessingPending(e,t,n);try{return{settled:!0,response:await this.resolveCheckoutProcessing(o,n,{nonce:s,paymentMethodCategory:i.provider==="paypal"?"paypal":i.paymentMethodCategory})}}catch(a){throw a instanceof C&&a.code==="checkout_processing_timeout"?new C(a.message,a.type,{code:a.code,statusCode:202,sessionId:o.sessionId,cause:a}):a}}async reportSessionIntentDecline(e,t,n,s){if(!t)throw new C("reportSessionIntentDecline requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let i=n,o=i.providerDeclineReason,a=i.paymentMethodType,l=i.providerIntentId,c=typeof o=="string"&&/^[a-z0-9][a-z0-9_.:-]{0,63}$/i.test(o)&&!/^(?:pm|pi|seti|tok|src|cus|sess|sk|pk)_/i.test(o),u=typeof a=="string"&&a.length>0&&a.trim().toLowerCase()!=="card"&&c,h=i.provider==="stripe"&&(i.paymentMethodCategory==="wallet"||i.paymentMethodCategory==="apm")&&(l===void 0||typeof l=="string"&&/^pi_[a-z0-9_]{1,252}$/i.test(l)),d=i.provider==="paypal"&&i.paymentMethodCategory==="wallet"&&i.paymentMethodType==="paypal"&&l===void 0;if(!u||!h&&!d)throw new C("Invalid non-card decline classification.","validation_error",{code:"InvalidSessionIntentDeclineRequest"});let g=d?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:o}:{provider:"stripe",paymentMethodCategory:i.paymentMethodCategory,paymentMethodType:i.paymentMethodType,providerDeclineReason:o,...typeof l=="string"?{providerIntentId:l}:{}},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 A(m,"Failed to report checkout decline")}async getPaymentsByEmail(e,t){this.beginDirectTelemetryOperation();let n=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved"});let s=t?.page??1,i=t?.limit??1,o=new URLSearchParams({email:e,page:String(s),limit:String(i),sortField:"createdAt",sortDirection:"DESC"});try{let a=await fetch(`${this.baseUrl}/v1/payments?${o.toString()}`,{method:"GET",signal:t?.signal,keepalive:!0});if(!a.ok)throw Ne(new C("Failed to fetch payments","api_error",{statusCode:a.status}),a);let l=await a.json();return this.directTelemetry?.log({name:"operation.recovery.completed",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),this.directTelemetry?.performance({stage:"recovery",durationMs:Math.max(0,this.telemetryTimestamp()-n),durationMode:"machine",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),l}catch(a){throw this.reportDirectFailure(a,"RECOVERY_FAILED","recovery","other","saved"),a}}async createAndFetchSession(e){if(At(e)){let i=e.account.email?.trim();if(i&&!ke(i))throw new C("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(),n=D(e.timeoutMs??12e3),s={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});try{let i=await this.createAndFetchSessionRequest(e,n.signal,s);return this.adoptDirectTelemetryCheckout(i.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}),i}catch(i){throw this.reportSessionCreateFailure(i,t,s),i}finally{n.clear()}}async createAndFetchSessionRequest(e,t,n){let s=e.products??J(e.items,e.subscriptions);Re({captureMethod:e.captureMethod,products:s});let i=Z(e.currency,e.items,e.subscriptions,s);if(!i)throw new C("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});let o={clientId:e.clientId,checkoutVersion:w,successUrl:e.successUrl,cancelUrl:e.cancelUrl,currency:i,checkoutMode:e.checkoutMode??"full",products:s.map(c=>ne(c,i)),accountData:Ve(e.account),couponCodes:e.couponCodes??[]};e.captureMethod==="manual"&&(o.captureMethod=e.captureMethod),e.tokenizedData&&(o.tokenizedData=e.tokenizedData),Be(o,e);let a=await this.postCheckoutSessionCreate(o,e,t,n),l=!1;try{let c=await a.json();if(c.data&&"gateways"in c.data){this.autoCacheDisplayData(c.data.uuid,e);let d=this.mergeCachedDisplayData(c.data),g=this.normalizeRawSession(d);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 u=c.data?.uuid;if(!u)throw new C("No session ID returned","api_error",{code:"InvalidCheckoutSessionResponse"});return this.autoCacheDisplayData(u,e),this.adoptDirectTelemetryCheckout(u),l=!0,{...await this.getUnifiedCheckoutSession(u),autoProcessingError:c.autoProcessingError,autoProcessingAttempted:c.autoProcessingAttempted,autoProcessingPending:c.autoProcessingPending}}catch(c){throw l?c:U(c)}}async postCheckoutSessionCreate(e,t,n,s){let i={"Content-Type":"application/json",[H]:w},o=wt(t.idempotencyKey);o&&(i[Ae]=o),t.checkoutMode==="auto"&&(i[St]=vt);let a,l=!1,c=Gt(t),u=(d,g,m)=>{l||(l=!0,this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:m,attempt:d}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:Math.max(0,this.telemetryTimestamp()-g),durationMode:"machine",requestCategory:"session_create",statusClass:m,attempt:d}))},h=d=>{try{this.telemetryHooks?.onRetry?.("session_create",d),this.directTelemetry?.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:d})}catch{}};for(let d=0;d<3;d++){s.attempt=d;let g=this.telemetryTimestamp();try{c?.onAttempt?.(d)}catch{}try{a=await fetch(`${this.baseUrl}/v1/checkouts/sessions?expand=true`,{method:"POST",headers:i,body:JSON.stringify(e),signal:n})}catch(f){if(s.statusClass=n.aborted||f instanceof Error&&f.name==="AbortError"?"timeout":"network_error",n.aborted||f instanceof Error&&f.name==="AbortError"||d>=2)throw f;let v=d+1;h(v),await B(d,n);continue}let m=k(a.status);if(s.statusClass=m,a.status===204)throw u(d,g,m),new C("Session auto-completed \u2014 payment method already on file","api_error",{code:"session_auto_completed"});if(a.ok){u(d,g,m);break}let y=await A(a,"Failed to create checkout session");if(y.code===Rt&&d<2){h(d+1),await B(d,n);continue}throw u(d,g,m),y}if(!a)throw new TypeError("Checkout-session creation exhausted its retry budget.");return a}async createDetachedSession(e){this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp(),n=D(e.timeoutMs??12e3),s={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let i=e.products??J(e.items,e.subscriptions);try{Re({captureMethod:e.captureMethod,products:i})}catch(v){throw n.clear(),this.reportSessionCreateFailure(v,t,s),v}let o=Z(e.currency,e.items,e.subscriptions,i);if(!o)throw n.clear(),this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),new C("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});try{qe(e,o,i)}catch(v){throw n.clear(),this.reportSessionCreateFailure(v,t,s),v}let a,l,c=!1;try{let v=await this.postCheckoutSessionCreate(Yt(e,o),e,n.signal,s);if(c=!0,l=await v.json(),!l.data||!("gateways"in l.data))throw new C("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(l.data)),l.vault&&a.data.session&&(a.data.session.vault=this.toVaultBlock(l.vault))}catch(v){throw n.clear(),c&&U(v),this.reportSessionCreateFailure(v,t,s),v}let u=a.data.session?.id??l.data.uuid??"",h=a.data.session?.clientSecret??l.data.nonce??"";if(!u||!h){n.clear();let v=new C("Checkout session shell was created without a session id or nonce.","api_error",{code:"InvalidCheckoutSessionResponse"});throw this.reportSessionCreateFailure(v,t,s),v}n.clear(),this.adoptDirectTelemetryCheckout(u),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 d=!e.account.email?.trim(),g=D(e.timeoutMs??12e3),m=this.claimCheckoutSession(u,h,d?Wt(e,o,i):qe(e,o,i),{params:e,startedAt:t,deadline:g,createAttempt:s.attempt}),y=d?void 0:m,f=(v={})=>{if(y!==void 0)return y;let T={...e,account:{...e.account,...v,email:v.email?.trim()||e.account.email?.trim()}};return ke(T.account.email)?(y=m.then(()=>{let p=this.telemetryTimestamp();return this.claimCheckoutSession(u,h,Qt(T.account),{params:T,startedAt:p,deadline:D(e.timeoutMs??12e3),createAttempt:0})}),y.catch(()=>{}),y):Promise.reject(new C("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}))};return m.catch(()=>{}),{shell:a,sessionId:u,nonce:h,claimed:m,claim:f}}async claimCheckoutSession(e,t,n,s){let i=s?.startedAt??this.telemetryTimestamp(),o=this.telemetryTimestamp(),a=s?.deadline??D(12e3),l=JSON.stringify(n),c="unknown",u=0,h=!1;this.directTelemetry?.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"});try{let d;for(u=0;u<3;u++){try{d=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/claim`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":t,[H]:w},body:l,signal:a.signal})}catch(y){let f=a.signal.aborted||y instanceof Error&&y.name==="AbortError";if(c=f?"timeout":"network_error",f||u>=2)throw y;try{this.telemetryHooks?.onRetry?.("session_claim",u+1),this.directTelemetry?.log({name:"operation.retry",stage:"session_claim",requestCategory:"session_claim",attempt:u+1})}catch{}await B(u,a.signal);continue}if(c=k(d.status),d.ok)break;throw await A(d,"Failed to attach checkout session data")}if(!d)throw new TypeError("Checkout-session claim exhausted its retry budget.");h=!0;let g=await d.json();if(!g.data?.gateways)throw new C("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()-o),durationMode:"machine",requestCategory:"session_claim",statusClass:c,attempt:u}),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()-i),durationMode:"machine",requestCategory:"session_create",statusClass:c,attempt:s?.createAttempt??u}),m}catch(d){throw h&&U(d),this.reportSessionCreateFailure(d,o,{attempt:u,statusClass:c},"session_claim"),d}finally{a.clear()}}reportSessionCreateFailure(e,t,n,s="session_create"){if(!(e instanceof C&&e.code==="session_auto_completed"))try{this.telemetryHooks?.onSessionCreateFailure?.(e)}catch{}let i=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:i.statusClass,attempt:n.attempt}),e instanceof C&&e.type==="validation_error"||e instanceof C&&Ue(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 C&&e.code==="session_auto_completed"||this.directTelemetry?.error({...i,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"})}beginThreeDsChallenge(e,t={}){try{return this.directTelemetry?(this.beginDirectTelemetryCheckout(e),this.directTelemetry.beginThreeDsChallenge(t)):void 0}catch{return}}async waitForCheckoutSessionCompletion(e,t){this.beginDirectTelemetryCheckout(e);let n=this.telemetryTimestamp(),s=t?.paymentMethodCategory??"saved";this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:s});let i=t?.timeoutMs??j,o=Date.now()+i,a=new AbortController,l=!1,c,u=setTimeout(()=>{c=setTimeout(()=>{l=!0,a.abort()},xe)},i),h=()=>a.abort(t?.signal?.reason);t?.signal?.aborted?h():t?.signal?.addEventListener("abort",h,{once:!0});let d=this.clampRetryAfterMs(t?.initialDelayMs??Pe),g=0;try{if(t?.statusUrl){let m=await this.waitForCheckoutStatus(e,{initialDelayMs:d,timeoutMs:i,nonce:t.nonce,statusUrl:t.statusUrl,pollAfterAction:t.continueAfterActionRequired,signal:a.signal});if(m){let y=await this.resolveCheckoutSessionStatus(e,m,t.nonce,a.signal,()=>l);return this.reportRecoveryCompleted(n,s,t.challengeAttemptId),y}}for(;;){let m=o-Date.now();if(m<=0)throw b();if(d>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 te(Math.min(d,m),a.signal),Date.now()>=o)throw b()}let y=await this.getUnifiedCheckoutSessionForRecovery(e,t?.nonce,a.signal),f=y.data.session?.status;if(f==="authorized"||f==="complete"||f==="expired")return this.reportRecoveryCompleted(n,s,t?.challengeAttemptId),y;if(Date.now()>=o)throw b();d=this.clampRetryAfterMs(Math.max(d*2,Oe))}}catch(m){let y=l&&ee(m)?b():m;throw this.reportDirectFailure(y,"RECOVERY_FAILED","recovery","session_read",s),y}finally{clearTimeout(u),clearTimeout(c),t?.signal?.removeEventListener("abort",h)}}reportRecoveryCompleted(e,t,n){let s={stage:"recovery",requestCategory:"session_read",paymentMethodCategory:t};if(this.directTelemetry?.log({name:"operation.recovery.completed",...s}),n)try{this.directTelemetry?.beginThreeDsChallenge({attemptId:n}).record("recovery_read_completed",{evidenceBasis:"server_status"})}catch{}this.directTelemetry?.performance({...s,durationMs:Math.max(0,this.telemetryTimestamp()-e),durationMode:"machine"})}async resolveCheckoutSessionStatus(e,t,n,s,i){let o=t.latestTransactionAttempt;if(this.rememberReportedFailure(e,t),o?.result==="DECLINE"){let c=o.code===Me;throw new C(c?Ie:"Payment was declined. Please choose another payment method.","api_error",{code:o.code??o.declineReason??"authorization_declined",statusCode:400})}if(o?.result==="ERROR"||t.status==="voided")throw new C("Payment could not be completed. Please try again.","api_error",{code:o?.code??"payment_processing_error",statusCode:500});let a;try{a=await this.getUnifiedCheckoutSessionForRecovery(e,n,s)}catch(c){if(!i?.()||!ee(c))throw c;a={providers:[],mode:"tokenize",data:{},raw:t}}let l=a.data.session;return l&&o?.result==="SUCCESS"?{...a,data:{...a.data,session:{...l,status:"complete"}}}:l&&o?.result==="AUTHORIZED"?{...a,data:{...a.data,session:{...l,status:"authorized",paymentId:t.paymentId??void 0,authorizationExpiresAt:t.authorizationExpiresAt??void 0}}}:l&&t.status==="completed"?{...a,data:{...a.data,session:{...l,status:"complete"}}}:l&&t.status==="authorized"?{...a,data:{...a.data,session:{...l,status:"authorized",paymentId:t.paymentId??void 0,authorizationExpiresAt:t.authorizationExpiresAt??void 0}}}:l&&t.status==="expired"?{...a,data:{...a.data,session:{...l,status:"expired"}}}:o?.result!=="ACTION_REQUIRED"?a:o.gateway==="paypal"&&o.providerIntentId?{...a,autoProcessingError:{type:"paypal_direct_required",message:"PayPal authorization required",orderId:o.providerIntentId,checkoutMethod:"paypal"}}:o.nextActionRedirectUrl?{...a,autoProcessingError:{type:"3ds_required",message:"Additional authentication is required.",nextActionRedirectUrl:o.nextActionRedirectUrl}}:a}async waitForCheckoutStatus(e,t){let n=t.timeoutMs??j,s=Date.now()+n,i=this.clampRetryAfterMs(t.initialDelayMs);for(;;){let o=s-Date.now();if(o<=0||i>0&&(await te(Math.min(i,o),t.signal),Date.now()>=s))throw b();let a=s-Date.now();if(a<=0)throw b();let l=new AbortController,c,u=t.signal?new Promise((T,p)=>{c=p}):null,h=()=>{l.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 d,g=t.signal?null:new Promise((T,p)=>{d=setTimeout(()=>{p(b()),l.abort()},a+xe)}),m;try{let T=this.fetchCheckoutStatus(e,t.nonce,t.statusUrl,l.signal);m=await Promise.race([T,g,u].filter(p=>p!==null))}finally{d!==void 0&&clearTimeout(d),t.signal?.removeEventListener("abort",h)}if(!m)return null;let y=De(m.latestTransactionAttempt)&&!this.isOwnFailedAttempt(e,m,t.submittedIntentId);if(m.status==="completed"||m.status==="authorized"||m.status==="expired"||m.status==="voided")return y?{...m,latestTransactionAttempt:null}:m;let f=m.latestTransactionAttempt?.result,v=t.pollAfterAction===!0&&f==="ACTION_REQUIRED";if(!y&&f!==void 0&&f!=="PENDING"&&!v)return m;i=this.clampRetryAfterMs(Math.max(i*2,Oe))}}isOwnFailedAttempt(e,t,n){let s=t.latestTransactionAttempt?.providerIntentId??null;return n!==void 0?s===n:s===null?!0:!Ft(t.uuid||e,s)}rememberReportedFailure(e,t){let n=t.latestTransactionAttempt;!De(n)||!n.providerIntentId||Ut(t.uuid||e,n.providerIntentId)}async fetchCheckoutStatus(e,t,n,s){let i=`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/status`,o=i;if(n)try{let u=new URL(n,`${this.baseUrl}/`),h=new URL(i);u.origin===h.origin&&(o=u.toString())}catch{}let a={[H]:w};t&&(a["x-checkout-session-token"]=t);let l=await K(o,{headers:a,signal:s});if(l.status===404||l.status===405)return null;if(!l.ok)throw await A(l,"Failed to get checkout session status");let c=await l.json();return q(c.data)&&"latestTransactionAttempt"in c.data?c.data:null}normalizeRawSession(e){let t=e.gateways??{},n=[],s={session:this.toCheckoutSession(e)},i=t.stripe;if(i?.publishableKey){n.push("stripe");let l=[e.stripeClientSecret,i.stripeClientSecret].find(c=>typeof c=="string"&&c.length>0);s.stripe={clientSecret:l??"",publishableKey:i.publishableKey??void 0,paypalPublishableKey:i.paypalPublishableKey??void 0,environment:i.environment,enabledPaymentMethods:Array.isArray(i.enabledPaymentMethods)?i.enabledPaymentMethods.filter(c=>typeof c=="string"):void 0}}let o=t.paypal;return o?.publishableKey&&(n.push("paypal"),s.paypal={publishableKey:o.publishableKey,environment:o.environment,providerObjectType:o.providerObjectType,approvalPresentation:o.approvalPresentation}),{providers:n,mode:"tokenize",...e.checkoutMetadata===void 0?{}:{checkoutMetadata:e.checkoutMetadata},data:s,raw:{data:e}}}toCheckoutSession(e){let t=e.products??[],n=typeof e.totalAmount=="number"&&Number.isFinite(e.totalAmount),s=t.reduce((c,u)=>c+(u.overrideAmount??u.totalAmount??0),0),i=n?e.totalAmount:s,o=Math.round(i*100),a=e.currency??t[0]?.currency??"USD",l="payment";return e.checkoutMode==="setup"?l="setup":t.some(c=>c.type==="subscription")&&(l="subscription"),{id:e.uuid,clientSecret:e.nonce,mode:l,status:this.toCheckoutSessionStatus(e.status),amount:o,currency:a,captureMethod:e.captureMethod,paymentId:e.paymentId,authorizationExpiresAt:e.authorizationExpiresAt,failureOutcome:we(e.outcome)??we(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}:{},...Mt(e.futureUse)?{futureUse:e.futureUse}:{},...Array.isArray(e.futureUseUnsupported)?{futureUseUnsupported:e.futureUseUnsupported.filter(It)}:{},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=Ht(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,n){if(e.status!==202)return e;let s=await e.json().catch(()=>null),i=this.toCheckoutProcessingPending(s,e,t);return this.resolveCheckoutProcessing(i,t,n)}async resolveCheckoutProcessing(e,t,n){let s=n?.pollTimeoutMs??j,i=Date.now()+s;if(e.statusUrl){let a=await this.waitForCheckoutStatus(e.sessionId,{initialDelayMs:e.retryAfterMs,timeoutMs:s,nonce:n?.nonce,statusUrl:e.statusUrl,submittedIntentId:n?.submittedIntentId});if(a)return this.toProcessResponseFromStatus(a,t,n?.nonce)}let o=await this.waitForCheckoutSessionCompletion(e.sessionId,{initialDelayMs:e.retryAfterMs,timeoutMs:i-Date.now(),nonce:n?.nonce,paymentMethodCategory:n?.paymentMethodCategory});return this.toProcessResponseFromSession(o,t)}async toProcessResponseFromStatus(e,t,n){let s=e.latestTransactionAttempt?.result,i={[Pt]:Ot},o={"Content-Type":"application/json",...i};if(e.status==="completed"||s==="SUCCESS")return new Response(null,{status:204,statusText:"No Content",headers:i});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:o});if(e.status==="expired"){let a=await this.resolveCheckoutSessionStatus(t,e,n);return this.toProcessResponseFromSession(a,t)}if(this.rememberReportedFailure(t,e),s==="DECLINE"){let a=e.latestTransactionAttempt,l=a?.code===Me,c=a?.declineReason??void 0;return new Response(JSON.stringify({type:c??"authorization_declined",message:l?Ie:"Payment was declined. Please choose another payment method.",code:a?.code??c??"authorization_declined",...c?{declineCode:c}:{}}),{status:400,headers:o})}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:o});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:o});if(s==="ERROR"||e.status==="voided")return new Response(JSON.stringify({type:"unknown",code:e.latestTransactionAttempt?.code??"payment_processing_error",message:Dt(e)??"Payment could not be completed. Please try again."}),{status:500,headers:o});throw b()}async reconcileProcessPayment(e,t){let n=t?.pollTimeoutMs??j,s=Date.now()+n,i=null;try{i=await this.waitForCheckoutStatus(e,{initialDelayMs:0,timeoutMs:n,nonce:t?.nonce,submittedIntentId:t?.submittedIntentId})}catch(l){if(this.reportDirectFailure(l,"RECOVERY_FAILED","recovery","session_read",t?.paymentMethodCategory??"saved"),l instanceof C&&l.code==="checkout_processing_timeout")throw l}if(i)return this.toProcessResponseFromStatus(i,e,t?.nonce);let o=s-Date.now();if(o<=0)throw b();let a=await this.waitForCheckoutSessionCompletion(e,{initialDelayMs:0,timeoutMs:o,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 n=e.data.session;return new Response(JSON.stringify({status:"authorized",paymentId:n.paymentId,sessionId:n.id||t,authorizationExpiresAt:n.authorizationExpiresAt}),{status:200,headers:{"Content-Type":"application/json"}})}if(e.data.session?.status==="expired"){let n=e.data.session.failureOutcome==="authorization_expired"||e.data.session.captureMethod==="manual";throw new C(n?"Authorization has expired.":"Checkout session has expired.","api_error",{code:n?"authorization_expired":"checkout_session_expired"})}throw b()}toCheckoutProcessingPending(e,t,n){let s=t.headers.get("Retry-After"),i=s===null||s.trim()===""?void 0:Number(s),o=i!==void 0&&Number.isFinite(i)?i*1e3:void 0;return{type:"checkout_processing",sessionId:E(e,"sessionId")??n,retryAfterMs:this.clampRetryAfterMs(Bt(e,"retryAfterMs")??o??Pe),statusUrl:E(e,"statusUrl"),sessionUrl:E(e,"sessionUrl")}}clampRetryAfterMs(e){return Math.max(0,Math.min(e,Lt))}autoCacheDisplayData(e,t){if(!e)return;let n=t.products??J(t.items,t.subscriptions);if(n.length===0&&!t.currency)return;let s=t.products!==void 0,i=Z(t.currency,s?void 0:t.items,s?void 0:t.subscriptions,n);W(e,{currency:i??void 0,products:n.map(o=>({code:o.code??o.providerItemId??o.providerPlanId,type:o.type,name:o.name??o.itemName??o.providerItemName??o.subscriptionName??o.providerPlanName??null,totalAmount:o.totalAmount,overrideAmount:o.overrideAmount,currency:o.currency??i??void 0}))})}mergeCachedDisplayData(e){let t=ae(e.uuid),n=new Map,s=o=>o?`code:${o}`:void 0;for(let o of t?.products??[]){let a=s(o.code);a&&n.set(a,o)}let i=(e.products??[]).map(o=>{let a=s(o.code),l=a?n.get(a):void 0;return{...o,name:o.name??l?.name??null,totalAmount:o.totalAmount??l?.totalAmount,overrideAmount:o.overrideAmount??l?.overrideAmount,currency:o.currency??l?.currency}});return{...e,currency:e.currency??t?.currency,products:i}}};I.activeVaultCaptureRequests=new Map;var re=I;function Dr(r,e){let t=re;return new t(r,e)}import{buildTelemetryErrorEvent as Jt,buildTelemetryLogEvent as Xt,buildTelemetryTerminalEvent as Ke,FloPayError as ze,resolveBillingApiUrl as He,SDK_VERSION as je,THREE_DS_CHALLENGE_WINDOW_MS as Zt}from"@flopay/shared";var er=4,ie="flopay-vault",tr=3e4,rr=Zt+tr,nr="Card authentication timed out.",Ge={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 sr(r){return r.class==="lifecycle"?r.name:r.class==="technical_error"?r.code:r.class==="expected_outcome"?r.outcome:"sdk.performance"}function P(r){let e={class:r.class,stage:r.stage};"code"in r&&(e.code=r.code),"provider"in r&&r.provider&&(e.provider=r.provider),"paymentMethodCategory"in r&&r.paymentMethodCategory&&(e.paymentMethodCategory=r.paymentMethodCategory),"outcome"in r&&(e.outcome=r.outcome),"durationMs"in r&&r.durationMs!==void 0&&(e.durationMs=r.durationMs),"durationMode"in r&&r.durationMode&&(e.durationMode=r.durationMode);try{globalThis.Sentry?.addBreadcrumb?.({category:"flopay.telemetry",level:r.class==="technical_error"?"error":"info",message:sr(r),data:e})}catch{}}function L(r,e){return Xt({eventId:"11111111-1111-4111-8111-111111111111",name:r,stage:e,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}var ir=new Set(["authorization_declined","authentication_required","authorization_expired","capture_failed"]);function or(r){return typeof r=="string"&&ir.has(r)?r:"unknown"}var ar=new Set(["verification_failed","verification_expired"]);function lr(r){return r==null?!0:typeof r=="string"&&ar.has(r)}var cr="vault_mount";function ur(r){return r.failureStage===cr}function $e(r,e){return r&&!ur(e)?{errorCode:"VAULT_SUBMIT_FAILED",stage:"vault_submit",failureCategory:"provider_runtime",reason:or(e.failureOutcome)}:{errorCode:"VAULT_LOAD_FAILED",stage:"vault_mount",failureCategory:"provider_runtime"}}function Ye(r,e,t="checkout"){return t==="card_setup"?r.type==="decline"?"card_setup_declined":"card_setup_succeeded":r.type==="decline"?"payment_declined":r.outcome==="authorized"||e==="manual"?"payment_authorized":"payment_succeeded"}function dr(r,e,t,n="checkout"){let{type:s}=r;if(s==="complete"||s==="decline")return Ke({eventId:"22222222-2222-4222-8222-222222222222",outcome:Ye(r,t,n),sequence:0,provider:"pcivault",paymentMethodCategory:"card"});if(s==="error"){let a=$e(e,r);return Jt({eventId:"33333333-3333-4333-8333-333333333333",...a,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}let[i,o]=Ge[s];return L(i,o)}function mr(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===ie&&(e.type==="ready"||e.type==="submitting"||e.type==="blocked"||e.type==="complete"||e.type==="decline"||e.type==="error"||e.type==="action_required")}function hr(r){if(typeof r!="object"||r===null)return;let e=r;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 pr(r){if(typeof r!="object"||r===null)return;let e=r,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 yr(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===ie&&e.type==="validation"&&Array.isArray(e.messages)}function gr(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===ie&&e.type==="resize"&&typeof e.height=="number"&&Number.isFinite(e.height)}var se=class{constructor(e={},t){this.provider="pcivault";this.container=null;this.messageHandler=null;this.actionOverlay=null;this.threeDsReturnHandler=null;this.actionChallenge=null;this.lastChallengeTelemetry=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:He(e.billingApiUrl),sdkVersion:je}):void 0)}async mount(e,t){this.ownsTelemetryReporter&&!this.telemetryReporter&&(this.telemetryReporter=new R({billingApiUrl:He(this.config.billingApiUrl),sdkVersion:je}));let n=this.telemetryReporter;if(this.config.operation==="card_setup"&&n&&this.setupTelemetryReporter!==n){this.setupTelemetryReporter=n;try{n.beginCheckout({checkoutMode:"setup"})}catch{}}if(this.mountStartedAt=this.telemetryReporter?.now?.()??_(),this.vaultReadyReported=!1,this.submissionStarted=!1,this.submissionStartedAt=null,typeof window>"u"||typeof document>"u")throw this.reportVaultLoadFailure(),new ze("The vault card form is only available in the browser.","api_error",{code:"card_capture_no_window"});if(!t?.html?.trim())throw this.reportVaultLoadFailure(),new ze("No vault capture widget HTML was provided to mount the secure card form.","api_error",{code:"card_capture_no_widget_html"});this.container=e,this.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(),P(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?.()??_())-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 n=this.listeners.get(e);return n||(n=new Set,this.listeners.set(e,n)),n.add(t),()=>{this.listeners.get(e)?.delete(t)}}unmount(){if(this.actionChallenge){let{telemetry:e}=this.actionChallenge;e.record("abort_observed",{reason:"component_unmount",evidenceBasis:"signal_reason"}),e.terminal("abort",{reason:"component_unmount",evidenceBasis:"signal_reason"})}this.lastChallengeTelemetry=null,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 n=Array.from(e.querySelectorAll("script"));for(let s of n){let i=document.createElement("script");for(let o of Array.from(s.attributes))i.setAttribute(o.name,o.value);i.text=s.text,s.replaceWith(i)}}attachMessageListener(){if(this.messageHandler)return;let e=t=>{if(this.expectedOrigin&&t.origin!==this.expectedOrigin)return;let n=t.data;if(gr(n)){if(this.messageToken&&n.messageToken!==this.messageToken)return;this.applyHeight(n.height);return}if(yr(n)){if(this.messageToken&&n.messageToken!==this.messageToken)return;let c=n.messages.filter(u=>typeof u=="string"&&u.trim()).join(" ");this.emit("validation",{sessionId:this.config.sessionId,message:c||void 0});return}if(!mr(n)||this.messageToken&&n.messageToken!==this.messageToken)return;let s=this.config.sessionId,i=typeof n.sessionId=="string"?n.sessionId:void 0;if(s&&i&&i!==s||(n.type==="complete"||n.type==="decline")&&s&&i!==s)return;let o=pr(n.paymentMethod),a=hr(n.vaultOutcome),l={...n.sessionId??this.config.sessionId?{sessionId:n.sessionId??this.config.sessionId}:{},...n.outcome?{outcome:n.outcome}:{},...n.paymentId?{paymentId:n.paymentId}:{},...n.authorizationExpiresAt?{authorizationExpiresAt:n.authorizationExpiresAt}:{},...n.failureOutcome?{failureOutcome:n.failureOutcome}:{},...n.intentId?{intentId:n.intentId}:{},...n.declineReason?{declineReason:n.declineReason}:{},...n.message?{message:n.message}:{},...a?{vaultOutcome:a}:{},...o?{paymentMethod:o}:{}};n.type==="submitting"&&(this.submissionStarted=!0,this.submissionStartedAt=this.telemetryReporter?.now?.()??_()),this.isVerificationStateError(n)?(P(L("operation.state_transition","vault_mount")),this.telemetryReporter?.log({name:"operation.state_transition",stage:"vault_mount",provider:"pcivault",paymentMethodCategory:"card"})):(P(dr(n,this.submissionStarted,this.config.captureMethod,this.config.operation)),this.reportOutcome(n)),n.type==="ready"&&(this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),this.postSubmitLabel()),n.type==="action_required"&&n.nextActionRedirectUrl&&this.showActionRequiredOverlay(n.nextActionRedirectUrl),(n.type==="complete"||n.type==="decline"||n.type==="error"||n.type==="submitting")&&(this.endActionChallengeFromWidget(n.type),this.hideActionRequiredOverlay()),n.type!=="action_required"&&this.emit(n.type,l)};this.messageHandler=e,window.addEventListener("message",e)}isVerificationStateError(e){return e.type==="error"&&this.verificationRequired&&!this.submissionStarted&&lr(e.failureOutcome)}reportOutcome(e){let t=this.telemetryReporter;if(!t)return;let{type:n}=e;if(n==="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"})),n==="complete"||n==="decline"){t.log({name:"vault.terminal",stage:"completion",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:Ye(e,this.config.captureMethod,this.config.operation),provider:"pcivault",paymentMethodCategory:"card"});return}if(n==="error"){let o=$e(this.submissionStarted,e);t.log({name:"vault.terminal",stage:o.stage,provider:"pcivault",paymentMethodCategory:"card"}),t.error({...o,provider:"pcivault",paymentMethodCategory:"card"});return}if(n==="action_required"){t.log({name:"vault.action.required",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"}),t.log({name:"vault.three_ds.handoff",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"});let o=this.submissionStartedAt;this.submissionStartedAt=null,o!==null&&t.performance({stage:"three_ds_handoff",durationMs:Math.max(0,t.now()-o),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:"action_required",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"});return}let[s,i]=Ge[n];t.log({name:s,stage:i,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:n,expectedOrigin:s}=this;e===void 0||!t||!n||!s||this.postToHostedWindow({source:"flopay-vault-host",type:"submitLabel",sessionId:t,messageToken:n,label:e},s)}hostedWindow(){return this.container?.querySelector("iframe")?.contentWindow??null}postToHostedWindow(e,t){let n=this.hostedWindow();if(n)try{n.postMessage(e,t)}catch{}}directiveTargetOrigin(){return this.expectedOrigin??"*"}emit(e,t){for(let n of this.listeners.get(e)??[])n(t)}showActionRequiredOverlay(e){if(typeof document>"u")return;if(this.actionOverlay){let m=this.actionOverlay.querySelector("iframe");m instanceof HTMLIFrameElement&&m.src!==e&&(m.src=e),this.armActionRequiredTimeout();return}this.actionOverlayPreviousFocus=document.activeElement instanceof HTMLElement?document.activeElement:null;let t=pe(this.beginActionChallengeAttempt()),n=fe(e),s=!1,i=m=>{if(s)return;let y=ge(m,n);y&&(s=!0,t.record("policy_violation",{reason:y,evidenceBasis:"parent_csp_event"}))},o=()=>{t.record("pagehide_observed",{evidenceBasis:"page_lifecycle_event"})},a={telemetry:t,loaded:!1,detach:()=>{document.removeEventListener("securitypolicyviolation",i),window.removeEventListener("pagehide",o)}};this.actionChallenge=a,this.lastChallengeTelemetry=t,t.record("handoff_planned"),Q(e)==="invalid"&&t.record("action_invalid",{reason:"invalid_url"}),document.addEventListener("securitypolicyviolation",i),window.addEventListener("pagehide",o);let l=document.createElement("div");l.setAttribute("data-flopay-action-required","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 c=document.createElement("iframe");c.setAttribute("title","Card authentication"),c.setAttribute("allow","payment"),c.tabIndex=0,c.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(";"),c.addEventListener("load",()=>{a.loaded||(a.loaded=!0,t.record("iframe_load",{evidenceBasis:"iframe_load_event"}))}),c.src=e,l.appendChild(c);let u=document.createElement("button");u.type="button",u.setAttribute("aria-label","Close card authentication"),u.textContent="\xD7",u.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(";"),u.addEventListener("click",()=>this.abandonActionRequiredOverlay()),l.appendChild(u),l.addEventListener("click",m=>{m.target===l&&this.abandonActionRequiredOverlay()});let h=0,d=m=>{let y=m.data,f=!!y&&typeof y=="object"&&y.source==="flopay-vault-3ds-return";if(m.source!==c.contentWindow){f&&h<er&&(h+=1,t.record("return_rejected",{reason:"untrusted_source",evidenceBasis:"message_origin_check"}));return}f&&(t.record("trusted_return",{evidenceBasis:"message_origin_check"}),t.terminal("trusted_return",{evidenceBasis:"message_origin_check"}),P(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",d),this.threeDsReturnHandler=d,t.record("render_attempted");try{document.body.appendChild(l)}catch(m){throw t.record("render_failed"),this.hideActionRequiredOverlay(),this.actionOverlayPreviousFocus=null,m}t.record("container_attached"),t.record("navigation_assigned");let g=ye(l);g&&t.record("container_visibility",{reason:g,evidenceBasis:"parent_computed_style"}),this.actionOverlay=l,c.focus(),this.armActionRequiredTimeout(),P(L("vault.three_ds.handoff","three_ds_handoff"))}armActionRequiredTimeout(){this.actionOverlayTimer&&clearTimeout(this.actionOverlayTimer),this.actionOverlayTimer=setTimeout(()=>{this.actionOverlayTimer=null,this.actionOverlay&&this.timeOutActionRequiredOverlay()},rr)}reportChallengeAbandoned(){P(Ke({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(){if(this.actionChallenge){let{telemetry:e,loaded:t}=this.actionChallenge;t||e.record("load_unconfirmed",{evidenceBasis:"no_load_signal"}),e.record("timer_expired",{reason:"window_elapsed",evidenceBasis:"timer"}),e.terminal("timer",{reason:"window_elapsed",evidenceBasis:"timer"})}this.reportChallengeAbandoned(),this.hideActionRequiredOverlay(),this.emit("error",{...this.config.sessionId?{sessionId:this.config.sessionId}:{},message:nr})}abandonActionRequiredOverlay(){if(this.actionOverlay){if(this.actionChallenge){let{telemetry:e}=this.actionChallenge;e.record("cancel_requested",{reason:"buyer_cancel",evidenceBasis:"signal_reason"}),e.terminal("cancel",{reason:"buyer_cancel",evidenceBasis:"signal_reason"})}this.reportChallengeAbandoned(),this.hideActionRequiredOverlay(),this.emit("challenge_dismissed",{...this.config.sessionId?{sessionId:this.config.sessionId}:{}})}}beginActionChallengeAttempt(){try{return this.telemetryReporter?.beginThreeDsChallenge?.()}catch{return}}endActionChallengeFromWidget(e){let t=this.actionChallenge,n=t?.telemetry??this.lastChallengeTelemetry;if(this.lastChallengeTelemetry=null,!!n){if(e==="submitting"){if(!t)return;n.record("abort_observed",{reason:"unspecified",evidenceBasis:"signal_reason"}),n.terminal("abort",{reason:"unspecified",evidenceBasis:"signal_reason"});return}t&&n.terminal("status_poll",{evidenceBasis:"server_status"}),e==="complete"&&n.reconcile("succeeded"),e==="decline"&&n.reconcile("declined")}}hideActionRequiredOverlay(){if(this.actionChallenge){let t=this.actionChallenge;this.actionChallenge=null;try{t.detach()}catch{}t.telemetry.record("teardown")}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 n=Math.max(0,Math.min(Math.ceil(e),2e3));t.style.height=`${n}px`}};function Ur(r,e){let t=se;return new t(r,{reporter:e})}export{ce as a,ue as b,D as c,B as d,W as e,ae as f,le as g,pe as h,Q as i,br as j,ye as k,ge as l,fe as m,_ as n,R as o,Kt as p,re as q,Dr as r,se as s,Ur as t};