@flopay/js 1.19.1 → 1.20.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.
@@ -0,0 +1 @@
1
+ var at="flopay_session_display:";var B=new Map;function z(n){return`${at}${n}`}function X(){if(typeof window>"u")return null;try{return window.sessionStorage}catch{return null}}function Z(n,e,t){if(!n)return;let r=t?.ttlMs??36e5,i={data:e,expiresAt:Date.now()+r},s=X();if(s)try{s.setItem(z(n),JSON.stringify(i));return}catch{}B.set(n,i)}function ue(n){if(!n)return null;let e=X();if(e)try{let r=e.getItem(z(n));if(r){let i=JSON.parse(r);if(i&&typeof i.expiresAt=="number"&&i.expiresAt>Date.now())return i.data;e.removeItem(z(n))}}catch{}let t=B.get(n);if(t){if(t.expiresAt>Date.now())return t.data;B.delete(n)}return null}function he(n){if(!n)return;B.delete(n);let e=X();if(e)try{e.removeItem(z(n))}catch{}}import{ASYNC_AUTO_CHECKOUT_CAPABILITY as wt,assertCaptureMethodEligible as ke,buildProductPayload as se,CHECKOUT_PROCESSING_TIMEOUT_MESSAGE as Et,CHECKOUT_SESSION_BUYER_EMAIL_REQUIRED as kt,classifyPaymentRejection as Mt,classifyTelemetryFailure as x,FLO_SDK_CAPABILITIES_HEADER as Me,FLO_SDK_VERSION_HEADER as U,FloPayError as f,foldIntoProducts as te,IDEMPOTENCY_IN_PROGRESS_CODE as It,IDEMPOTENCY_KEY_HEADER as Ie,isCardHolderNamePlaceholder as oe,isDetachedSessionEligible as Dt,isUuidV4 as De,isValidEmail as Pe,markSessionResponseReceived as L,normalizeCheckoutFailureOutcome as Fe,normalizePaymentMethodLayout as Pt,PAYPAL_VAULTED_PAYMENT_METHOD_TYPE as re,randomUuidV4 as Ft,readTelemetryHttpDiagnostics as Ot,resolveIdempotencyKey as xt,resolveSessionCurrency as ne,SDK_VERSION as E,STORED_PAYMENT_METHOD_UNSUPPORTED_CODE as Oe,STORED_PAYMENT_METHOD_UNSUPPORTED_MESSAGE as xe,telemetryStatusClass as M,withTelemetryHttpDiagnostics as Ge}from"@flopay/shared";function me(n){return typeof n=="string"&&n.trim()?n:void 0}function pe(n){if(typeof n=="string")return n.trim()?n:void 0;if(Array.isArray(n))return n.filter(t=>typeof t=="string"&&t.trim().length>0).join("; ")||void 0}function D(n=12e3){let e=Number.isFinite(n)&&n>=0?n:12e3,t=new AbortController,r=setTimeout(()=>t.abort(),e);return{signal:t.signal,clear:()=>clearTimeout(r)}}function lt(){return Object.assign(new Error("The operation was aborted."),{name:"AbortError"})}function H(n,e){let t=150*2**n,r=Math.round(t*(.75+Math.random()*.5));return new Promise((i,s)=>{let o,a=()=>e.removeEventListener("abort",l),l=()=>{o!==void 0&&clearTimeout(o),a(),s(lt())};if(e.aborted){l();return}o=setTimeout(()=>{a(),i()},r),e.addEventListener("abort",l,{once:!0})})}import{buildTelemetryErrorEvent as _e,buildTelemetryLogEvent as Re,buildTelemetryPerformanceEvent as pt,buildTelemetryTerminalEvent as yt,serializeTelemetryBatch as gt,TELEMETRY_MAX_BATCH_BYTES as ft}from"@flopay/shared";import{isThreeDsChallengeAttemptId as ge}from"@flopay/shared";var dt=32,ye=Symbol.for("@flopay/js.three-ds-challenge.attempts.v1");function ct(){let n=globalThis,e=n[ye];if(e instanceof Map)return e;let t=new Map;try{Object.defineProperty(n,ye,{configurable:!0,enumerable:!1,writable:!1,value:t})}catch{}return t}function ut(n,e){let t=ct(),r=t.get(n);if(r)return r;for(;t.size>=dt;){let s=t.keys().next();if(s.done)break;t.delete(s.value)}let i={nextSequence:0,startedAt:e,terminated:!1,reconciled:new Set,provider:"unknown"};return t.set(n,i),i}var ht=new Set(["pagehide_observed","cancel_requested","abort_observed","browser_terminal"]),mt=new Set(["teardown","recovery_read_completed","provider_reconciled"]);function fe(n,e={}){let t=ge(e.attemptId)?e.attemptId.toLowerCase():n.newAttemptId(),r=()=>{try{let a=n.now();return Number.isFinite(a)?a:0}catch{return 0}},i=ut(t,r());(e.provider==="stripe"||e.provider==="worldpay")&&(i.provider=e.provider);let s=i.provider,o=(a,l)=>{if(i.terminated&&!mt.has(a))return;let d={attemptId:t,phase:a,attemptSequence:i.nextSequence,elapsedMs:Math.max(0,r()-i.startedAt),provider:s};i.nextSequence+=1,l.reason!==void 0&&(d.reason=l.reason),l.evidenceBasis!==void 0&&(d.evidenceBasis=l.evidenceBasis),l.terminalSource!==void 0&&(d.terminalSource=l.terminalSource),l.providerOutcome!==void 0&&(d.providerOutcome=l.providerOutcome);try{n.emit(d,ht.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={}){i.terminated||(o("browser_terminal",{terminalSource:a,reason:l.reason,evidenceBasis:l.evidenceBasis}),i.terminated=!0)},reconcile(a){i.reconciled.has(a)||(i.reconciled.add(a),o("provider_reconciled",{providerOutcome:a,evidenceBasis:"provider_fact"}))}}}function ve(n){let e=null;try{e=ge(n?.attemptId)?n?.attemptId??null:null}catch{e=null}return{attemptId:e,record(t,r){try{n?.record(t,r)}catch{}},terminal(t,r){try{n?.terminal(t,r)}catch{}},reconcile(t){try{n?.reconcile(t)}catch{}}}}function ee(n){if(typeof n!="string"||n.trim()==="")return"missing";try{let e=new URL(n);return e.protocol==="https:"||e.protocol==="http:"?"valid":"invalid"}catch{return"invalid"}}function jr(n){return n==="buyer_cancel"||n==="component_unmount"||n==="navigation"?n:"unspecified"}function Ce(n){try{if(typeof window>"u"||typeof window.getComputedStyle!="function")return null;for(let e=n;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 Te(n,e){if(!e)return null;try{let t=n,r=String(t.effectiveDirective||t.violatedDirective||"").trim().split(/\s+/)[0],i=null;return r==="frame-src"&&(i="frame_src"),r==="child-src"&&(i="child_src"),!i||typeof t.blockedURI!="string"?null:new URL(t.blockedURI).origin===e?i:null}catch{return null}}function be(n){try{return ee(n)==="valid"?new URL(n).origin:null}catch{return null}}var vt="/v1/sdk-telemetry/events",j=16,Se=64,Ct=1500,Ae=1e3,Tt=64,bt="00000000-0000-4000-8000-000000000000",_t={technical_error:8,lifecycle:32,expected_outcome:32,performance:24},Rt=48;function A(){try{return globalThis.crypto.randomUUID()}catch{let n=new Uint8Array(16);try{globalThis.crypto.getRandomValues(n)}catch{for(let t=0;t<n.length;t+=1)n[t]=Math.floor(Math.random()*256)}n[6]=(n[6]??0)&15|64,n[8]=(n[8]??0)&63|128;let e=[...n].map(t=>t.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}}function St(n){try{return new TextEncoder().encode(n).byteLength}catch{return n.length}}function At(n){return JSON.stringify([n.code,n.failureCategory,n.reason,n.stage,n.provider,n.attempt,n.statusClass,n.requestCategory,n.paymentMethodCategory,n.walletType,n.operationOutcome,n.checkoutMode,n.layout,n.inAppBrowser,n.appFamily,n.popupCapability,n.presentationMode,n.terminalReason])}function _(){return globalThis.performance?.now()??0}var w=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(/\/+$/,"")}${vt}`,this.sdkPackage=e.sdkPackage??"@flopay/js",this.sdkVersion=e.sdkVersion,this.correlationId=A(),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(Re({...this.checkoutContext,...e,eventId:A(),sequence:this.sequence++}))}error(e){if(this.notify({...e,class:"technical_error"}),!this.canCollect())return;let t=_e({...this.checkoutContext,...e,eventId:bt,sequence:0}),r=At(t),i=this.now();this.pruneReportedFailures(i);let s=this.reportedFailures.get(r);if(s!==void 0&&i>=s&&i-s<Ae){this.log({name:"operation.deduplicated",stage:e.stage,provider:e.provider,paymentMethodCategory:e.paymentMethodCategory,attempt:e.attempt,inAppBrowser:e.inAppBrowser,appFamily:e.appFamily,popupCapability:e.popupCapability,presentationMode:e.presentationMode,terminalReason:e.terminalReason});return}this.rememberReportedFailure(r,i),this.enqueue(_e({...this.checkoutContext,...e,eventId:A(),sequence:this.sequence++}))}performance(e){this.canCollect()&&this.enqueue(pt({...this.checkoutContext,...e,eventId:A(),sequence:this.sequence++}))}terminal(e){if(this.canCollect()&&(this.enqueue(yt({...this.checkoutContext,...e,eventId:A(),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 fe({now:()=>this.now(),newAttemptId:A,emit:(t,r)=>this.recordThreeDsChallenge(t,r)},e)}recordThreeDsChallenge(e,t){if(!this.canCollect()||this.threeDsChallengeCount>=Rt)return;let r=Re({...this.checkoutContext,...e,name:"three_ds.challenge",stage:"three_ds_handoff",eventId:A(),sequence:this.sequence++});if(!(this.queue.length>=Se)){if(this.threeDsChallengeCount+=1,this.queue.push(r),t){this.drainQueue();return}if(this.queue.length>=j){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,r]of this.reportedFailures)(e<r||e-r>=Ae)&&this.reportedFailures.delete(t)}rememberReportedFailure(e,t){for(;this.reportedFailures.size>=Tt;){let r=this.reportedFailures.keys().next();if(r.done)break;this.reportedFailures.delete(r.value)}this.reportedFailures.set(e,t)}setCheckoutContext(e){this.checkoutContext={checkoutMode:e.checkoutMode,layout:e.layout}}beginCheckout(e={}){return this.canCollect()?(this.drainQueue(),this.setCheckoutContext(e),this.sequence=0,this.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>=Se||this.eventCounts[e.class]>=_t[e.class])){if(this.eventCounts[e.class]+=1,this.queue.push(e),this.queue.length>=j){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,j);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,j);this.sendBatch(e)}}async sendBatch(e){if(!this.browserTransportAvailable||this.ingestionDisabled)return;let t=gt(e,{correlationId:this.correlationId,sdkPackage:this.sdkPackage,sdkVersion:this.sdkVersion,batchId:A()});if(St(t)>ft)return;let r=typeof AbortController>"u"?null:new AbortController,i=null;try{let s=fetch(this.endpoint,{method:"POST",headers:{"content-type":"text/plain;charset=UTF-8"},body:t,credentials:"omit",keepalive:!0,referrerPolicy:"no-referrer",signal:r?.signal}).then(async l=>{if(l.status!==202)return null;let d=null;try{d=await l.json()}catch{}return d?.status==="disabled"?"disabled":null}).catch(()=>null),o=new Promise(l=>{i=setTimeout(()=>{r?.abort(),l(null)},Ct)});await Promise.race([s,o])==="disabled"&&this.disableFromIngestion()}catch{}finally{i&&clearTimeout(i)}}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)}},we=Symbol.for("@flopay/js.telemetry.reporter-factory.v1"),Ee=globalThis;Ee[we]===void 0&&Object.defineProperty(Ee,we,{configurable:!0,enumerable:!1,writable:!1,value:n=>new w(n)});function Ut(n){return n==="on_session"||n==="off_session"}function Lt(n){if(!n||typeof n!="object")return!1;let e=n;return typeof e.paymentMethodType=="string"&&typeof e.reason=="string"}function qt(n){let e=n.vaultOutcome;if(!(!e||e.code!==kt))return typeof e.message=="string"&&e.message.trim()!==""?e.message:void 0}var Nt="x-flopay-process-result-source",Vt="status",$e=new WeakSet;function Bt(n,e){let t=new f(n,"api_error",{code:e,statusCode:500});return $e.add(t),t}function zt(n){return typeof n=="object"&&n!==null&&$e.has(n)}function Ue(n){return n?.result==="DECLINE"||n?.result==="ERROR"}var Ht=50,I=new Map;function jt(n,e){return I.get(n)?.has(e)===!0}function Kt(n,e){let t=I.get(n)??new Set;if(t.add(e),I.delete(n),I.set(n,t),I.size>Ht){let r=I.keys().next().value;r!==void 0&&I.delete(r)}}function Gt(n){let e=n?.threeDSecureActionResultTokenId;if(typeof e=="string"&&e.length>0)return e;if(n?.gateway==="paypal"&&n.type!=="paypal_setup_token"&&typeof n.id=="string"&&n.id.length>0)return n.id}var Le=0,qe=500,K=15e3,Ne=15e3,$t=3e3,Yt=1e4,Wt=1e4;function q(n){return typeof n=="object"&&n!==null}function k(n,e){return me(n?.[e])}function Ve(n,e){return pe(n?.[e])}function Jt(n,e){let t=n?.[e];return typeof t=="number"&&Number.isFinite(t)?t:void 0}function $(n,e){return e?new Promise((t,r)=>{let i=()=>{clearTimeout(s),r(e.reason??Object.assign(new Error("The operation was aborted."),{name:"AbortError"}))},s=setTimeout(()=>{e.removeEventListener("abort",i),t()},n);e.aborted?i():e.addEventListener("abort",i,{once:!0})}):new Promise(t=>setTimeout(t,n))}function ie(n){return n instanceof Error&&n.name==="AbortError"}function b(){return new f(Et,"api_error",{code:"checkout_processing_timeout"})}async function S(n,e){let t=await n.json().catch(()=>null),r=q(t?.error)?t.error:null,i=Ve(t,"message")??Ve(r,"message")??e,s=k(t,"code")??k(t,"gatewayErrorCode")??k(r,"code")??`http_${n.status}`;return Ge(new f(i,"api_error",{code:s,statusCode:n.status}),n)}async function Qt(n){if(n.status!==403)return!1;let e=await n.clone().json().catch(()=>null),t=q(e?.error)?e.error:null;return(k(e,"code")??k(t,"code"))==="verification_required"}function Xt(n){if(!(!q(n)||typeof n.required!="boolean"))return{required:n.required,provider:"turnstile"}}async function Zt(n){let e=n.status===400?await n.clone().json().catch(()=>null):null;return Mt(n.status,e)}function Be(n){return n===400||n===422}var Y=2;async function G(n,e,t=Y,r,i){let s;for(let o=0;;o++)try{return i?.(o),await fetch(n,e)}catch(a){if(e?.signal?.aborted||a instanceof Error&&a.name==="AbortError")throw a;if(s=a,o>=t)throw s;try{r?.(o+1)}catch{}await $(150*2**o,e?.signal??void 0)}}var er=2e3,tr=1e4,rr=150;async function nr(n){try{let t=(await n.json())?.data?.status;return t==="closed"||t==="not_open"?t:"failed"}catch{return"failed"}}async function ze(n,e,t){let r=new AbortController,i=()=>r.abort();t?.addEventListener("abort",i,{once:!0});let s,o=new Promise(a=>{s=setTimeout(()=>{r.abort(),a("timeout")},tr)});try{let a=await Promise.race([fetch(n,{...e,signal:r.signal}),o]);return a==="timeout"?"failed":a.status>=500?"retry":a.ok?await nr(a):"failed"}catch{return r.signal.aborted?"failed":"retry"}finally{clearTimeout(s),t?.removeEventListener("abort",i)}}function ir(n,e){return new Promise(t=>{let r=setTimeout(t,e);n.then(()=>{clearTimeout(r),t()},()=>{clearTimeout(r),t()})})}var He="stripe-account-switch-v1",sr=Symbol.for("@flopay/js.session-create.telemetry.v1");function or(n){return n[sr]}function ar(n){return"now"in n||"onFirstByte"in n||"onSessionCreateFailure"in n||"onRetry"in n}function Ye(n){let e=oe(n.firstName,n.lastName);return{userId:n.userId,firstName:e?null:n.firstName??null,lastName:e?null:n.lastName??null,email:n.email,country:n.country??null,gender:n.gender??null,city:n.city??null,state:n.state??null,zip:n.zip??null,addressLine1:n.addressLine1??null,addressLine2:n.addressLine2??null}}function We(n,e){e.checkoutMetadata!==void 0&&(n.checkoutMetadata=e.checkoutMetadata),e.tagsData&&(n.tagsData=e.tagsData),e.utmMetadata&&e.utmMetadata.length>0&&(n.utmMetadata=e.utmMetadata),e.avsCheck!==void 0&&(n.avsCheck=e.avsCheck),e.checkoutType&&(n.checkoutType=e.checkoutType),e.checkoutLayout&&(n.checkoutLayout=e.checkoutLayout),e.avsConfig&&(n.avsConfig=e.avsConfig)}function je(n){if(typeof n!="string")return;let e=n.trim();return e.length>0?e:void 0}function lr(n){let e={};if(n.country&&(e.country=n.country),!oe(n.firstName,n.lastName)){let t=je(n.firstName),r=je(n.lastName);t&&(e.firstName=t),r&&(e.lastName=r)}return Object.keys(e).length>0?e:void 0}function dr(n,e,t){let r={clientId:n.clientId,checkoutVersion:E,successUrl:n.successUrl,cancelUrl:n.cancelUrl,currency:e,checkoutMode:"full",deferDataAttachment:!0};n.captureMethod==="manual"&&(r.captureMethod=n.captureMethod);let i=lr(n.account);i&&(r.accountData=i),We(r,n);let s=cr(t);return s&&(r.routingProducts=s),r}function cr(n){let e=new Set;for(let t of n){let r=[t.code,t.providerItemId,t.providerPlanId].map(i=>typeof i=="string"?i.trim():"").find(i=>i.length>0);r&&e.add(r)}return e.size>0?Array.from(e,t=>({code:t})):void 0}function Ke(n,e,t){return{currency:e,products:t.map(r=>se(r,e)),couponCodes:n.couponCodes??[],accountData:Ye(n.account)}}function ur(n,e,t){return{currency:e,products:t.map(r=>se(r,e)),couponCodes:n.couponCodes??[]}}function hr(n){let e={},t=oe(n.firstName,n.lastName);for(let[r,i]of Object.entries(n)){if(t&&r.endsWith("Name")||typeof i!="string")continue;let s=i.trim();s&&(e[r]=s)}return{accountData:e}}var R=class R{constructor(e,t={}){this.baseUrl=e.replace(/\/+$/,"");let r=ar(t);this.telemetryHooks=r?t:void 0,this.stripeAccountSwitch=!r&&t.stripeAccountSwitch===!0,this.directTelemetry=r||t.telemetry===!1?void 0:new w({billingApiUrl:this.baseUrl,sdkVersion:E})}destroy(){this.directTelemetry?.destroy()}reportDirectFailure(e,t,r,i,s="unknown"){let o=x(e,t);this.directTelemetry?.error({...o,...zt(e)?{reason:"capture_failed"}:{},stage:r,requestCategory:i,paymentMethodCategory:s})}reportAccountSnapshotFailure(e,t){let r=x(e,"NETWORK_REQUEST_FAILED");if(t==="best_effort"&&r.errorCode==="REQUEST_TIMEOUT"){this.directTelemetry?.log({name:"operation.fallback",stage:"processing",requestCategory:"account_snapshot",statusClass:"timeout"});return}this.directTelemetry?.error({...r,stage:"processing",requestCategory:"account_snapshot",paymentMethodCategory:"unknown"})}telemetryTimestamp(){try{return this.telemetryHooks?.now?.()??this.directTelemetry?.now()??_()}catch{return _()}}beginDirectTelemetryCheckout(e){!this.directTelemetry||this.directTelemetryCheckoutId===e||(this.directTelemetryCheckoutId=e,this.directTelemetry.beginCheckout())}beginDirectTelemetryOperation(){this.directTelemetry&&(this.directTelemetryCheckoutId=void 0,this.directTelemetry.beginCheckout())}adoptDirectTelemetryCheckout(e){e&&(this.directTelemetryCheckoutId=e)}async getCheckoutSession(e,t){return this.fetchCheckoutSession(e,t)}async fetchCheckoutSession(e,t,r=!0,i){this.beginDirectTelemetryCheckout(e);let s=this.telemetryTimestamp(),o=s,a=0;this.directTelemetry?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let l={[U]:E};t&&(l["x-checkout-session-token"]=t);let d=!1;try{let c=await G(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}`,{headers:l,signal:i},Y,u=>{this.telemetryHooks?.onRetry?.("session_read",u),this.directTelemetry?.log({name:"operation.retry",stage:"session_read",requestCategory:"session_read",attempt:u})},u=>{a=u,o=this.telemetryTimestamp()});d=!0;let p=Math.max(0,this.telemetryTimestamp()-o);try{this.telemetryHooks?.onFirstByte?.(p,a)}catch{}let h=`${Math.floor(c.status/100)}xx`;if(this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:h,attempt:a}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:p,durationMode:"machine",requestCategory:"session_read",statusClass:h,attempt:a}),!c.ok)throw await S(c,"Failed to get checkout session");let m=await c.json();return this.directTelemetry?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:h}),this.directTelemetry?.performance({stage:"session_complete",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"session_read",statusClass:h}),{...m,data:this.mergeCachedDisplayData(m.data)}}catch(c){throw d&&L(c),r&&this.directTelemetry?.error({...x(c,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"}),c}}cacheSessionDisplayData(e,t,r){Z(e,t,r)}clearSessionDisplayData(e){he(e)}async getVaultCapture(e,t){let r=`${this.baseUrl}\0${e}\0${t??""}`,i=R.activeVaultCaptureRequests.get(r);if(i!==void 0)return i;let s=R.pendingThreeDsAbandonReports.get(e),o=s===void 0?this.requestVaultCapture(e,t):ir(s,er).then(()=>this.requestVaultCapture(e,t));R.activeVaultCaptureRequests.set(r,o);try{return await o}finally{R.activeVaultCaptureRequests.get(r)===o&&R.activeVaultCaptureRequests.delete(r)}}async requestVaultCapture(e,t){let r=new AbortController,i=setTimeout(()=>r.abort(),Wt);this.beginDirectTelemetryCheckout(e);let s=this.telemetryTimestamp();this.directTelemetry?.log({name:"vault.capture.requested",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card"});let o={"Content-Type":"application/json"};t&&(o["x-checkout-session-token"]=t);try{let a=await G(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/vault/capture`,{method:"POST",headers:o,signal:r.signal},Y,d=>{this.telemetryHooks?.onRetry?.("vault_capture",d),this.directTelemetry?.log({name:"operation.retry",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card",attempt:d})});if(await Qt(a))return this.directTelemetry?.performance({stage:"vault_request",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"4xx"}),{verification:{required:!0,provider:"turnstile"}};if(!a.ok)throw await S(a,"Failed to load the secure card form");let l=await a.json();return this.directTelemetry?.performance({stage:"vault_request",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"2xx"}),this.toVaultBlock(l)}catch(a){let l=r.signal.aborted?new f("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(i)}}async getUnifiedCheckoutSession(e,t){let r=await this.getCheckoutSession(e,t);return this.normalizeCheckoutSessionResponse(r)}async getUnifiedCheckoutSessionForRecovery(e,t,r){let i=await this.fetchCheckoutSession(e,t,!1,r);return this.normalizeCheckoutSessionResponse(i)}normalizeCheckoutSessionResponse(e){try{let t=this.normalizeRawSession(e.data),r=e.vault;return r&&t.data.session&&(t.data.session.vault=this.toVaultBlock(r)),t}catch(t){throw L(t)}}async processPayment(e,t,r){this.beginDirectTelemetryCheckout(t.sessionId);let i=t.paymentMethodCategory??"unknown";if(!t.nonce)throw this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"process_payment",paymentMethodCategory:i}),new f("processPayment requires `nonce` \u2014 pass the value returned from session creation.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let s=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.processing.started",stage:"processing",requestCategory:"process_payment",paymentMethodCategory:i});let{nonce:o,paymentMethodCategory:a,...l}=t,d=Gt(t.tokenizedData),c,p;try{c=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)}),p=c}catch(h){if(ie(h))throw this.reportDirectFailure(h,"PAYMENT_PROCESSING_FAILED","processing","process_payment",i),h;c=await this.reconcileProcessPayment(t.sessionId,{...r,nonce:o,paymentMethodCategory:i,submittedIntentId:d})}if(!c.ok&&c.status!==202){let h=await Zt(c);return h?this.directTelemetry?.terminal({outcome:h,stage:"processing",requestCategory:"process_payment",statusClass:"4xx",paymentMethodCategory:i}):this.directTelemetry?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",requestCategory:"process_payment",statusClass:M(c.status),failureCategory:c.status>=500?"server_error":void 0,paymentMethodCategory:i,...Ot(p)}),c}try{let h=await this.resolveProcessResponse(c,t.sessionId,{...r,nonce:o,paymentMethodCategory:i,submittedIntentId:d});return this.directTelemetry?.log({name:"payment.processing.completed",stage:"processing",requestCategory:"process_payment",statusClass:M(h.status),paymentMethodCategory:i}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"process_payment",statusClass:M(h.status),paymentMethodCategory:i}),h}catch(h){throw h instanceof f&&h.code==="checkout_processing_timeout"||this.reportDirectFailure(h,"PAYMENT_PROCESSING_FAILED","processing","process_payment",i),h}}async patchAccountSnapshot(e,t,r,i){this.beginDirectTelemetryCheckout(e);let s=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.state_transition",stage:"processing",requestCategory:"account_snapshot"});let o=i?.timeoutMs??Yt,a=new AbortController,l=()=>a.abort();i?.signal&&(i.signal.aborted?a.abort():i.signal.addEventListener("abort",l,{once:!0}));let d=setTimeout(()=>a.abort(),o);try{let c;try{c=await G(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/account`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":t},body:JSON.stringify(r),signal:a.signal},Y,p=>{this.telemetryHooks?.onRetry?.("account_snapshot",p),this.directTelemetry?.log({name:"operation.retry",stage:"processing",requestCategory:"account_snapshot",attempt:p})})}finally{clearTimeout(d),i?.signal?.removeEventListener("abort",l)}if(!c.ok)throw await S(c,"Failed to persist account snapshot");this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"account_snapshot",statusClass:"2xx"})}catch(c){throw this.reportAccountSnapshotFailure(c,i?.telemetryMode??"blocking"),c}}async createSessionIntent(e,t,r,i){if(!t)throw new f("createSessionIntent requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let s=r,o=s.paymentMethodType,a=typeof o=="string"&&o.trim().toLowerCase()==="card",l=typeof o=="string"&&o.length>0&&!a&&(typeof s.paymentMethodId=="string"||s.paymentMethodId===null),d=s.provider==="stripe"&&(s.paymentMethodCategory==="wallet"||s.paymentMethodCategory==="apm")&&(s.intentKind==="payment"||s.intentKind==="setup"),c=s.provider==="paypal"&&s.paymentMethodCategory==="wallet"&&s.paymentMethodId===null&&(s.paymentMethodType==="paypal"&&s.intentKind==="payment"||s.paymentMethodType===re&&(s.intentKind==="payment"||s.intentKind==="setup"));if(!l||!d&&!c)throw new f("Only wallet, APM, and PayPal session intents are supported.","validation_error",{code:"InvalidSessionIntentRequest"});let p=s.authorizationAttemptId;if(p!==void 0&&!De(p))throw new f("authorizationAttemptId must be a v4 UUID identifying one buyer authorization attempt.","validation_error",{code:"InvalidAuthorizationAttemptId",param:"authorizationAttemptId"});let h=De(p)?p:Ft();this.beginDirectTelemetryCheckout(e);let m=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.intent.started",stage:"processing",requestCategory:"intent_create"});let u={"Content-Type":"application/json","x-checkout-session-token":t,[Ie]:i?.idempotencyKey||h},y=!1;try{let C=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents`,{method:"POST",headers:u,body:JSON.stringify({...r,authorizationAttemptId:h}),signal:i?.signal});if(!C.ok){y=!0;let Q=await S(C,"Failed to create checkout intent"),ot=x(Q,"PAYMENT_PROCESSING_FAILED");throw Be(Q.statusCode)?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"intent_create",statusClass:"4xx"}):this.directTelemetry?.error({...ot,stage:"processing",requestCategory:"intent_create"}),Q}let v=await C.json();if(C.status===202&&q(v)&&v.type==="checkout_processing")return y=!0,await this.settleProcessingSessionIntent(v,C,e,t,r);let T=v.data;if(!T||typeof T!="object")throw new f("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});let g=T,ce=g.paymentMethodType,rt=(g.paymentMethodCategory==="wallet"||g.paymentMethodCategory==="apm")&&typeof ce=="string"&&ce.trim().toLowerCase()!=="card"&&(typeof g.paymentMethodId=="string"||g.paymentMethodId===null)&&typeof g.providerObjectId=="string",nt=g.provider==="stripe"&&(g.intentKind==="payment"||g.intentKind==="setup")&&typeof g.clientSecret=="string",it=g.provider==="paypal"&&g.paymentMethodCategory==="wallet"&&g.paymentMethodId===null&&(g.paymentMethodType==="paypal"&&g.intentKind==="payment"&&(g.providerObjectType==="order"||g.providerObjectType==="subscription")||g.paymentMethodType===re&&g.intentKind==="payment"&&g.providerObjectType==="order"||g.paymentMethodType===re&&g.intentKind==="setup"&&g.providerObjectType==="setup_token")&&g.clientSecret===null,st=g.provider===r.provider&&g.paymentMethodCategory===r.paymentMethodCategory&&g.paymentMethodType===r.paymentMethodType&&g.paymentMethodId===r.paymentMethodId&&g.intentKind===r.intentKind;if(!rt||!nt&&!it||!st)throw new f("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});return this.directTelemetry?.log({name:"payment.intent.completed",stage:"processing",requestCategory:"intent_create",statusClass:M(C.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-m),durationMode:"machine",requestCategory:"intent_create",statusClass:M(C.status)}),g}catch(C){throw y||this.reportDirectFailure(C,"PAYMENT_PROCESSING_FAILED","processing","intent_create"),C}}async settleProcessingSessionIntent(e,t,r,i,s){let o=this.toCheckoutProcessingPending(e,t,r);try{return{settled:!0,response:await this.resolveCheckoutProcessing(o,r,{nonce:i,paymentMethodCategory:s.provider==="paypal"?"paypal":s.paymentMethodCategory})}}catch(a){throw a instanceof f&&a.code==="checkout_processing_timeout"?new f(a.message,a.type,{code:a.code,statusCode:202,sessionId:o.sessionId,cause:a}):a}}closeThreeDsChallenge(e,t,r,i={}){if(!e||!t||!r||i.signal?.aborted)return Promise.resolve("failed");let s=this.requestThreeDsChallengeClose(e,t,r,i.signal),o=R.pendingThreeDsAbandonReports;return o.set(e,s),s.then(()=>{o.get(e)===s&&o.delete(e)}),s}async requestThreeDsChallengeClose(e,t,r,i){let s=`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/3ds/abandoned`,o={method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":t},body:JSON.stringify({providerIntentId:r})};try{let a=await ze(s,o,i);if(a!=="retry")return a;if(i?.aborted)return"failed";await $(rr,i);let l=await ze(s,o,i);return l==="retry"?"failed":l}catch{return"failed"}}async reportSessionIntentDecline(e,t,r,i){if(!t)throw new f("reportSessionIntentDecline requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let s=r,o=s.providerDeclineReason,a=s.paymentMethodType,l=s.providerIntentId,d=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),c=typeof a=="string"&&a.length>0&&a.trim().toLowerCase()!=="card"&&d,p=s.provider==="stripe"&&(s.paymentMethodCategory==="wallet"||s.paymentMethodCategory==="apm")&&(l===void 0||typeof l=="string"&&/^pi_[a-z0-9_]{1,252}$/i.test(l)),h=s.provider==="paypal"&&s.paymentMethodCategory==="wallet"&&s.paymentMethodType==="paypal"&&l===void 0;if(!c||!p&&!h)throw new f("Invalid non-card decline classification.","validation_error",{code:"InvalidSessionIntentDeclineRequest"});let m=h?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:o}:{provider:"stripe",paymentMethodCategory:s.paymentMethodCategory,paymentMethodType:s.paymentMethodType,providerDeclineReason:o,...typeof l=="string"?{providerIntentId:l}:{}},u=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(m),signal:i?.signal});if(!u.ok)throw await S(u,"Failed to report checkout decline")}async resolvePaymentMethodLayout(e,t,r,i){if(!t)throw new f("resolvePaymentMethodLayout requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let s=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/payment-method-layout`,{method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":t,[U]:E},body:JSON.stringify(r),signal:i?.signal});if(s.status===404||s.status===405)return null;if(!s.ok)throw await S(s,"Failed to resolve the payment method layout");let o=await s.json();return Pt(o?.data)}async getPaymentsByEmail(e,t){this.beginDirectTelemetryOperation();let r=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved"});let i=t?.page??1,s=t?.limit??1,o=new URLSearchParams({email:e,page:String(i),limit:String(s),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 Ge(new f("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()-r),durationMode:"machine",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),l}catch(a){throw this.reportDirectFailure(a,"RECOVERY_FAILED","recovery","other","saved"),a}}async createAndFetchSession(e){if(Dt(e)){let s=e.account.email?.trim();if(s&&!Pe(s))throw new f("Buyer email must be valid when supplied.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"});return(await this.createDetachedSession(e)).claimed}this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp(),r=D(e.timeoutMs??12e3),i={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});try{let s=await this.createAndFetchSessionRequest(e,r.signal,i);return this.adoptDirectTelemetryCheckout(s.data.session?.id),this.directTelemetry?.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:i.statusClass}),this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:"session_create",statusClass:i.statusClass,attempt:i.attempt}),s}catch(s){throw this.reportSessionCreateFailure(s,t,i),s}finally{r.clear()}}async createAndFetchSessionRequest(e,t,r){let i=e.products??te(e.items,e.subscriptions);ke({captureMethod:e.captureMethod,products:i});let s=ne(e.currency,e.items,e.subscriptions,i);if(!s)throw new f("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:E,successUrl:e.successUrl,cancelUrl:e.cancelUrl,currency:s,checkoutMode:e.checkoutMode??"full",products:i.map(d=>se(d,s)),accountData:Ye(e.account),couponCodes:e.couponCodes??[]};e.captureMethod==="manual"&&(o.captureMethod=e.captureMethod),e.tokenizedData&&(o.tokenizedData=e.tokenizedData),We(o,e);let a=await this.postCheckoutSessionCreate(o,e,t,r),l=!1;try{let d=await a.json();if(d.data&&"gateways"in d.data){this.autoCacheDisplayData(d.data.uuid,e);let h=this.mergeCachedDisplayData(d.data),m=this.normalizeRawSession(h);return d.vault&&m.data.session&&(m.data.session.vault=this.toVaultBlock(d.vault)),{...m,autoProcessingError:d.autoProcessingError,autoProcessingAttempted:d.autoProcessingAttempted,autoProcessingPending:d.autoProcessingPending}}let c=d.data?.uuid;if(!c)throw new f("No session ID returned","api_error",{code:"InvalidCheckoutSessionResponse"});return this.autoCacheDisplayData(c,e),this.adoptDirectTelemetryCheckout(c),l=!0,{...await this.getUnifiedCheckoutSession(c),autoProcessingError:d.autoProcessingError,autoProcessingAttempted:d.autoProcessingAttempted,autoProcessingPending:d.autoProcessingPending}}catch(d){throw l?d:L(d)}}async postCheckoutSessionCreate(e,t,r,i){let s={"Content-Type":"application/json",[U]:E},o=xt(t.idempotencyKey);o&&(s[Ie]=o);let a=[];t.checkoutMode==="auto"&&a.push(wt),this.stripeAccountSwitch&&e.deferDataAttachment===!0&&a.push(He),a.length>0&&(s[Me]=a.join(", "));let l,d=!1,c=or(t),p=(m,u,y)=>{d||(d=!0,this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:y,attempt:m}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:Math.max(0,this.telemetryTimestamp()-u),durationMode:"machine",requestCategory:"session_create",statusClass:y,attempt:m}))},h=m=>{try{this.telemetryHooks?.onRetry?.("session_create",m),this.directTelemetry?.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:m})}catch{}};for(let m=0;m<3;m++){i.attempt=m;let u=this.telemetryTimestamp();try{c?.onAttempt?.(m)}catch{}try{l=await fetch(`${this.baseUrl}/v1/checkouts/sessions?expand=true`,{method:"POST",headers:s,body:JSON.stringify(e),signal:r})}catch(v){if(i.statusClass=r.aborted||v instanceof Error&&v.name==="AbortError"?"timeout":"network_error",r.aborted||v instanceof Error&&v.name==="AbortError"||m>=2)throw v;let T=m+1;h(T),await H(m,r);continue}let y=M(l.status);if(i.statusClass=y,l.status===204)throw p(m,u,y),new f("Session auto-completed \u2014 payment method already on file","api_error",{code:"session_auto_completed"});if(l.ok){p(m,u,y);break}let C=await S(l,"Failed to create checkout session");if(C.code===It&&m<2){h(m+1),await H(m,r);continue}throw p(m,u,y),C}if(!l)throw new TypeError("Checkout-session creation exhausted its retry budget.");return l}async createDetachedSession(e){this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp(),r=D(e.timeoutMs??12e3),i={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let s=e.products??te(e.items,e.subscriptions);try{ke({captureMethod:e.captureMethod,products:s})}catch(v){throw r.clear(),this.reportSessionCreateFailure(v,t,i),v}let o=ne(e.currency,e.items,e.subscriptions,s);if(!o)throw r.clear(),this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),new f("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{Ke(e,o,s)}catch(v){throw r.clear(),this.reportSessionCreateFailure(v,t,i),v}let a,l,d=!1;try{let v=await this.postCheckoutSessionCreate(dr(e,o,s),e,r.signal,i);if(d=!0,l=await v.json(),!l.data||!("gateways"in l.data))throw new f("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 r.clear(),d&&L(v),this.reportSessionCreateFailure(v,t,i),v}let c=a.data.session?.id??l.data.uuid??"",p=a.data.session?.clientSecret??l.data.nonce??"";if(!c||!p){r.clear();let v=new f("Checkout session shell was created without a session id or nonce.","api_error",{code:"InvalidCheckoutSessionResponse"});throw this.reportSessionCreateFailure(v,t,i),v}r.clear(),this.adoptDirectTelemetryCheckout(c),this.directTelemetry?.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",statusClass:i.statusClass,paymentMethodCategory:"card"}),this.directTelemetry?.performance({stage:"session_shell",durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:"session_create",statusClass:i.statusClass,attempt:i.attempt,paymentMethodCategory:"card"});let h=!e.account.email?.trim(),m=D(e.timeoutMs??12e3),u=this.claimCheckoutSession(c,p,h?ur(e,o,s):Ke(e,o,s),{params:e,startedAt:t,deadline:m,createAttempt:i.attempt}),y=h?void 0:u,C=(v={})=>{if(y!==void 0)return y;let T={...e,account:{...e.account,...v,email:v.email?.trim()||e.account.email?.trim()}};return Pe(T.account.email)?(y=u.then(()=>{let g=this.telemetryTimestamp();return this.claimCheckoutSession(c,p,hr(T.account),{params:T,startedAt:g,deadline:D(e.timeoutMs??12e3),createAttempt:0})}),y.catch(()=>{}),y):Promise.reject(new f("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}))};return u.catch(()=>{}),{shell:a,sessionId:c,nonce:p,claimed:u,claim:C}}async claimCheckoutSession(e,t,r,i){let s=i?.startedAt??this.telemetryTimestamp(),o=this.telemetryTimestamp(),a=i?.deadline??D(12e3),l=JSON.stringify(r),d="unknown",c=0,p=!1;this.directTelemetry?.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"});try{let h;for(c=0;c<3;c++){try{h=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/claim`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":t,[U]:E,...this.stripeAccountSwitch?{[Me]:He}:{}},body:l,signal:a.signal})}catch(y){let C=a.signal.aborted||y instanceof Error&&y.name==="AbortError";if(d=C?"timeout":"network_error",C||c>=2)throw y;try{this.telemetryHooks?.onRetry?.("session_claim",c+1),this.directTelemetry?.log({name:"operation.retry",stage:"session_claim",requestCategory:"session_claim",attempt:c+1})}catch{}await H(c,a.signal);continue}if(d=M(h.status),h.ok)break;throw await S(h,"Failed to attach checkout session data")}if(!h)throw new TypeError("Checkout-session claim exhausted its retry budget.");p=!0;let m=await h.json();if(!m.data?.gateways)throw new f("The billing API returned no checkout session with gateways after claiming it.","api_error",{code:"InvalidCheckoutSessionResponse"});i?.params&&this.autoCacheDisplayData(m.data.uuid??e,i.params);let u=this.normalizeRawSession(this.mergeCachedDisplayData(m.data));return m.vault&&u.data.session&&(u.data.session.vault=this.toVaultBlock(m.vault)),this.directTelemetry?.log({name:"session.claim.completed",stage:"session_claim",requestCategory:"session_claim",statusClass:d}),this.directTelemetry?.performance({stage:"session_claim",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"session_claim",statusClass:d,attempt:c}),this.directTelemetry?.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:d}),this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"session_create",statusClass:d,attempt:i?.createAttempt??c}),u}catch(h){throw p&&L(h),this.reportSessionCreateFailure(h,o,{attempt:c,statusClass:d},"session_claim"),h}finally{a.clear()}}reportSessionCreateFailure(e,t,r,i="session_create"){if(!(e instanceof f&&e.code==="session_auto_completed"))try{this.telemetryHooks?.onSessionCreateFailure?.(e)}catch{}let s=x(e,"CHECKOUT_SESSION_CREATE_FAILED");if(this.directTelemetry?.performance({stage:i,durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:i==="session_claim"?"session_claim":"session_create",statusClass:s.statusClass,attempt:r.attempt}),e instanceof f&&e.type==="validation_error"||e instanceof f&&Be(e.statusCode)){this.directTelemetry?.terminal({outcome:"validation_rejected",stage:i,requestCategory:i==="session_claim"?"session_claim":"session_create",...e.type==="validation_error"?{}:{statusClass:"4xx"}});return}e instanceof f&&e.code==="session_auto_completed"||this.directTelemetry?.error({...s,stage:i,requestCategory:i==="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 r=this.telemetryTimestamp(),i=t?.paymentMethodCategory??"saved";this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:i});let s=t?.timeoutMs??K,o=Date.now()+s,a=new AbortController,l=!1,d,c=setTimeout(()=>{d=setTimeout(()=>{l=!0,a.abort()},Ne)},s),p=()=>a.abort(t?.signal?.reason);t?.signal?.aborted?p():t?.signal?.addEventListener("abort",p,{once:!0});let h=this.clampRetryAfterMs(t?.initialDelayMs??Le),m=0;try{if(t?.statusUrl){let u=await this.waitForCheckoutStatus(e,{initialDelayMs:h,timeoutMs:s,nonce:t.nonce,statusUrl:t.statusUrl,pollAfterAction:t.continueAfterActionRequired,signal:a.signal});if(u){let y=await this.resolveCheckoutSessionStatus(e,u,t.nonce,a.signal,()=>l);return this.reportRecoveryCompleted(r,i,t.challengeAttemptId),y}}for(;;){let u=o-Date.now();if(u<=0)throw b();if(h>0){try{m+=1,this.telemetryHooks?.onRetry?.("session_read",m),this.directTelemetry?.log({name:"operation.retry",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:i,attempt:m})}catch{}if(await $(Math.min(h,u),a.signal),Date.now()>=o)throw b()}let y=await this.getUnifiedCheckoutSessionForRecovery(e,t?.nonce,a.signal),C=y.data.session?.status;if(C==="authorized"||C==="complete"||C==="expired")return this.reportRecoveryCompleted(r,i,t?.challengeAttemptId),y;if(Date.now()>=o)throw b();h=this.clampRetryAfterMs(Math.max(h*2,qe))}}catch(u){let y=l&&ie(u)?b():u;throw this.reportDirectFailure(y,"RECOVERY_FAILED","recovery","session_read",i),y}finally{clearTimeout(c),clearTimeout(d),t?.signal?.removeEventListener("abort",p)}}reportRecoveryCompleted(e,t,r){let i={stage:"recovery",requestCategory:"session_read",paymentMethodCategory:t};if(this.directTelemetry?.log({name:"operation.recovery.completed",...i}),r)try{this.directTelemetry?.beginThreeDsChallenge({attemptId:r}).record("recovery_read_completed",{evidenceBasis:"server_status"})}catch{}this.directTelemetry?.performance({...i,durationMs:Math.max(0,this.telemetryTimestamp()-e),durationMode:"machine"})}async resolveCheckoutSessionStatus(e,t,r,i,s){let o=t.latestTransactionAttempt;if(this.rememberReportedFailure(e,t),o?.result==="DECLINE"){let d=o.code===Oe;throw new f(d?xe:"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 Bt("Payment could not be completed. Please try again.",o?.code??"payment_processing_error");let a;try{a=await this.getUnifiedCheckoutSessionForRecovery(e,r,i)}catch(d){if(!s?.()||!ie(d))throw d;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 r=t.timeoutMs??K,i=Date.now()+r,s=this.clampRetryAfterMs(t.initialDelayMs);for(;;){let o=i-Date.now();if(o<=0||s>0&&(await $(Math.min(s,o),t.signal),Date.now()>=i))throw b();let a=i-Date.now();if(a<=0)throw b();let l=new AbortController,d,c=t.signal?new Promise((T,g)=>{d=g}):null,p=()=>{l.abort(t.signal?.reason),d?.(t.signal?.reason??Object.assign(new Error("The operation was aborted."),{name:"AbortError"}))};t.signal?.aborted?p():t.signal?.addEventListener("abort",p,{once:!0});let h,m=t.signal?null:new Promise((T,g)=>{h=setTimeout(()=>{g(b()),l.abort()},a+Ne)}),u;try{let T=this.fetchCheckoutStatus(e,t.nonce,t.statusUrl,l.signal);u=await Promise.race([T,m,c].filter(g=>g!==null))}finally{h!==void 0&&clearTimeout(h),t.signal?.removeEventListener("abort",p)}if(!u)return null;let y=Ue(u.latestTransactionAttempt)&&!this.isOwnFailedAttempt(e,u,t.submittedIntentId);if(u.status==="completed"||u.status==="authorized"||u.status==="expired"||u.status==="voided")return y?{...u,latestTransactionAttempt:null}:u;let C=u.latestTransactionAttempt?.result,v=t.pollAfterAction===!0&&C==="ACTION_REQUIRED";if(!y&&C!==void 0&&C!=="PENDING"&&!v)return u;s=this.clampRetryAfterMs(Math.max(s*2,qe))}}isOwnFailedAttempt(e,t,r){let i=t.latestTransactionAttempt?.providerIntentId??null;return r!==void 0?i===r:i===null?!0:!jt(t.uuid||e,i)}rememberReportedFailure(e,t){let r=t.latestTransactionAttempt;!Ue(r)||!r.providerIntentId||Kt(t.uuid||e,r.providerIntentId)}async fetchCheckoutStatus(e,t,r,i){let s=`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/status`,o=s;if(r)try{let c=new URL(r,`${this.baseUrl}/`),p=new URL(s);c.origin===p.origin&&(o=c.toString())}catch{}let a={[U]:E};t&&(a["x-checkout-session-token"]=t);let l=await G(o,{headers:a,signal:i});if(l.status===404||l.status===405)return null;if(!l.ok)throw await S(l,"Failed to get checkout session status");let d=await l.json();return q(d.data)&&"latestTransactionAttempt"in d.data?d.data:null}normalizeRawSession(e){let t=e.gateways??{},r=[],i={session:this.toCheckoutSession(e)},s=t.stripe;if(s?.publishableKey){r.push("stripe");let l=[e.stripeClientSecret,s.stripeClientSecret].find(d=>typeof d=="string"&&d.length>0);i.stripe={clientSecret:l??"",publishableKey:s.publishableKey??void 0,paypalPublishableKey:s.paypalPublishableKey??void 0,environment:s.environment,enabledPaymentMethods:Array.isArray(s.enabledPaymentMethods)?s.enabledPaymentMethods.filter(d=>typeof d=="string"):void 0}}let o=t.paypal;return o?.publishableKey&&(r.push("paypal"),i.paypal={publishableKey:o.publishableKey,environment:o.environment,providerObjectType:o.providerObjectType,approvalPresentation:o.approvalPresentation}),{providers:r,mode:"tokenize",...e.checkoutMetadata===void 0?{}:{checkoutMetadata:e.checkoutMetadata},data:i,raw:{data:e}}}toCheckoutSession(e){let t=e.products??[],r=typeof e.totalAmount=="number"&&Number.isFinite(e.totalAmount),i=t.reduce((d,c)=>d+(c.overrideAmount??c.totalAmount??0),0),s=r?e.totalAmount:i,o=Math.round(s*100),a=e.currency??t[0]?.currency??"USD",l="payment";return e.checkoutMode==="setup"?l="setup":t.some(d=>d.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:Fe(e.outcome)??Fe(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}:{},...Ut(e.futureUse)?{futureUse:e.futureUse}:{},...Array.isArray(e.futureUseUnsupported)?{futureUseUnsupported:e.futureUseUnsupported.filter(Lt)}:{},buyerIdentified:e.buyerIdentified,providerPaymentMethodId:typeof e.providerPaymentMethodId=="string"?e.providerPaymentMethodId:null,products:t.map(d=>({...d,totalAmount:typeof d.totalAmount=="number"?d.totalAmount:void 0,overrideAmount:typeof d.overrideAmount=="number"?d.overrideAmount:null,currency:typeof d.currency=="string"?d.currency:void 0,metadata:d.metadata??null})),successUrl:e.successUrl,cancelUrl:e.cancelUrl,coupons:e.coupons,subtotalAmount:e.subtotalAmount,discountAmount:e.discountAmount,totalAmount:e.totalAmount,createdAt:e.createdAt,gateways:e.gateways,accountData:e.accountData,tagsData:e.tagsData}}toVaultBlock(e){let t=Xt(e.verification);return{html:typeof e.html=="string"?e.html:void 0,url:typeof e.url=="string"?e.url:void 0,messageToken:typeof e.messageToken=="string"?e.messageToken:void 0,expectedOrigin:typeof e.expectedOrigin=="string"?e.expectedOrigin:void 0,...t?{verification:t}:{}}}toCheckoutSessionStatus(e){return e==="completed"?"complete":e==="authorized"?"authorized":e==="expired"?"expired":"open"}async resolveProcessResponse(e,t,r){if(e.status!==202)return e;let i=await e.json().catch(()=>null),s=this.toCheckoutProcessingPending(i,e,t);return this.resolveCheckoutProcessing(s,t,r)}async resolveCheckoutProcessing(e,t,r){let i=r?.pollTimeoutMs??K,s=Date.now()+i;if(e.statusUrl){let a=await this.waitForCheckoutStatus(e.sessionId,{initialDelayMs:e.retryAfterMs,timeoutMs:i,nonce:r?.nonce,statusUrl:e.statusUrl,submittedIntentId:r?.submittedIntentId});if(a)return this.toProcessResponseFromStatus(a,t,r?.nonce)}let o=await this.waitForCheckoutSessionCompletion(e.sessionId,{initialDelayMs:e.retryAfterMs,timeoutMs:s-Date.now(),nonce:r?.nonce,paymentMethodCategory:r?.paymentMethodCategory});return this.toProcessResponseFromSession(o,t)}async toProcessResponseFromStatus(e,t,r){let i=e.latestTransactionAttempt?.result,s={[Nt]:Vt},o={"Content-Type":"application/json",...s};if(e.status==="completed"||i==="SUCCESS")return new Response(null,{status:204,statusText:"No Content",headers:s});if(e.status==="authorized"||i==="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,r);return this.toProcessResponseFromSession(a,t)}if(this.rememberReportedFailure(t,e),i==="DECLINE"){let a=e.latestTransactionAttempt,l=a?.code===Oe,d=a?.declineReason??void 0;return new Response(JSON.stringify({type:d??"authorization_declined",message:l?xe:"Payment was declined. Please choose another payment method.",code:a?.code??d??"authorization_declined",...d?{declineCode:d}:{}}),{status:400,headers:o})}if(i==="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(i==="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(i==="ERROR"||e.status==="voided")return new Response(JSON.stringify({type:"unknown",code:e.latestTransactionAttempt?.code??"payment_processing_error",message:qt(e)??"Payment could not be completed. Please try again."}),{status:500,headers:o});throw b()}async reconcileProcessPayment(e,t){let r=t?.pollTimeoutMs??K,i=Date.now()+r,s=null;try{s=await this.waitForCheckoutStatus(e,{initialDelayMs:0,timeoutMs:r,nonce:t?.nonce,submittedIntentId:t?.submittedIntentId})}catch(l){if(this.reportDirectFailure(l,"RECOVERY_FAILED","recovery","session_read",t?.paymentMethodCategory??"saved"),l instanceof f&&l.code==="checkout_processing_timeout")throw l}if(s)return this.toProcessResponseFromStatus(s,e,t?.nonce);let o=i-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 r=e.data.session;return new Response(JSON.stringify({status:"authorized",paymentId:r.paymentId,sessionId:r.id||t,authorizationExpiresAt:r.authorizationExpiresAt}),{status:200,headers:{"Content-Type":"application/json"}})}if(e.data.session?.status==="expired"){let r=e.data.session.failureOutcome==="authorization_expired"||e.data.session.captureMethod==="manual";throw new f(r?"Authorization has expired.":"Checkout session has expired.","api_error",{code:r?"authorization_expired":"checkout_session_expired"})}throw b()}toCheckoutProcessingPending(e,t,r){let i=t.headers.get("Retry-After"),s=i===null||i.trim()===""?void 0:Number(i),o=s!==void 0&&Number.isFinite(s)?s*1e3:void 0;return{type:"checkout_processing",sessionId:k(e,"sessionId")??r,retryAfterMs:this.clampRetryAfterMs(Jt(e,"retryAfterMs")??o??Le),statusUrl:k(e,"statusUrl"),sessionUrl:k(e,"sessionUrl")}}clampRetryAfterMs(e){return Math.max(0,Math.min(e,$t))}autoCacheDisplayData(e,t){if(!e)return;let r=t.products??te(t.items,t.subscriptions);if(r.length===0&&!t.currency)return;let i=t.products!==void 0,s=ne(t.currency,i?void 0:t.items,i?void 0:t.subscriptions,r);Z(e,{currency:s??void 0,products:r.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??s??void 0}))})}mergeCachedDisplayData(e){let t=ue(e.uuid),r=new Map,i=o=>o?`code:${o}`:void 0;for(let o of t?.products??[]){let a=i(o.code);a&&r.set(a,o)}let s=(e.products??[]).map(o=>{let a=i(o.code),l=a?r.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:s}}};R.activeVaultCaptureRequests=new Map,R.pendingThreeDsAbandonReports=new Map;var N=R;function en(n,e){let t=N;return new t(n,e)}import{buildCardFieldLabelsPayload as yr,buildTelemetryErrorEvent as gr,buildTelemetryLogEvent as fr,buildTelemetryTerminalEvent as Ze,FloPayError as Qe,resolveBillingApiUrl as ae,SDK_VERSION as Xe,THREE_DS_CHALLENGE_WINDOW_MS as vr}from"@flopay/shared";import{invokeMerchantCallback as mr,resolveCardFieldsTimeoutMs as pr}from"@flopay/shared";function Je(n){if(!n)return null;try{let e=new URL(n,window.location.href);return e.origin==="null"?null:e.origin}catch{return null}}var W=class{constructor(e){this.options=e;this.handlers=new Set;this.active=!1;this.readyReported=!1;this.failureReported=!1;this.startedAt=0;this.timer=null;this.detach=null}subscribe(e){return this.handlers.add(e),()=>{this.handlers.delete(e)}}begin(){this.end(),this.active=!0,this.readyReported=!1,this.failureReported=!1,this.startedAt=this.options.now();let e=pr(this.options.timeoutMs);this.timer=setTimeout(()=>{this.timer=null,this.reportFailure("timeout",e)},e)}watch(e){if(!this.active)return;this.detachWatchers();let t=new Set,r=[];for(let s of Array.from(e.querySelectorAll("script[src], iframe[src]"))){let o=Je(s.getAttribute("src"));if(o&&t.add(o),s.tagName==="SCRIPT"){let a=()=>this.fail("load_error");s.addEventListener("error",a),r.push(()=>s.removeEventListener("error",a))}}let i=s=>{let o=Je(s.blockedURI);o&&t.has(o)&&this.fail("blocked")};document.addEventListener("securitypolicyviolation",i),r.push(()=>document.removeEventListener("securitypolicyviolation",i)),this.detach=()=>{for(let s of r)s()}}ready(){!this.active||this.readyReported||(this.readyReported=!0,this.clearTimer(),this.detachWatchers(),this.dispatch({type:"card_fields_ready",elapsedMs:this.elapsed()}))}fail(e){this.reportFailure(e,0)}reportFailure(e,t){!this.active||this.readyReported||this.failureReported||(this.failureReported=!0,this.clearTimer(),this.dispatch({type:"card_fields_failed",reason:e,elapsedMs:Math.max(t,this.elapsed())}))}end(){this.active=!1,this.clearTimer(),this.detachWatchers()}elapsed(){return Math.max(0,Math.round(this.options.now()-this.startedAt))}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}detachWatchers(){this.detach?.(),this.detach=null}dispatch(e){try{this.options.report?.(e)}catch{}for(let t of Array.from(this.handlers))mr(()=>t(e))}};var Cr=4,J="flopay-vault",Tr=3e4,br=vr+Tr,_r="Card authentication timed out.",et={ready:["vault.widget.ready","vault_ready"],submitting:["vault.submission.started","vault_submit"],blocked:["operation.state_transition","vault_submit"],action_required:["vault.action.required","three_ds_handoff"]};function Rr(n){return n.class==="lifecycle"?n.name:n.class==="technical_error"?n.code:n.class==="expected_outcome"?n.outcome:"sdk.performance"}function P(n){let e={class:n.class,stage:n.stage};"code"in n&&(e.code=n.code),"provider"in n&&n.provider&&(e.provider=n.provider),"paymentMethodCategory"in n&&n.paymentMethodCategory&&(e.paymentMethodCategory=n.paymentMethodCategory),"outcome"in n&&(e.outcome=n.outcome),"durationMs"in n&&n.durationMs!==void 0&&(e.durationMs=n.durationMs),"durationMode"in n&&n.durationMode&&(e.durationMode=n.durationMode);try{globalThis.Sentry?.addBreadcrumb?.({category:"flopay.telemetry",level:n.class==="technical_error"?"error":"info",message:Rr(n),data:e})}catch{}}function V(n,e){return fr({eventId:"11111111-1111-4111-8111-111111111111",name:n,stage:e,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}var Sr=new Set(["authorization_declined","authentication_required","authorization_expired","capture_failed"]);function Ar(n){return typeof n=="string"&&Sr.has(n)?n:"unknown"}var wr=new Set(["verification_failed","verification_expired"]);function Er(n){return n==null?!0:typeof n=="string"&&wr.has(n)}var kr="vault_mount";function Mr(n){return n.failureStage===kr}function le(n,e){return n&&!Mr(e)?{errorCode:"VAULT_SUBMIT_FAILED",stage:"vault_submit",failureCategory:"provider_runtime",reason:Ar(e.failureOutcome)}:{errorCode:"VAULT_LOAD_FAILED",stage:"vault_mount",failureCategory:"provider_runtime"}}function tt(n,e,t="checkout"){return t==="card_setup"?n.type==="decline"?"card_setup_declined":"card_setup_succeeded":n.type==="decline"?"payment_declined":n.outcome==="authorized"||e==="manual"?"payment_authorized":"payment_succeeded"}function Ir(n,e,t,r="checkout"){let{type:i}=n;if(i==="complete"||i==="decline")return Ze({eventId:"22222222-2222-4222-8222-222222222222",outcome:tt(n,t,r),sequence:0,provider:"pcivault",paymentMethodCategory:"card"});if(i==="error"){let a=le(e,n);return gr({eventId:"33333333-3333-4333-8333-333333333333",...a,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}let[s,o]=et[i];return V(s,o)}function Dr(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===J&&(e.type==="ready"||e.type==="submitting"||e.type==="blocked"||e.type==="complete"||e.type==="decline"||e.type==="error"||e.type==="action_required")}function Pr(n){if(typeof n!="object"||n===null)return;let e=n;if(typeof e.code!="string"||e.code.trim()==="")return;let t=typeof e.message=="string"&&e.message.trim()!==""?e.message:void 0;return t?{code:e.code,message:t}:{code:e.code}}function Fr(n){if(typeof n!="object"||n===null)return;let e=n,t=e.status;if(!(typeof e.id!="string"||e.id.trim()===""||typeof e.brand!="string"||e.brand.trim()===""||typeof e.lastFour!="string"||!/^\d{4}$/.test(e.lastFour)||typeof e.expiryMonth!="number"||!Number.isInteger(e.expiryMonth)||e.expiryMonth<1||e.expiryMonth>12||typeof e.expiryYear!="number"||!Number.isInteger(e.expiryYear)||e.expiryYear<1970||e.expiryYear>9999||t!=="pending"&&t!=="active"&&t!=="deleted"))return{id:e.id,brand:e.brand,lastFour:e.lastFour,expiryMonth:e.expiryMonth,expiryYear:e.expiryYear,status:t}}function Or(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===J&&e.type==="validation"&&Array.isArray(e.messages)}function xr(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===J&&e.type==="resize"&&typeof e.height=="number"&&Number.isFinite(e.height)}function Ur(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===J&&e.type==="fields_interactive"}function Lr(n){let e=n.capabilities;return Array.isArray(e)&&e.includes("fields_interactive")}var qr=["number","expiry","cvv","name"];function Nr(n){if(n===null||typeof n!="object")return;let e=n,t={};for(let r of qr){let i=e[r];typeof i=="string"&&(t[r]=i)}return t}var de=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.actionChallengeIntentId=null;this.messageToken=null;this.expectedOrigin=null;this.theme=void 0;this.submitGateBlocked=!1;this.cardFieldOrder=null;this.cardAutoFocus=!0;this.cardBrandIcons=!1;this.showCardFieldLabels=void 0;this.cardFieldLabels=void 0;this.submitLabel=void 0;this.cardFieldPlaceholders=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.cardFields=new W({timeoutMs:e.cardFieldsTimeoutMs,now:()=>this.telemetryReporter?.now?.()??_(),report:r=>this.reportCardFields(r)}),this.ownsTelemetryReporter=!t&&e.telemetry!==!1,this.telemetryReporter=t?.reporter??(this.ownsTelemetryReporter?new w({billingApiUrl:ae(e.billingApiUrl),sdkVersion:Xe}):void 0)}async mount(e,t){this.ownsTelemetryReporter&&!this.telemetryReporter&&(this.telemetryReporter=new w({billingApiUrl:ae(this.config.billingApiUrl),sdkVersion:Xe}));let r=this.telemetryReporter;if(this.config.operation==="card_setup"&&r&&this.setupTelemetryReporter!==r){this.setupTelemetryReporter=r;try{r.beginCheckout({checkoutMode:"setup"})}catch{}}if(this.mountStartedAt=this.telemetryReporter?.now?.()??_(),this.vaultReadyReported=!1,this.submissionStarted=!1,this.submissionStartedAt=null,this.cardFields.begin(),typeof window>"u"||typeof document>"u")throw this.reportVaultLoadFailure(),this.failCardFieldsMount(),new Qe("The vault card form is only available in the browser.","api_error",{code:"card_capture_no_window"});if(!t?.html?.trim())throw this.reportVaultLoadFailure(),this.failCardFieldsMount(),new Qe("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),this.cardFields.watch(e)}catch(i){throw this.reportVaultLoadFailure(),this.failCardFieldsMount(),i}this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),this.postCardBrandIcons(),this.postCardFieldLabels(),this.postCardFieldPlaceholders(),this.postSubmitLabel(),P(V("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 r=this.listeners.get(e);return r||(r=new Set,this.listeners.set(e,r)),r.add(t),()=>{this.listeners.get(e)?.delete(t)}}onCardFields(e){return this.cardFields.subscribe(e)}failCardFieldsMount(){this.cardFields.fail("other"),this.cardFields.end()}reportCardFields(e){let t=e.type==="card_fields_ready",r=this.config.sessionId;this.telemetryReporter?.log({name:t?"vault.fields.ready":"vault.fields.failed",stage:t?"vault_ready":"vault_mount",provider:"pcivault",paymentMethodCategory:"card",elapsedMs:e.elapsedMs,...e.type==="card_fields_failed"?{loadFailureReason:e.reason}:{},...r?{checkoutSessionId:r}:{}})}unmount(){if(this.cardFields.end(),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 r=Array.from(e.querySelectorAll("script"));for(let i of r){let s=document.createElement("script");for(let o of Array.from(i.attributes))s.setAttribute(o.name,o.value);s.text=i.text,i.replaceWith(s)}}attachMessageListener(){if(this.messageHandler)return;let e=t=>{if(this.expectedOrigin&&t.origin!==this.expectedOrigin)return;let r=t.data;if(xr(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;this.applyHeight(r.height);return}if(Or(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;let d=r.messages.filter(c=>typeof c=="string"&&c.trim()).join(" ");this.emit("validation",{sessionId:this.config.sessionId,message:d||void 0});return}if(Ur(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;let d=typeof r.sessionId=="string"?r.sessionId:void 0;if(this.config.sessionId&&d&&d!==this.config.sessionId)return;this.cardFields.ready();return}if(!Dr(r)||this.messageToken&&r.messageToken!==this.messageToken)return;let i=this.config.sessionId,s=typeof r.sessionId=="string"?r.sessionId:void 0;if(i&&s&&s!==i||(r.type==="complete"||r.type==="decline")&&i&&s!==i)return;let o=Fr(r.paymentMethod),a=Pr(r.vaultOutcome),l={...r.sessionId??this.config.sessionId?{sessionId:r.sessionId??this.config.sessionId}:{},...r.outcome?{outcome:r.outcome}:{},...r.paymentId?{paymentId:r.paymentId}:{},...r.authorizationExpiresAt?{authorizationExpiresAt:r.authorizationExpiresAt}:{},...r.failureOutcome?{failureOutcome:r.failureOutcome}:{},...r.intentId?{intentId:r.intentId}:{},...r.declineReason?{declineReason:r.declineReason}:{},...r.message?{message:r.message}:{},...a?{vaultOutcome:a}:{},...o?{paymentMethod:o}:{}};r.type==="submitting"&&(this.submissionStarted=!0,this.submissionStartedAt=this.telemetryReporter?.now?.()??_()),this.isVerificationStateError(r)?(P(V("operation.state_transition","vault_mount")),this.telemetryReporter?.log({name:"operation.state_transition",stage:"vault_mount",provider:"pcivault",paymentMethodCategory:"card"})):(P(Ir(r,this.submissionStarted,this.config.captureMethod,this.config.operation)),this.reportOutcome(r),r.type==="error"&&le(this.submissionStarted,r).errorCode==="VAULT_LOAD_FAILED"&&this.cardFields.fail("load_error")),r.type==="ready"&&(this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),this.postCardBrandIcons(),this.postCardFieldLabels(),this.postCardFieldPlaceholders(),this.postSubmitLabel(),Lr(r)||this.cardFields.ready()),r.type==="action_required"&&r.nextActionRedirectUrl&&(this.showActionRequiredOverlay(r.nextActionRedirectUrl),this.actionOverlay&&typeof r.intentId=="string"&&r.intentId&&(this.actionChallengeIntentId=r.intentId)),(r.type==="complete"||r.type==="decline"||r.type==="error"||r.type==="submitting")&&(this.endActionChallengeFromWidget(r.type),this.hideActionRequiredOverlay()),r.type!=="action_required"&&this.emit(r.type,l)};this.messageHandler=e,window.addEventListener("message",e)}isVerificationStateError(e){return e.type==="error"&&this.verificationRequired&&!this.submissionStarted&&Er(e.failureOutcome)}reportOutcome(e){let t=this.telemetryReporter;if(!t)return;let{type:r}=e;if(r==="ready"&&!this.vaultReadyReported&&(this.vaultReadyReported=!0,t.performance({stage:"vault_ready",durationMs:Math.max(0,t.now()-this.mountStartedAt),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card",requestCategory:"provider_sdk"})),r==="complete"||r==="decline"){t.log({name:"vault.terminal",stage:"completion",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:tt(e,this.config.captureMethod,this.config.operation),provider:"pcivault",paymentMethodCategory:"card"});return}if(r==="error"){let o=le(this.submissionStarted,e);t.log({name:"vault.terminal",stage:o.stage,provider:"pcivault",paymentMethodCategory:"card"}),t.error({...o,provider:"pcivault",paymentMethodCategory:"card"});return}if(r==="action_required"){t.log({name:"vault.action.required",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"}),t.log({name:"vault.three_ds.handoff",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"});let 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[i,s]=et[r];t.log({name:i,stage:s,provider:"pcivault",paymentMethodCategory:"card"})}applyTheme(e){this.theme=e,this.postTheme()}postTheme(){this.theme!==void 0&&this.postToHostedWindow({source:"flopay-vault-host",type:"theme",theme:this.theme},this.directiveTargetOrigin())}setSubmitGate(e){this.submitGateBlocked=e,this.postSubmitGate()}postSubmitGate(){this.postToHostedWindow({source:"flopay-vault-host",type:"gate",blocked:this.submitGateBlocked},this.directiveTargetOrigin())}setCardFieldOrder(e,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())}setCardBrandIcons(e){this.cardBrandIcons=e===!0,this.postCardBrandIcons()}setShowCardFieldLabels(e){this.showCardFieldLabels=e===!0,this.postCardFieldLabels()}setCardFieldLabels(e){this.cardFieldLabels=yr(e),this.postCardFieldLabels()}postCardFieldLabels(){let e=this.showCardFieldLabels,t=this.cardFieldLabels;if(e===void 0&&t===void 0)return;let r=this.config.sessionId,{messageToken:i,expectedOrigin:s}=this;!r||!i||!s||this.postToHostedWindow({source:"flopay-vault-host",type:"cardFieldLabels",sessionId:r,messageToken:i,...e===void 0?{}:{show:e},...t===void 0?{}:{labels:{...t}}},s)}setCardFieldPlaceholders(e){let t=Nr(e),r=t===void 0&&this.cardFieldPlaceholders!==void 0;this.cardFieldPlaceholders=t,this.postCardFieldPlaceholders(r?{}:t)}postCardFieldPlaceholders(e=this.cardFieldPlaceholders){let t=this.config.sessionId,{messageToken:r,expectedOrigin:i}=this;e===void 0||!t||!r||!i||this.postToHostedWindow({source:"flopay-vault-host",type:"cardFieldPlaceholders",sessionId:t,messageToken:r,placeholders:{...e}},i)}postCardBrandIcons(){this.postToHostedWindow({source:"flopay-vault-host",type:"cardBrandIcons",show:this.cardBrandIcons},this.directiveTargetOrigin())}setSubmitLabel(e){this.submitLabel=e,this.postSubmitLabel()}postSubmitLabel(){let e=this.submitLabel,t=this.config.sessionId,{messageToken:r,expectedOrigin:i}=this;e===void 0||!t||!r||!i||this.postToHostedWindow({source:"flopay-vault-host",type:"submitLabel",sessionId:t,messageToken:r,label:e},i)}hostedWindow(){return this.container?.querySelector("iframe")?.contentWindow??null}postToHostedWindow(e,t){let r=this.hostedWindow();if(r)try{r.postMessage(e,t)}catch{}}directiveTargetOrigin(){return this.expectedOrigin??"*"}emit(e,t){for(let r of this.listeners.get(e)??[])r(t)}showActionRequiredOverlay(e){if(typeof document>"u")return;if(this.actionOverlay){let u=this.actionOverlay.querySelector("iframe");u instanceof HTMLIFrameElement&&u.src!==e&&(u.src=e),this.armActionRequiredTimeout();return}this.actionOverlayPreviousFocus=document.activeElement instanceof HTMLElement?document.activeElement:null;let t=ve(this.beginActionChallengeAttempt()),r=be(e),i=!1,s=u=>{if(i)return;let y=Te(u,r);y&&(i=!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",s),window.removeEventListener("pagehide",o)}};this.actionChallenge=a,this.lastChallengeTelemetry=t,t.record("handoff_planned"),ee(e)==="invalid"&&t.record("action_invalid",{reason:"invalid_url"}),document.addEventListener("securitypolicyviolation",s),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 d=document.createElement("iframe");d.setAttribute("title","Card authentication"),d.setAttribute("allow","payment"),d.tabIndex=0,d.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(";"),d.addEventListener("load",()=>{a.loaded||(a.loaded=!0,t.record("iframe_load",{evidenceBasis:"iframe_load_event"}))}),d.src=e,l.appendChild(d);let c=document.createElement("button");c.type="button",c.setAttribute("aria-label","Close card authentication"),c.textContent="\xD7",c.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(";"),c.addEventListener("click",()=>this.abandonActionRequiredOverlay()),l.appendChild(c),l.addEventListener("click",u=>{u.target===l&&this.abandonActionRequiredOverlay()});let p=0,h=u=>{let y=u.data,C=!!y&&typeof y=="object"&&y.source==="flopay-vault-3ds-return";if(u.source!==d.contentWindow){C&&p<Cr&&(p+=1,t.record("return_rejected",{reason:"untrusted_source",evidenceBasis:"message_origin_check"}));return}C&&(t.record("trusted_return",{evidenceBasis:"message_origin_check"}),t.terminal("trusted_return",{evidenceBasis:"message_origin_check"}),P(V("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",h),this.threeDsReturnHandler=h,t.record("render_attempted");try{document.body.appendChild(l)}catch(u){throw t.record("render_failed"),this.hideActionRequiredOverlay(),this.actionOverlayPreviousFocus=null,u}t.record("container_attached"),t.record("navigation_assigned");let m=Ce(l);m&&t.record("container_visibility",{reason:m,evidenceBasis:"parent_computed_style"}),this.actionOverlay=l,d.focus(),this.armActionRequiredTimeout(),P(V("vault.three_ds.handoff","three_ds_handoff"))}armActionRequiredTimeout(){this.actionOverlayTimer&&clearTimeout(this.actionOverlayTimer),this.actionOverlayTimer=setTimeout(()=>{this.actionOverlayTimer=null,this.actionOverlay&&this.timeOutActionRequiredOverlay()},br)}reportChallengeAbandoned(){P(Ze({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.closeAbandonedChallenge(),this.hideActionRequiredOverlay(),this.emit("error",{...this.config.sessionId?{sessionId:this.config.sessionId}:{},message:_r})}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.closeAbandonedChallenge(),this.hideActionRequiredOverlay(),this.emit("challenge_dismissed",{...this.config.sessionId?{sessionId:this.config.sessionId}:{}})}}closeAbandonedChallenge(){let e=this.actionChallengeIntentId;this.actionChallengeIntentId=null;let{sessionId:t,sessionToken:r}=this.config;if(!(!e||!t||!r))try{new N(ae(this.config.billingApiUrl),{telemetry:!1}).closeThreeDsChallenge(t,r,e).catch(()=>{})}catch{}}beginActionChallengeAttempt(){try{return this.telemetryReporter?.beginThreeDsChallenge?.()}catch{return}}endActionChallengeFromWidget(e){let t=this.actionChallenge,r=t?.telemetry??this.lastChallengeTelemetry;if(this.lastChallengeTelemetry=null,!!r){if(e==="submitting"){if(!t)return;r.record("abort_observed",{reason:"unspecified",evidenceBasis:"signal_reason"}),r.terminal("abort",{reason:"unspecified",evidenceBasis:"signal_reason"});return}t&&r.terminal("status_poll",{evidenceBasis:"server_status"}),e==="complete"&&r.reconcile("succeeded"),e==="decline"&&r.reconcile("declined")}}hideActionRequiredOverlay(){if(this.actionChallengeIntentId=null,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 r=Math.max(0,Math.min(Math.ceil(e),2e3));t.style.height=`${r}px`}};function cn(n,e){let t=de;return new t(n,{reporter:e})}export{me as a,pe as b,D as c,H as d,Z as e,ue as f,he as g,ve as h,ee as i,jr as j,Ce as k,Te as l,be as m,_ as n,w as o,sr as p,N as q,en as r,de as s,cn as t};