@flopay/js 1.16.7 → 1.17.1
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/README.md
CHANGED
|
@@ -132,7 +132,15 @@ posted only when the vault block supplied both `messageToken` and
|
|
|
132
132
|
{ source: 'flopay-vault-host', type: 'submitLabel', sessionId, messageToken, label }
|
|
133
133
|
```
|
|
134
134
|
|
|
135
|
-
A form mounted without those fields (an older billing API) keeps its default. The label is never added to telemetry. The other host directives (theme, submit gate, and
|
|
135
|
+
A form mounted without those fields (an older billing API) keeps its default. The label is never added to telemetry. The other host directives (theme, submit gate, field order, and card brand icons) also target the exact `expectedOrigin` when one was supplied, falling back to `'*'` only for a widget mounted without it. There is no host directive for authentication: the hosted form accepts no completion signal from the page, because the outcome of a challenge is resolved server-side.
|
|
136
|
+
|
|
137
|
+
`capture.setCardBrandIcons(show)` shows or hides the Visa, Mastercard, Amex and Discover icons in the hosted card number field, live and without remounting. Only `true` turns them on; the default is `false`, so a form whose host never calls it is unchanged. The adapter posts the setting with the initial directives at mount and replays the latest value on every `ready`:
|
|
138
|
+
|
|
139
|
+
```ts
|
|
140
|
+
{ source: 'flopay-vault-host', type: 'cardBrandIcons', show }
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
The hosted form narrows the icons to the brand the buyer types; no brand is reported back to the page. A hosted form that predates the icons ignores the directive.
|
|
136
144
|
|
|
137
145
|
### Card-field lifecycle
|
|
138
146
|
|
|
@@ -384,6 +392,7 @@ await api.reportSessionIntentDecline('session_uuid', 'session_nonce', {
|
|
|
384
392
|
| `applyTheme(theme)` | Re-skins the mounted form; `null` is the classic reset |
|
|
385
393
|
| `setSubmitGate(blocked)` | While `blocked`, the hosted form cancels its next submit and emits `blocked` so the host can validate its own fields (such as AVS) first |
|
|
386
394
|
| `setCardFieldOrder(order, autoFocus)` | Reorders the hosted card rows (`name`, `number`, `expiry`); the first row is focused unless `autoFocus` is false |
|
|
395
|
+
| `setCardBrandIcons(show)` | Shows the Visa, Mastercard, Amex and Discover icons in the hosted card number field when `show` is `true`; off by default |
|
|
387
396
|
| `setSubmitLabel(label)` | Sets the hosted submit wording live; `null` restores the session default |
|
|
388
397
|
|
|
389
398
|
## Errors
|
package/dist/card-setup.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var J=Object.defineProperty;var Ne=Object.getOwnPropertyDescriptor;var Ve=Object.getOwnPropertyNames;var Be=Object.prototype.hasOwnProperty;var ze=(r,e)=>{for(var t in e)J(r,t,{get:e[t],enumerable:!0})},He=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Ve(e))!Be.call(r,i)&&i!==t&&J(r,i,{get:()=>e[i],enumerable:!(n=Ne(e,i))||n.enumerable});return r};var je=r=>He(J({},"__esModule",{value:!0}),r);var Jt={};ze(Jt,{PaymentAPI:()=>j,PciVaultCardCapture:()=>$,clearSetupRedirectParams:()=>Oe,readSetupRedirectReturn:()=>De});module.exports=je(Jt);var l=require("@flopay/shared");function se(r){return typeof r=="string"&&r.trim()?r:void 0}function oe(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 P(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 Ge(){return Object.assign(new Error("The operation was aborted."),{name:"AbortError"})}function q(r,e){let t=150*2**r,n=Math.round(t*(.75+Math.random()*.5));return new Promise((i,s)=>{let o,a=()=>e.removeEventListener("abort",c),c=()=>{o!==void 0&&clearTimeout(o),a(),s(Ge())};if(e.aborted){c();return}o=setTimeout(()=>{a(),i()},n),e.addEventListener("abort",c,{once:!0})})}var Ke="flopay_session_display:";var L=new Map;function N(r){return`${Ke}${r}`}function Q(){if(typeof window>"u")return null;try{return window.sessionStorage}catch{return null}}function X(r,e,t){if(!r)return;let n=t?.ttlMs??36e5,i={data:e,expiresAt:Date.now()+n},s=Q();if(s)try{s.setItem(N(r),JSON.stringify(i));return}catch{}L.set(r,i)}function ae(r){if(!r)return null;let e=Q();if(e)try{let n=e.getItem(N(r));if(n){let i=JSON.parse(n);if(i&&typeof i.expiresAt=="number"&&i.expiresAt>Date.now())return i.data;e.removeItem(N(r))}}catch{}let t=L.get(r);if(t){if(t.expiresAt>Date.now())return t.data;L.delete(r)}return null}function le(r){if(!r)return;L.delete(r);let e=Q();if(e)try{e.removeItem(N(r))}catch{}}var b=require("@flopay/shared");var Z=require("@flopay/shared"),$e=32,ce=Symbol.for("@flopay/js.three-ds-challenge.attempts.v1");function Ye(){let r=globalThis,e=r[ce];if(e instanceof Map)return e;let t=new Map;try{Object.defineProperty(r,ce,{configurable:!0,enumerable:!1,writable:!1,value:t})}catch{}return t}function We(r,e){let t=Ye(),n=t.get(r);if(n)return n;for(;t.size>=$e;){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(r,i),i}var Je=new Set(["pagehide_observed","cancel_requested","abort_observed","browser_terminal"]),Qe=new Set(["teardown","recovery_read_completed","provider_reconciled"]);function de(r,e={}){let t=(0,Z.isThreeDsChallengeAttemptId)(e.attemptId)?e.attemptId.toLowerCase():r.newAttemptId(),n=()=>{try{let a=r.now();return Number.isFinite(a)?a:0}catch{return 0}},i=We(t,n());(e.provider==="stripe"||e.provider==="worldpay")&&(i.provider=e.provider);let s=i.provider,o=(a,c)=>{if(i.terminated&&!Qe.has(a))return;let d={attemptId:t,phase:a,attemptSequence:i.nextSequence,elapsedMs:Math.max(0,n()-i.startedAt),provider:s};i.nextSequence+=1,c.reason!==void 0&&(d.reason=c.reason),c.evidenceBasis!==void 0&&(d.evidenceBasis=c.evidenceBasis),c.terminalSource!==void 0&&(d.terminalSource=c.terminalSource),c.providerOutcome!==void 0&&(d.providerOutcome=c.providerOutcome);try{r.emit(d,Je.has(a))}catch{}};return{attemptId:t,record(a,c={}){a==="browser_terminal"||a==="provider_reconciled"||o(a,{reason:c.reason,evidenceBasis:c.evidenceBasis})},terminal(a,c={}){i.terminated||(o("browser_terminal",{terminalSource:a,reason:c.reason,evidenceBasis:c.evidenceBasis}),i.terminated=!0)},reconcile(a){i.reconciled.has(a)||(i.reconciled.add(a),o("provider_reconciled",{providerOutcome:a,evidenceBasis:"provider_fact"}))}}}function ue(r){let e=null;try{e=(0,Z.isThreeDsChallengeAttemptId)(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 ee(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 he(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 me(r,e){if(!e)return null;try{let t=r,n=String(t.effectiveDirective||t.violatedDirective||"").trim().split(/\s+/)[0],i=null;return n==="frame-src"&&(i="frame_src"),n==="child-src"&&(i="child_src"),!i||typeof t.blockedURI!="string"?null:new URL(t.blockedURI).origin===e?i:null}catch{return null}}function pe(r){try{return ee(r)==="valid"?new URL(r).origin:null}catch{return null}}var Xe="/v1/sdk-telemetry/events",V=16,ye=64,Ze=1500,ge=1e3,et=64,tt="00000000-0000-4000-8000-000000000000",rt={technical_error:8,lifecycle:32,expected_outcome:32,performance:24},nt=48;function w(){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 it(r){try{return new TextEncoder().encode(r).byteLength}catch{return r.length}}function st(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 R(){return globalThis.performance?.now()??0}var E=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(/\/+$/,"")}${Xe}`,this.sdkPackage=e.sdkPackage??"@flopay/js",this.sdkVersion=e.sdkVersion,this.correlationId=w(),this.merchantEnabled=e.enabled!==!1,this.clock=e.clock??R,this.browserTransportAvailable=typeof window<"u"&&typeof document<"u",this.browserTransportAvailable&&(window.addEventListener("pagehide",this.pageExitHandler),document.addEventListener("visibilitychange",this.visibilityHandler))}log(e){this.notify({...e,class:"lifecycle"}),this.canCollect()&&this.enqueue((0,b.buildTelemetryLogEvent)({...this.checkoutContext,...e,eventId:w(),sequence:this.sequence++}))}error(e){if(this.notify({...e,class:"technical_error"}),!this.canCollect())return;let t=(0,b.buildTelemetryErrorEvent)({...this.checkoutContext,...e,eventId:tt,sequence:0}),n=st(t),i=this.now();this.pruneReportedFailures(i);let s=this.reportedFailures.get(n);if(s!==void 0&&i>=s&&i-s<ge){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,i),this.enqueue((0,b.buildTelemetryErrorEvent)({...this.checkoutContext,...e,eventId:w(),sequence:this.sequence++}))}performance(e){this.canCollect()&&this.enqueue((0,b.buildTelemetryPerformanceEvent)({...this.checkoutContext,...e,eventId:w(),sequence:this.sequence++}))}terminal(e){if(this.canCollect()&&(this.enqueue((0,b.buildTelemetryTerminalEvent)({...this.checkoutContext,...e,eventId:w(),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 de({now:()=>this.now(),newAttemptId:w,emit:(t,n)=>this.recordThreeDsChallenge(t,n)},e)}recordThreeDsChallenge(e,t){if(!this.canCollect()||this.threeDsChallengeCount>=nt)return;let n=(0,b.buildTelemetryLogEvent)({...this.checkoutContext,...e,name:"three_ds.challenge",stage:"three_ds_handoff",eventId:w(),sequence:this.sequence++});if(!(this.queue.length>=ye)){if(this.threeDsChallengeCount+=1,this.queue.push(n),t){this.drainQueue();return}if(this.queue.length>=V){this.flush();return}this.scheduleFlush()}}now(){try{return this.clock()}catch{return R()}}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>=ge)&&this.reportedFailures.delete(t)}rememberReportedFailure(e,t){for(;this.reportedFailures.size>=et;){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>=ye||this.eventCounts[e.class]>=rt[e.class])){if(this.eventCounts[e.class]+=1,this.queue.push(e),this.queue.length>=V){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,V);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,V);this.sendBatch(e)}}async sendBatch(e){if(!this.browserTransportAvailable||this.ingestionDisabled)return;let t=(0,b.serializeTelemetryBatch)(e,{correlationId:this.correlationId,sdkPackage:this.sdkPackage,sdkVersion:this.sdkVersion,batchId:w()});if(it(t)>b.TELEMETRY_MAX_BATCH_BYTES)return;let n=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:n?.signal}).then(async c=>{if(c.status!==202)return null;let d=null;try{d=await c.json()}catch{}return d?.status==="disabled"?"disabled":null}).catch(()=>null),o=new Promise(c=>{i=setTimeout(()=>{n?.abort(),c(null)},Ze)});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)}},fe=Symbol.for("@flopay/js.telemetry.reporter-factory.v1"),ve=globalThis;ve[fe]===void 0&&Object.defineProperty(ve,fe,{configurable:!0,enumerable:!1,writable:!1,value:r=>new E(r)});function ot(r){return r==="on_session"||r==="off_session"}function at(r){if(!r||typeof r!="object")return!1;let e=r;return typeof e.paymentMethodType=="string"&&typeof e.reason=="string"}function lt(r){let e=r.vaultOutcome;if(!(!e||e.code!==l.CHECKOUT_SESSION_BUYER_EMAIL_REQUIRED))return typeof e.message=="string"&&e.message.trim()!==""?e.message:void 0}var ct="x-flopay-process-result-source",dt="status",we=new WeakSet;function ut(r,e){let t=new l.FloPayError(r,"api_error",{code:e,statusCode:500});return we.add(t),t}function ht(r){return typeof r=="object"&&r!==null&&we.has(r)}function Ce(r){return r?.result==="DECLINE"||r?.result==="ERROR"}var mt=50,M=new Map;function pt(r,e){return M.get(r)?.has(e)===!0}function yt(r,e){let t=M.get(r)??new Set;if(t.add(e),M.delete(r),M.set(r,t),M.size>mt){let n=M.keys().next().value;n!==void 0&&M.delete(n)}}function gt(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 Te=0,be=500,B=15e3,_e=15e3,ft=3e3,vt=1e4,Ct=1e4;function x(r){return typeof r=="object"&&r!==null}function k(r,e){return se(r?.[e])}function Se(r,e){return oe(r?.[e])}function Tt(r,e){let t=r?.[e];return typeof t=="number"&&Number.isFinite(t)?t:void 0}function re(r,e){return e?new Promise((t,n)=>{let i=()=>{clearTimeout(s),n(e.reason??Object.assign(new Error("The operation was aborted."),{name:"AbortError"}))},s=setTimeout(()=>{e.removeEventListener("abort",i),t()},r);e.aborted?i():e.addEventListener("abort",i,{once:!0})}):new Promise(t=>setTimeout(t,r))}function te(r){return r instanceof Error&&r.name==="AbortError"}function S(){return new l.FloPayError(l.CHECKOUT_PROCESSING_TIMEOUT_MESSAGE,"api_error",{code:"checkout_processing_timeout"})}async function A(r,e){let t=await r.json().catch(()=>null),n=x(t?.error)?t.error:null,i=Se(t,"message")??Se(n,"message")??e,s=k(t,"code")??k(t,"gatewayErrorCode")??k(n,"code")??`http_${r.status}`;return(0,l.withTelemetryHttpDiagnostics)(new l.FloPayError(i,"api_error",{code:s,statusCode:r.status}),r)}async function bt(r){if(r.status!==403)return!1;let e=await r.clone().json().catch(()=>null),t=x(e?.error)?e.error:null;return(k(e,"code")??k(t,"code"))==="verification_required"}function _t(r){if(!(!x(r)||typeof r.required!="boolean"))return{required:r.required,provider:"turnstile"}}async function St(r){let e=r.status===400?await r.clone().json().catch(()=>null):null;return(0,l.classifyPaymentRejection)(r.status,e)}function Re(r){return r===400||r===422}var H=2;async function z(r,e,t=H,n,i){let s;for(let o=0;;o++)try{return i?.(o),await fetch(r,e)}catch(a){if(e?.signal?.aborted||a instanceof Error&&a.name==="AbortError")throw a;if(s=a,o>=t)throw s;try{n?.(o+1)}catch{}await re(150*2**o,e?.signal??void 0)}}var Rt=Symbol.for("@flopay/js.session-create.telemetry.v1");function At(r){return r[Rt]}function wt(r){return"now"in r||"onFirstByte"in r||"onSessionCreateFailure"in r||"onRetry"in r}function Ee(r){let e=(0,l.isCardHolderNamePlaceholder)(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 ke(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 Et(r,e){let t={clientId:r.clientId,checkoutVersion:l.SDK_VERSION,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}),ke(t,r),t}function Ae(r,e,t){return{currency:e,products:t.map(n=>(0,l.buildProductPayload)(n,e)),couponCodes:r.couponCodes??[],accountData:Ee(r.account)}}function kt(r,e,t){return{currency:e,products:t.map(n=>(0,l.buildProductPayload)(n,e)),couponCodes:r.couponCodes??[]}}function Mt(r){let e={},t=(0,l.isCardHolderNamePlaceholder)(r.firstName,r.lastName);for(let[n,i]of Object.entries(r)){if(t&&n.endsWith("Name")||typeof i!="string")continue;let s=i.trim();s&&(e[n]=s)}return{accountData:e}}var I=class I{constructor(e,t={}){this.baseUrl=e.replace(/\/+$/,"");let n=wt(t);this.telemetryHooks=n?t:void 0,this.directTelemetry=n||t.telemetry===!1?void 0:new E({billingApiUrl:this.baseUrl,sdkVersion:l.SDK_VERSION})}destroy(){this.directTelemetry?.destroy()}reportDirectFailure(e,t,n,i,s="unknown"){let o=(0,l.classifyTelemetryFailure)(e,t);this.directTelemetry?.error({...o,...ht(e)?{reason:"capture_failed"}:{},stage:n,requestCategory:i,paymentMethodCategory:s})}reportAccountSnapshotFailure(e,t){let n=(0,l.classifyTelemetryFailure)(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()??R()}catch{return R()}}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,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 c={[l.FLO_SDK_VERSION_HEADER]:l.SDK_VERSION};t&&(c["x-checkout-session-token"]=t);let d=!1;try{let u=await z(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}`,{headers:c,signal:i},H,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()});d=!0;let p=Math.max(0,this.telemetryTimestamp()-o);try{this.telemetryHooks?.onFirstByte?.(p,a)}catch{}let h=`${Math.floor(u.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}),!u.ok)throw await A(u,"Failed to get checkout session");let f=await u.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}),{...f,data:this.mergeCachedDisplayData(f.data)}}catch(u){throw d&&(0,l.markSessionResponseReceived)(u),n&&this.directTelemetry?.error({...(0,l.classifyTelemetryFailure)(u,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"}),u}}cacheSessionDisplayData(e,t,n){X(e,t,n)}clearSessionDisplayData(e){le(e)}async getVaultCapture(e,t){let n=`${this.baseUrl}\0${e}\0${t??""}`,i=I.activeVaultCaptureRequests.get(n);if(i!==void 0)return i;let s=this.requestVaultCapture(e,t);I.activeVaultCaptureRequests.set(n,s);try{return await s}finally{I.activeVaultCaptureRequests.get(n)===s&&I.activeVaultCaptureRequests.delete(n)}}async requestVaultCapture(e,t){let n=new AbortController,i=setTimeout(()=>n.abort(),Ct);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 z(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/vault/capture`,{method:"POST",headers:o,signal:n.signal},H,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 bt(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 A(a,"Failed to load the secure card form");let c=await a.json();return this.directTelemetry?.performance({stage:"vault_request",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"2xx"}),this.toVaultBlock(c)}catch(a){let c=n.signal.aborted?new l.FloPayError("Timed out while loading the secure card form. Please try again.","api_error",{code:"vault_capture_timeout"}):a;throw this.reportDirectFailure(c,"VAULT_LOAD_FAILED","vault_request","vault_capture","card"),c}finally{clearTimeout(i)}}async getUnifiedCheckoutSession(e,t){let n=await this.getCheckoutSession(e,t);return this.normalizeCheckoutSessionResponse(n)}async getUnifiedCheckoutSessionForRecovery(e,t,n){let i=await this.fetchCheckoutSession(e,t,!1,n);return this.normalizeCheckoutSessionResponse(i)}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(0,l.markSessionResponseReceived)(t)}}async processPayment(e,t,n){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 l.FloPayError("processPayment requires `nonce` \u2014 pass the value returned from session creation.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let s=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.processing.started",stage:"processing",requestCategory:"process_payment",paymentMethodCategory:i});let{nonce:o,paymentMethodCategory:a,...c}=t,d=gt(t.tokenizedData),u,p;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(c)}),p=u}catch(h){if(te(h))throw this.reportDirectFailure(h,"PAYMENT_PROCESSING_FAILED","processing","process_payment",i),h;u=await this.reconcileProcessPayment(t.sessionId,{...n,nonce:o,paymentMethodCategory:i,submittedIntentId:d})}if(!u.ok&&u.status!==202){let h=await St(u);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:(0,l.telemetryStatusClass)(u.status),failureCategory:u.status>=500?"server_error":void 0,paymentMethodCategory:i,...(0,l.readTelemetryHttpDiagnostics)(p)}),u}try{let h=await this.resolveProcessResponse(u,t.sessionId,{...n,nonce:o,paymentMethodCategory:i,submittedIntentId:d});return this.directTelemetry?.log({name:"payment.processing.completed",stage:"processing",requestCategory:"process_payment",statusClass:(0,l.telemetryStatusClass)(h.status),paymentMethodCategory:i}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"process_payment",statusClass:(0,l.telemetryStatusClass)(h.status),paymentMethodCategory:i}),h}catch(h){throw h instanceof l.FloPayError&&h.code==="checkout_processing_timeout"||this.reportDirectFailure(h,"PAYMENT_PROCESSING_FAILED","processing","process_payment",i),h}}async patchAccountSnapshot(e,t,n,i){this.beginDirectTelemetryCheckout(e);let s=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.state_transition",stage:"processing",requestCategory:"account_snapshot"});let o=i?.timeoutMs??vt,a=new AbortController,c=()=>a.abort();i?.signal&&(i.signal.aborted?a.abort():i.signal.addEventListener("abort",c,{once:!0}));let d=setTimeout(()=>a.abort(),o);try{let u;try{u=await z(`${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},H,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",c)}if(!u.ok)throw await A(u,"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(u){throw this.reportAccountSnapshotFailure(u,i?.telemetryMode??"blocking"),u}}async createSessionIntent(e,t,n,i){if(!t)throw new l.FloPayError("createSessionIntent requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let s=n,o=s.paymentMethodType,a=typeof o=="string"&&o.trim().toLowerCase()==="card",c=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"),u=s.provider==="paypal"&&s.paymentMethodCategory==="wallet"&&s.paymentMethodId===null&&(s.paymentMethodType==="paypal"&&s.intentKind==="payment"||s.paymentMethodType===l.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&(s.intentKind==="payment"||s.intentKind==="setup"));if(!c||!d&&!u)throw new l.FloPayError("Only wallet, APM, and PayPal session intents are supported.","validation_error",{code:"InvalidSessionIntentRequest"});let p=s.authorizationAttemptId;if(p!==void 0&&!(0,l.isUuidV4)(p))throw new l.FloPayError("authorizationAttemptId must be a v4 UUID identifying one buyer authorization attempt.","validation_error",{code:"InvalidAuthorizationAttemptId",param:"authorizationAttemptId"});let h=(0,l.isUuidV4)(p)?p:(0,l.randomUuidV4)();this.beginDirectTelemetryCheckout(e);let f=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,[l.IDEMPOTENCY_KEY_HEADER]:i?.idempotencyKey||h},g=!1;try{let v=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents`,{method:"POST",headers:m,body:JSON.stringify({...n,authorizationAttemptId:h}),signal:i?.signal});if(!v.ok){g=!0;let W=await A(v,"Failed to create checkout intent"),Le=(0,l.classifyTelemetryFailure)(W,"PAYMENT_PROCESSING_FAILED");throw Re(W.statusCode)?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"intent_create",statusClass:"4xx"}):this.directTelemetry?.error({...Le,stage:"processing",requestCategory:"intent_create"}),W}let C=await v.json();if(v.status===202&&x(C)&&C.type==="checkout_processing")return g=!0,await this.settleProcessingSessionIntent(C,v,e,t,n);let _=C.data;if(!_||typeof _!="object")throw new l.FloPayError("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});let y=_,ie=y.paymentMethodType,Fe=(y.paymentMethodCategory==="wallet"||y.paymentMethodCategory==="apm")&&typeof ie=="string"&&ie.trim().toLowerCase()!=="card"&&(typeof y.paymentMethodId=="string"||y.paymentMethodId===null)&&typeof y.providerObjectId=="string",xe=y.provider==="stripe"&&(y.intentKind==="payment"||y.intentKind==="setup")&&typeof y.clientSecret=="string",Ue=y.provider==="paypal"&&y.paymentMethodCategory==="wallet"&&y.paymentMethodId===null&&(y.paymentMethodType==="paypal"&&y.intentKind==="payment"&&(y.providerObjectType==="order"||y.providerObjectType==="subscription")||y.paymentMethodType===l.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&y.intentKind==="payment"&&y.providerObjectType==="order"||y.paymentMethodType===l.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&y.intentKind==="setup"&&y.providerObjectType==="setup_token")&&y.clientSecret===null,qe=y.provider===n.provider&&y.paymentMethodCategory===n.paymentMethodCategory&&y.paymentMethodType===n.paymentMethodType&&y.paymentMethodId===n.paymentMethodId&&y.intentKind===n.intentKind;if(!Fe||!xe&&!Ue||!qe)throw new l.FloPayError("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});return this.directTelemetry?.log({name:"payment.intent.completed",stage:"processing",requestCategory:"intent_create",statusClass:(0,l.telemetryStatusClass)(v.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-f),durationMode:"machine",requestCategory:"intent_create",statusClass:(0,l.telemetryStatusClass)(v.status)}),y}catch(v){throw g||this.reportDirectFailure(v,"PAYMENT_PROCESSING_FAILED","processing","intent_create"),v}}async settleProcessingSessionIntent(e,t,n,i,s){let o=this.toCheckoutProcessingPending(e,t,n);try{return{settled:!0,response:await this.resolveCheckoutProcessing(o,n,{nonce:i,paymentMethodCategory:s.provider==="paypal"?"paypal":s.paymentMethodCategory})}}catch(a){throw a instanceof l.FloPayError&&a.code==="checkout_processing_timeout"?new l.FloPayError(a.message,a.type,{code:a.code,statusCode:202,sessionId:o.sessionId,cause:a}):a}}async reportSessionIntentDecline(e,t,n,i){if(!t)throw new l.FloPayError("reportSessionIntentDecline requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let s=n,o=s.providerDeclineReason,a=s.paymentMethodType,c=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),u=typeof a=="string"&&a.length>0&&a.trim().toLowerCase()!=="card"&&d,p=s.provider==="stripe"&&(s.paymentMethodCategory==="wallet"||s.paymentMethodCategory==="apm")&&(c===void 0||typeof c=="string"&&/^pi_[a-z0-9_]{1,252}$/i.test(c)),h=s.provider==="paypal"&&s.paymentMethodCategory==="wallet"&&s.paymentMethodType==="paypal"&&c===void 0;if(!u||!p&&!h)throw new l.FloPayError("Invalid non-card decline classification.","validation_error",{code:"InvalidSessionIntentDeclineRequest"});let f=h?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:o}:{provider:"stripe",paymentMethodCategory:s.paymentMethodCategory,paymentMethodType:s.paymentMethodType,providerDeclineReason:o,...typeof c=="string"?{providerIntentId:c}:{}},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(f),signal:i?.signal});if(!m.ok)throw await A(m,"Failed to report checkout decline")}async resolvePaymentMethodLayout(e,t,n,i){if(!t)throw new l.FloPayError("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,[l.FLO_SDK_VERSION_HEADER]:l.SDK_VERSION},body:JSON.stringify(n),signal:i?.signal});if(s.status===404||s.status===405)return null;if(!s.ok)throw await A(s,"Failed to resolve the payment method layout");let o=await s.json();return(0,l.normalizePaymentMethodLayout)(o?.data)}async getPaymentsByEmail(e,t){this.beginDirectTelemetryOperation();let n=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(0,l.withTelemetryHttpDiagnostics)(new l.FloPayError("Failed to fetch payments","api_error",{statusCode:a.status}),a);let c=await a.json();return this.directTelemetry?.log({name:"operation.recovery.completed",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),this.directTelemetry?.performance({stage:"recovery",durationMs:Math.max(0,this.telemetryTimestamp()-n),durationMode:"machine",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),c}catch(a){throw this.reportDirectFailure(a,"RECOVERY_FAILED","recovery","other","saved"),a}}async createAndFetchSession(e){if((0,l.isDetachedSessionEligible)(e)){let s=e.account.email?.trim();if(s&&!(0,l.isValidEmail)(s))throw new l.FloPayError("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=P(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,n.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{n.clear()}}async createAndFetchSessionRequest(e,t,n){let i=e.products??(0,l.foldIntoProducts)(e.items,e.subscriptions);(0,l.assertCaptureMethodEligible)({captureMethod:e.captureMethod,products:i});let s=(0,l.resolveSessionCurrency)(e.currency,e.items,e.subscriptions,i);if(!s)throw new l.FloPayError("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});let o={clientId:e.clientId,checkoutVersion:l.SDK_VERSION,successUrl:e.successUrl,cancelUrl:e.cancelUrl,currency:s,checkoutMode:e.checkoutMode??"full",products:i.map(d=>(0,l.buildProductPayload)(d,s)),accountData:Ee(e.account),couponCodes:e.couponCodes??[]};e.captureMethod==="manual"&&(o.captureMethod=e.captureMethod),e.tokenizedData&&(o.tokenizedData=e.tokenizedData),ke(o,e);let a=await this.postCheckoutSessionCreate(o,e,t,n),c=!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),f=this.normalizeRawSession(h);return d.vault&&f.data.session&&(f.data.session.vault=this.toVaultBlock(d.vault)),{...f,autoProcessingError:d.autoProcessingError,autoProcessingAttempted:d.autoProcessingAttempted,autoProcessingPending:d.autoProcessingPending}}let u=d.data?.uuid;if(!u)throw new l.FloPayError("No session ID returned","api_error",{code:"InvalidCheckoutSessionResponse"});return this.autoCacheDisplayData(u,e),this.adoptDirectTelemetryCheckout(u),c=!0,{...await this.getUnifiedCheckoutSession(u),autoProcessingError:d.autoProcessingError,autoProcessingAttempted:d.autoProcessingAttempted,autoProcessingPending:d.autoProcessingPending}}catch(d){throw c?d:(0,l.markSessionResponseReceived)(d)}}async postCheckoutSessionCreate(e,t,n,i){let s={"Content-Type":"application/json",[l.FLO_SDK_VERSION_HEADER]:l.SDK_VERSION},o=(0,l.resolveIdempotencyKey)(t.idempotencyKey);o&&(s[l.IDEMPOTENCY_KEY_HEADER]=o),t.checkoutMode==="auto"&&(s[l.FLO_SDK_CAPABILITIES_HEADER]=l.ASYNC_AUTO_CHECKOUT_CAPABILITY);let a,c=!1,d=At(t),u=(h,f,m)=>{c||(c=!0,this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:m,attempt:h}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:Math.max(0,this.telemetryTimestamp()-f),durationMode:"machine",requestCategory:"session_create",statusClass:m,attempt:h}))},p=h=>{try{this.telemetryHooks?.onRetry?.("session_create",h),this.directTelemetry?.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:h})}catch{}};for(let h=0;h<3;h++){i.attempt=h;let f=this.telemetryTimestamp();try{d?.onAttempt?.(h)}catch{}try{a=await fetch(`${this.baseUrl}/v1/checkouts/sessions?expand=true`,{method:"POST",headers:s,body:JSON.stringify(e),signal:n})}catch(v){if(i.statusClass=n.aborted||v instanceof Error&&v.name==="AbortError"?"timeout":"network_error",n.aborted||v instanceof Error&&v.name==="AbortError"||h>=2)throw v;let C=h+1;p(C),await q(h,n);continue}let m=(0,l.telemetryStatusClass)(a.status);if(i.statusClass=m,a.status===204)throw u(h,f,m),new l.FloPayError("Session auto-completed \u2014 payment method already on file","api_error",{code:"session_auto_completed"});if(a.ok){u(h,f,m);break}let g=await A(a,"Failed to create checkout session");if(g.code===l.IDEMPOTENCY_IN_PROGRESS_CODE&&h<2){p(h+1),await q(h,n);continue}throw u(h,f,m),g}if(!a)throw new TypeError("Checkout-session creation exhausted its retry budget.");return a}async createDetachedSession(e){this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp(),n=P(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??(0,l.foldIntoProducts)(e.items,e.subscriptions);try{(0,l.assertCaptureMethodEligible)({captureMethod:e.captureMethod,products:s})}catch(C){throw n.clear(),this.reportSessionCreateFailure(C,t,i),C}let o=(0,l.resolveSessionCurrency)(e.currency,e.items,e.subscriptions,s);if(!o)throw n.clear(),this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),new l.FloPayError("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});try{Ae(e,o,s)}catch(C){throw n.clear(),this.reportSessionCreateFailure(C,t,i),C}let a,c,d=!1;try{let C=await this.postCheckoutSessionCreate(Et(e,o),e,n.signal,i);if(d=!0,c=await C.json(),!c.data||!("gateways"in c.data))throw new l.FloPayError("The billing API returned no session shell for a detached create. It must support `deferDataAttachment` (TeamFloPay/backend#1099).","api_error",{code:"InvalidCheckoutSessionResponse"});a=this.normalizeRawSession(this.mergeCachedDisplayData(c.data)),c.vault&&a.data.session&&(a.data.session.vault=this.toVaultBlock(c.vault))}catch(C){throw n.clear(),d&&(0,l.markSessionResponseReceived)(C),this.reportSessionCreateFailure(C,t,i),C}let u=a.data.session?.id??c.data.uuid??"",p=a.data.session?.clientSecret??c.data.nonce??"";if(!u||!p){n.clear();let C=new l.FloPayError("Checkout session shell was created without a session id or nonce.","api_error",{code:"InvalidCheckoutSessionResponse"});throw this.reportSessionCreateFailure(C,t,i),C}n.clear(),this.adoptDirectTelemetryCheckout(u),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(),f=P(e.timeoutMs??12e3),m=this.claimCheckoutSession(u,p,h?kt(e,o,s):Ae(e,o,s),{params:e,startedAt:t,deadline:f,createAttempt:i.attempt}),g=h?void 0:m,v=(C={})=>{if(g!==void 0)return g;let _={...e,account:{...e.account,...C,email:C.email?.trim()||e.account.email?.trim()}};return(0,l.isValidEmail)(_.account.email)?(g=m.then(()=>{let y=this.telemetryTimestamp();return this.claimCheckoutSession(u,p,Mt(_.account),{params:_,startedAt:y,deadline:P(e.timeoutMs??12e3),createAttempt:0})}),g.catch(()=>{}),g):Promise.reject(new l.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}))};return m.catch(()=>{}),{shell:a,sessionId:u,nonce:p,claimed:m,claim:v}}async claimCheckoutSession(e,t,n,i){let s=i?.startedAt??this.telemetryTimestamp(),o=this.telemetryTimestamp(),a=i?.deadline??P(12e3),c=JSON.stringify(n),d="unknown",u=0,p=!1;this.directTelemetry?.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"});try{let h;for(u=0;u<3;u++){try{h=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/claim`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":t,[l.FLO_SDK_VERSION_HEADER]:l.SDK_VERSION},body:c,signal:a.signal})}catch(g){let v=a.signal.aborted||g instanceof Error&&g.name==="AbortError";if(d=v?"timeout":"network_error",v||u>=2)throw g;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 q(u,a.signal);continue}if(d=(0,l.telemetryStatusClass)(h.status),h.ok)break;throw await A(h,"Failed to attach checkout session data")}if(!h)throw new TypeError("Checkout-session claim exhausted its retry budget.");p=!0;let f=await h.json();if(!f.data?.gateways)throw new l.FloPayError("The billing API returned no checkout session with gateways after claiming it.","api_error",{code:"InvalidCheckoutSessionResponse"});i?.params&&this.autoCacheDisplayData(f.data.uuid??e,i.params);let m=this.normalizeRawSession(this.mergeCachedDisplayData(f.data));return f.vault&&m.data.session&&(m.data.session.vault=this.toVaultBlock(f.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:u}),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??u}),m}catch(h){throw p&&(0,l.markSessionResponseReceived)(h),this.reportSessionCreateFailure(h,o,{attempt:u,statusClass:d},"session_claim"),h}finally{a.clear()}}reportSessionCreateFailure(e,t,n,i="session_create"){if(!(e instanceof l.FloPayError&&e.code==="session_auto_completed"))try{this.telemetryHooks?.onSessionCreateFailure?.(e)}catch{}let s=(0,l.classifyTelemetryFailure)(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:n.attempt}),e instanceof l.FloPayError&&e.type==="validation_error"||e instanceof l.FloPayError&&Re(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 l.FloPayError&&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 n=this.telemetryTimestamp(),i=t?.paymentMethodCategory??"saved";this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:i});let s=t?.timeoutMs??B,o=Date.now()+s,a=new AbortController,c=!1,d,u=setTimeout(()=>{d=setTimeout(()=>{c=!0,a.abort()},_e)},s),p=()=>a.abort(t?.signal?.reason);t?.signal?.aborted?p():t?.signal?.addEventListener("abort",p,{once:!0});let h=this.clampRetryAfterMs(t?.initialDelayMs??Te),f=0;try{if(t?.statusUrl){let m=await this.waitForCheckoutStatus(e,{initialDelayMs:h,timeoutMs:s,nonce:t.nonce,statusUrl:t.statusUrl,pollAfterAction:t.continueAfterActionRequired,signal:a.signal});if(m){let g=await this.resolveCheckoutSessionStatus(e,m,t.nonce,a.signal,()=>c);return this.reportRecoveryCompleted(n,i,t.challengeAttemptId),g}}for(;;){let m=o-Date.now();if(m<=0)throw S();if(h>0){try{f+=1,this.telemetryHooks?.onRetry?.("session_read",f),this.directTelemetry?.log({name:"operation.retry",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:i,attempt:f})}catch{}if(await re(Math.min(h,m),a.signal),Date.now()>=o)throw S()}let g=await this.getUnifiedCheckoutSessionForRecovery(e,t?.nonce,a.signal),v=g.data.session?.status;if(v==="authorized"||v==="complete"||v==="expired")return this.reportRecoveryCompleted(n,i,t?.challengeAttemptId),g;if(Date.now()>=o)throw S();h=this.clampRetryAfterMs(Math.max(h*2,be))}}catch(m){let g=c&&te(m)?S():m;throw this.reportDirectFailure(g,"RECOVERY_FAILED","recovery","session_read",i),g}finally{clearTimeout(u),clearTimeout(d),t?.signal?.removeEventListener("abort",p)}}reportRecoveryCompleted(e,t,n){let i={stage:"recovery",requestCategory:"session_read",paymentMethodCategory:t};if(this.directTelemetry?.log({name:"operation.recovery.completed",...i}),n)try{this.directTelemetry?.beginThreeDsChallenge({attemptId:n}).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,n,i,s){let o=t.latestTransactionAttempt;if(this.rememberReportedFailure(e,t),o?.result==="DECLINE"){let d=o.code===l.STORED_PAYMENT_METHOD_UNSUPPORTED_CODE;throw new l.FloPayError(d?l.STORED_PAYMENT_METHOD_UNSUPPORTED_MESSAGE:"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 ut("Payment could not be completed. Please try again.",o?.code??"payment_processing_error");let a;try{a=await this.getUnifiedCheckoutSessionForRecovery(e,n,i)}catch(d){if(!s?.()||!te(d))throw d;a={providers:[],mode:"tokenize",data:{},raw:t}}let c=a.data.session;return c&&o?.result==="SUCCESS"?{...a,data:{...a.data,session:{...c,status:"complete"}}}:c&&o?.result==="AUTHORIZED"?{...a,data:{...a.data,session:{...c,status:"authorized",paymentId:t.paymentId??void 0,authorizationExpiresAt:t.authorizationExpiresAt??void 0}}}:c&&t.status==="completed"?{...a,data:{...a.data,session:{...c,status:"complete"}}}:c&&t.status==="authorized"?{...a,data:{...a.data,session:{...c,status:"authorized",paymentId:t.paymentId??void 0,authorizationExpiresAt:t.authorizationExpiresAt??void 0}}}:c&&t.status==="expired"?{...a,data:{...a.data,session:{...c,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??B,i=Date.now()+n,s=this.clampRetryAfterMs(t.initialDelayMs);for(;;){let o=i-Date.now();if(o<=0||s>0&&(await re(Math.min(s,o),t.signal),Date.now()>=i))throw S();let a=i-Date.now();if(a<=0)throw S();let c=new AbortController,d,u=t.signal?new Promise((_,y)=>{d=y}):null,p=()=>{c.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,f=t.signal?null:new Promise((_,y)=>{h=setTimeout(()=>{y(S()),c.abort()},a+_e)}),m;try{let _=this.fetchCheckoutStatus(e,t.nonce,t.statusUrl,c.signal);m=await Promise.race([_,f,u].filter(y=>y!==null))}finally{h!==void 0&&clearTimeout(h),t.signal?.removeEventListener("abort",p)}if(!m)return null;let g=Ce(m.latestTransactionAttempt)&&!this.isOwnFailedAttempt(e,m,t.submittedIntentId);if(m.status==="completed"||m.status==="authorized"||m.status==="expired"||m.status==="voided")return g?{...m,latestTransactionAttempt:null}:m;let v=m.latestTransactionAttempt?.result,C=t.pollAfterAction===!0&&v==="ACTION_REQUIRED";if(!g&&v!==void 0&&v!=="PENDING"&&!C)return m;s=this.clampRetryAfterMs(Math.max(s*2,be))}}isOwnFailedAttempt(e,t,n){let i=t.latestTransactionAttempt?.providerIntentId??null;return n!==void 0?i===n:i===null?!0:!pt(t.uuid||e,i)}rememberReportedFailure(e,t){let n=t.latestTransactionAttempt;!Ce(n)||!n.providerIntentId||yt(t.uuid||e,n.providerIntentId)}async fetchCheckoutStatus(e,t,n,i){let s=`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/status`,o=s;if(n)try{let u=new URL(n,`${this.baseUrl}/`),p=new URL(s);u.origin===p.origin&&(o=u.toString())}catch{}let a={[l.FLO_SDK_VERSION_HEADER]:l.SDK_VERSION};t&&(a["x-checkout-session-token"]=t);let c=await z(o,{headers:a,signal:i});if(c.status===404||c.status===405)return null;if(!c.ok)throw await A(c,"Failed to get checkout session status");let d=await c.json();return x(d.data)&&"latestTransactionAttempt"in d.data?d.data:null}normalizeRawSession(e){let t=e.gateways??{},n=[],i={session:this.toCheckoutSession(e)},s=t.stripe;if(s?.publishableKey){n.push("stripe");let c=[e.stripeClientSecret,s.stripeClientSecret].find(d=>typeof d=="string"&&d.length>0);i.stripe={clientSecret:c??"",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&&(n.push("paypal"),i.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:i,raw:{data:e}}}toCheckoutSession(e){let t=e.products??[],n=typeof e.totalAmount=="number"&&Number.isFinite(e.totalAmount),i=t.reduce((d,u)=>d+(u.overrideAmount??u.totalAmount??0),0),s=n?e.totalAmount:i,o=Math.round(s*100),a=e.currency??t[0]?.currency??"USD",c="payment";return e.checkoutMode==="setup"?c="setup":t.some(d=>d.type==="subscription")&&(c="subscription"),{id:e.uuid,clientSecret:e.nonce,mode:c,status:this.toCheckoutSessionStatus(e.status),amount:o,currency:a,captureMethod:e.captureMethod,paymentId:e.paymentId,authorizationExpiresAt:e.authorizationExpiresAt,failureOutcome:(0,l.normalizeCheckoutFailureOutcome)(e.outcome)??(0,l.normalizeCheckoutFailureOutcome)(e.failureReason)??(e.status==="expired"&&e.captureMethod==="manual"?"authorization_expired":void 0),customer:{id:e.accountData.userId??void 0,email:e.accountData.email??void 0,firstName:e.accountData.firstName??void 0,lastName:e.accountData.lastName??void 0,country:e.accountData.country??void 0,city:e.accountData.city??void 0,state:e.accountData.state??void 0,zip:e.accountData.zip??void 0,gender:e.accountData.gender??void 0,line1:e.accountData.addressLine1??void 0,line2:e.accountData.addressLine2??void 0},...e.checkoutMetadata===void 0?{}:{checkoutMetadata:e.checkoutMetadata},metadata:{},checkoutMode:e.checkoutMode,...Array.isArray(e.advertisedPaymentMethods)?{advertisedPaymentMethods:e.advertisedPaymentMethods}:{},...ot(e.futureUse)?{futureUse:e.futureUse}:{},...Array.isArray(e.futureUseUnsupported)?{futureUseUnsupported:e.futureUseUnsupported.filter(at)}:{},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=_t(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 i=await e.json().catch(()=>null),s=this.toCheckoutProcessingPending(i,e,t);return this.resolveCheckoutProcessing(s,t,n)}async resolveCheckoutProcessing(e,t,n){let i=n?.pollTimeoutMs??B,s=Date.now()+i;if(e.statusUrl){let a=await this.waitForCheckoutStatus(e.sessionId,{initialDelayMs:e.retryAfterMs,timeoutMs:i,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:s-Date.now(),nonce:n?.nonce,paymentMethodCategory:n?.paymentMethodCategory});return this.toProcessResponseFromSession(o,t)}async toProcessResponseFromStatus(e,t,n){let i=e.latestTransactionAttempt?.result,s={[ct]:dt},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,n);return this.toProcessResponseFromSession(a,t)}if(this.rememberReportedFailure(t,e),i==="DECLINE"){let a=e.latestTransactionAttempt,c=a?.code===l.STORED_PAYMENT_METHOD_UNSUPPORTED_CODE,d=a?.declineReason??void 0;return new Response(JSON.stringify({type:d??"authorization_declined",message:c?l.STORED_PAYMENT_METHOD_UNSUPPORTED_MESSAGE:"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:lt(e)??"Payment could not be completed. Please try again."}),{status:500,headers:o});throw S()}async reconcileProcessPayment(e,t){let n=t?.pollTimeoutMs??B,i=Date.now()+n,s=null;try{s=await this.waitForCheckoutStatus(e,{initialDelayMs:0,timeoutMs:n,nonce:t?.nonce,submittedIntentId:t?.submittedIntentId})}catch(c){if(this.reportDirectFailure(c,"RECOVERY_FAILED","recovery","session_read",t?.paymentMethodCategory??"saved"),c instanceof l.FloPayError&&c.code==="checkout_processing_timeout")throw c}if(s)return this.toProcessResponseFromStatus(s,e,t?.nonce);let o=i-Date.now();if(o<=0)throw S();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 l.FloPayError(n?"Authorization has expired.":"Checkout session has expired.","api_error",{code:n?"authorization_expired":"checkout_session_expired"})}throw S()}toCheckoutProcessingPending(e,t,n){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")??n,retryAfterMs:this.clampRetryAfterMs(Tt(e,"retryAfterMs")??o??Te),statusUrl:k(e,"statusUrl"),sessionUrl:k(e,"sessionUrl")}}clampRetryAfterMs(e){return Math.max(0,Math.min(e,ft))}autoCacheDisplayData(e,t){if(!e)return;let n=t.products??(0,l.foldIntoProducts)(t.items,t.subscriptions);if(n.length===0&&!t.currency)return;let i=t.products!==void 0,s=(0,l.resolveSessionCurrency)(t.currency,i?void 0:t.items,i?void 0:t.subscriptions,n);X(e,{currency:s??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??s??void 0}))})}mergeCachedDisplayData(e){let t=ae(e.uuid),n=new Map,i=o=>o?`code:${o}`:void 0;for(let o of t?.products??[]){let a=i(o.code);a&&n.set(a,o)}let s=(e.products??[]).map(o=>{let a=i(o.code),c=a?n.get(a):void 0;return{...o,name:o.name??c?.name??null,totalAmount:o.totalAmount??c?.totalAmount,overrideAmount:o.overrideAmount??c?.overrideAmount,currency:o.currency??c?.currency}});return{...e,currency:e.currency??t?.currency,products:s}}};I.activeVaultCaptureRequests=new Map;var j=I;var T=require("@flopay/shared");var K=require("@flopay/shared");function Me(r){if(!r)return null;try{let e=new URL(r,window.location.href);return e.origin==="null"?null:e.origin}catch{return null}}var G=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=(0,K.resolveCardFieldsTimeoutMs)(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,n=[];for(let s of Array.from(e.querySelectorAll("script[src], iframe[src]"))){let o=Me(s.getAttribute("src"));if(o&&t.add(o),s.tagName==="SCRIPT"){let a=()=>this.fail("load_error");s.addEventListener("error",a),n.push(()=>s.removeEventListener("error",a))}}let i=s=>{let o=Me(s.blockedURI);o&&t.has(o)&&this.fail("blocked")};document.addEventListener("securitypolicyviolation",i),n.push(()=>document.removeEventListener("securitypolicyviolation",i)),this.detach=()=>{for(let s of n)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))(0,K.invokeMerchantCallback)(()=>t(e))}};var It=4,Y="flopay-vault",Pt=3e4,Dt=T.THREE_DS_CHALLENGE_WINDOW_MS+Pt,Ot="Card authentication timed out.",Ie={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 Ft(r){return r.class==="lifecycle"?r.name:r.class==="technical_error"?r.code:r.class==="expected_outcome"?r.outcome:"sdk.performance"}function D(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:Ft(r),data:e})}catch{}}function U(r,e){return(0,T.buildTelemetryLogEvent)({eventId:"11111111-1111-4111-8111-111111111111",name:r,stage:e,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}var xt=new Set(["authorization_declined","authentication_required","authorization_expired","capture_failed"]);function Ut(r){return typeof r=="string"&&xt.has(r)?r:"unknown"}var qt=new Set(["verification_failed","verification_expired"]);function Lt(r){return r==null?!0:typeof r=="string"&&qt.has(r)}var Nt="vault_mount";function Vt(r){return r.failureStage===Nt}function ne(r,e){return r&&!Vt(e)?{errorCode:"VAULT_SUBMIT_FAILED",stage:"vault_submit",failureCategory:"provider_runtime",reason:Ut(e.failureOutcome)}:{errorCode:"VAULT_LOAD_FAILED",stage:"vault_mount",failureCategory:"provider_runtime"}}function Pe(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 Bt(r,e,t,n="checkout"){let{type:i}=r;if(i==="complete"||i==="decline")return(0,T.buildTelemetryTerminalEvent)({eventId:"22222222-2222-4222-8222-222222222222",outcome:Pe(r,t,n),sequence:0,provider:"pcivault",paymentMethodCategory:"card"});if(i==="error"){let a=ne(e,r);return(0,T.buildTelemetryErrorEvent)({eventId:"33333333-3333-4333-8333-333333333333",...a,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}let[s,o]=Ie[i];return U(s,o)}function zt(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===Y&&(e.type==="ready"||e.type==="submitting"||e.type==="blocked"||e.type==="complete"||e.type==="decline"||e.type==="error"||e.type==="action_required")}function Ht(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 jt(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 Gt(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===Y&&e.type==="validation"&&Array.isArray(e.messages)}function Kt(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===Y&&e.type==="resize"&&typeof e.height=="number"&&Number.isFinite(e.height)}function $t(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===Y&&e.type==="fields_interactive"}function Yt(r){let e=r.capabilities;return Array.isArray(e)&&e.includes("fields_interactive")}var $=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.cardFields=new G({timeoutMs:e.cardFieldsTimeoutMs,now:()=>this.telemetryReporter?.now?.()??R(),report:n=>this.reportCardFields(n)}),this.ownsTelemetryReporter=!t&&e.telemetry!==!1,this.telemetryReporter=t?.reporter??(this.ownsTelemetryReporter?new E({billingApiUrl:(0,T.resolveBillingApiUrl)(e.billingApiUrl),sdkVersion:T.SDK_VERSION}):void 0)}async mount(e,t){this.ownsTelemetryReporter&&!this.telemetryReporter&&(this.telemetryReporter=new E({billingApiUrl:(0,T.resolveBillingApiUrl)(this.config.billingApiUrl),sdkVersion:T.SDK_VERSION}));let n=this.telemetryReporter;if(this.config.operation==="card_setup"&&n&&this.setupTelemetryReporter!==n){this.setupTelemetryReporter=n;try{n.beginCheckout({checkoutMode:"setup"})}catch{}}if(this.mountStartedAt=this.telemetryReporter?.now?.()??R(),this.vaultReadyReported=!1,this.submissionStarted=!1,this.submissionStartedAt=null,this.cardFields.begin(),typeof window>"u"||typeof document>"u")throw this.reportVaultLoadFailure(),this.failCardFieldsMount(),new T.FloPayError("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 T.FloPayError("No vault capture widget HTML was provided to mount the secure card form.","api_error",{code:"card_capture_no_widget_html"});this.container=e,this.verificationRequired=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.postSubmitLabel(),D(U("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?.()??R())-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)}}onCardFields(e){return this.cardFields.subscribe(e)}failCardFieldsMount(){this.cardFields.fail("other"),this.cardFields.end()}reportCardFields(e){let t=e.type==="card_fields_ready",n=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}:{},...n?{checkoutSessionId:n}:{}})}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 n=Array.from(e.querySelectorAll("script"));for(let i of n){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 n=t.data;if(Kt(n)){if(this.messageToken&&n.messageToken!==this.messageToken)return;this.applyHeight(n.height);return}if(Gt(n)){if(this.messageToken&&n.messageToken!==this.messageToken)return;let d=n.messages.filter(u=>typeof u=="string"&&u.trim()).join(" ");this.emit("validation",{sessionId:this.config.sessionId,message:d||void 0});return}if($t(n)){if(this.messageToken&&n.messageToken!==this.messageToken)return;let d=typeof n.sessionId=="string"?n.sessionId:void 0;if(this.config.sessionId&&d&&d!==this.config.sessionId)return;this.cardFields.ready();return}if(!zt(n)||this.messageToken&&n.messageToken!==this.messageToken)return;let i=this.config.sessionId,s=typeof n.sessionId=="string"?n.sessionId:void 0;if(i&&s&&s!==i||(n.type==="complete"||n.type==="decline")&&i&&s!==i)return;let o=jt(n.paymentMethod),a=Ht(n.vaultOutcome),c={...n.sessionId??this.config.sessionId?{sessionId:n.sessionId??this.config.sessionId}:{},...n.outcome?{outcome:n.outcome}:{},...n.paymentId?{paymentId:n.paymentId}:{},...n.authorizationExpiresAt?{authorizationExpiresAt:n.authorizationExpiresAt}:{},...n.failureOutcome?{failureOutcome:n.failureOutcome}:{},...n.intentId?{intentId:n.intentId}:{},...n.declineReason?{declineReason:n.declineReason}:{},...n.message?{message:n.message}:{},...a?{vaultOutcome:a}:{},...o?{paymentMethod:o}:{}};n.type==="submitting"&&(this.submissionStarted=!0,this.submissionStartedAt=this.telemetryReporter?.now?.()??R()),this.isVerificationStateError(n)?(D(U("operation.state_transition","vault_mount")),this.telemetryReporter?.log({name:"operation.state_transition",stage:"vault_mount",provider:"pcivault",paymentMethodCategory:"card"})):(D(Bt(n,this.submissionStarted,this.config.captureMethod,this.config.operation)),this.reportOutcome(n),n.type==="error"&&ne(this.submissionStarted,n).errorCode==="VAULT_LOAD_FAILED"&&this.cardFields.fail("load_error")),n.type==="ready"&&(this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),this.postSubmitLabel(),Yt(n)||this.cardFields.ready()),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,c)};this.messageHandler=e,window.addEventListener("message",e)}isVerificationStateError(e){return e.type==="error"&&this.verificationRequired&&!this.submissionStarted&&Lt(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:Pe(e,this.config.captureMethod,this.config.operation),provider:"pcivault",paymentMethodCategory:"card"});return}if(n==="error"){let o=ne(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[i,s]=Ie[n];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())}setSubmitLabel(e){this.submitLabel=e,this.postSubmitLabel()}postSubmitLabel(){let e=this.submitLabel,t=this.config.sessionId,{messageToken:n,expectedOrigin:i}=this;e===void 0||!t||!n||!i||this.postToHostedWindow({source:"flopay-vault-host",type:"submitLabel",sessionId:t,messageToken:n,label:e},i)}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=ue(this.beginActionChallengeAttempt()),n=pe(e),i=!1,s=m=>{if(i)return;let g=me(m,n);g&&(i=!0,t.record("policy_violation",{reason:g,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 c=document.createElement("div");c.setAttribute("data-flopay-action-required","1"),c.setAttribute("role","dialog"),c.setAttribute("aria-modal","true"),c.setAttribute("aria-label","Card authentication"),c.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let 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,c.appendChild(d);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()),c.appendChild(u),c.addEventListener("click",m=>{m.target===c&&this.abandonActionRequiredOverlay()});let p=0,h=m=>{let g=m.data,v=!!g&&typeof g=="object"&&g.source==="flopay-vault-3ds-return";if(m.source!==d.contentWindow){v&&p<It&&(p+=1,t.record("return_rejected",{reason:"untrusted_source",evidenceBasis:"message_origin_check"}));return}v&&(t.record("trusted_return",{evidenceBasis:"message_origin_check"}),t.terminal("trusted_return",{evidenceBasis:"message_origin_check"}),D(U("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(c)}catch(m){throw t.record("render_failed"),this.hideActionRequiredOverlay(),this.actionOverlayPreviousFocus=null,m}t.record("container_attached"),t.record("navigation_assigned");let f=he(c);f&&t.record("container_visibility",{reason:f,evidenceBasis:"parent_computed_style"}),this.actionOverlay=c,d.focus(),this.armActionRequiredTimeout(),D(U("vault.three_ds.handoff","three_ds_handoff"))}armActionRequiredTimeout(){this.actionOverlayTimer&&clearTimeout(this.actionOverlayTimer),this.actionOverlayTimer=setTimeout(()=>{this.actionOverlayTimer=null,this.actionOverlay&&this.timeOutActionRequiredOverlay()},Dt)}reportChallengeAbandoned(){D((0,T.buildTelemetryTerminalEvent)({eventId:"77777777-7777-4777-8777-777777777777",outcome:"customer_abandoned",stage:"three_ds_handoff",sequence:0,provider:"pcivault",paymentMethodCategory:"card"})),this.telemetryReporter?.terminal({outcome:"customer_abandoned",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"})}timeOutActionRequiredOverlay(){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:Ot})}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`}};var Wt=["setup_intent","setup_intent_client_secret","redirect_status"];function De(){if(typeof window>"u")return null;let r=new URLSearchParams(window.location.search);return!r.has("setup_intent")||!r.has("redirect_status")?null:{failed:r.get("redirect_status")==="failed"}}function Oe(){if(typeof window>"u")return;let r=new URL(window.location.href),e=!1;for(let t of Wt)r.searchParams.has(t)&&(r.searchParams.delete(t),e=!0);e&&window.history.replaceState(window.history.state,"",r.toString())}0&&(module.exports={PaymentAPI,PciVaultCardCapture,clearSetupRedirectParams,readSetupRedirectReturn});
|
|
1
|
+
"use strict";var J=Object.defineProperty;var Ne=Object.getOwnPropertyDescriptor;var Ve=Object.getOwnPropertyNames;var Be=Object.prototype.hasOwnProperty;var ze=(r,e)=>{for(var t in e)J(r,t,{get:e[t],enumerable:!0})},He=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Ve(e))!Be.call(r,i)&&i!==t&&J(r,i,{get:()=>e[i],enumerable:!(n=Ne(e,i))||n.enumerable});return r};var je=r=>He(J({},"__esModule",{value:!0}),r);var Jt={};ze(Jt,{PaymentAPI:()=>j,PciVaultCardCapture:()=>$,clearSetupRedirectParams:()=>Oe,readSetupRedirectReturn:()=>De});module.exports=je(Jt);var l=require("@flopay/shared");function se(r){return typeof r=="string"&&r.trim()?r:void 0}function oe(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 P(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 Ge(){return Object.assign(new Error("The operation was aborted."),{name:"AbortError"})}function q(r,e){let t=150*2**r,n=Math.round(t*(.75+Math.random()*.5));return new Promise((i,s)=>{let o,a=()=>e.removeEventListener("abort",c),c=()=>{o!==void 0&&clearTimeout(o),a(),s(Ge())};if(e.aborted){c();return}o=setTimeout(()=>{a(),i()},n),e.addEventListener("abort",c,{once:!0})})}var Ke="flopay_session_display:";var L=new Map;function N(r){return`${Ke}${r}`}function Q(){if(typeof window>"u")return null;try{return window.sessionStorage}catch{return null}}function X(r,e,t){if(!r)return;let n=t?.ttlMs??36e5,i={data:e,expiresAt:Date.now()+n},s=Q();if(s)try{s.setItem(N(r),JSON.stringify(i));return}catch{}L.set(r,i)}function ae(r){if(!r)return null;let e=Q();if(e)try{let n=e.getItem(N(r));if(n){let i=JSON.parse(n);if(i&&typeof i.expiresAt=="number"&&i.expiresAt>Date.now())return i.data;e.removeItem(N(r))}}catch{}let t=L.get(r);if(t){if(t.expiresAt>Date.now())return t.data;L.delete(r)}return null}function le(r){if(!r)return;L.delete(r);let e=Q();if(e)try{e.removeItem(N(r))}catch{}}var b=require("@flopay/shared");var Z=require("@flopay/shared"),$e=32,ce=Symbol.for("@flopay/js.three-ds-challenge.attempts.v1");function Ye(){let r=globalThis,e=r[ce];if(e instanceof Map)return e;let t=new Map;try{Object.defineProperty(r,ce,{configurable:!0,enumerable:!1,writable:!1,value:t})}catch{}return t}function We(r,e){let t=Ye(),n=t.get(r);if(n)return n;for(;t.size>=$e;){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(r,i),i}var Je=new Set(["pagehide_observed","cancel_requested","abort_observed","browser_terminal"]),Qe=new Set(["teardown","recovery_read_completed","provider_reconciled"]);function de(r,e={}){let t=(0,Z.isThreeDsChallengeAttemptId)(e.attemptId)?e.attemptId.toLowerCase():r.newAttemptId(),n=()=>{try{let a=r.now();return Number.isFinite(a)?a:0}catch{return 0}},i=We(t,n());(e.provider==="stripe"||e.provider==="worldpay")&&(i.provider=e.provider);let s=i.provider,o=(a,c)=>{if(i.terminated&&!Qe.has(a))return;let d={attemptId:t,phase:a,attemptSequence:i.nextSequence,elapsedMs:Math.max(0,n()-i.startedAt),provider:s};i.nextSequence+=1,c.reason!==void 0&&(d.reason=c.reason),c.evidenceBasis!==void 0&&(d.evidenceBasis=c.evidenceBasis),c.terminalSource!==void 0&&(d.terminalSource=c.terminalSource),c.providerOutcome!==void 0&&(d.providerOutcome=c.providerOutcome);try{r.emit(d,Je.has(a))}catch{}};return{attemptId:t,record(a,c={}){a==="browser_terminal"||a==="provider_reconciled"||o(a,{reason:c.reason,evidenceBasis:c.evidenceBasis})},terminal(a,c={}){i.terminated||(o("browser_terminal",{terminalSource:a,reason:c.reason,evidenceBasis:c.evidenceBasis}),i.terminated=!0)},reconcile(a){i.reconciled.has(a)||(i.reconciled.add(a),o("provider_reconciled",{providerOutcome:a,evidenceBasis:"provider_fact"}))}}}function ue(r){let e=null;try{e=(0,Z.isThreeDsChallengeAttemptId)(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 ee(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 he(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 me(r,e){if(!e)return null;try{let t=r,n=String(t.effectiveDirective||t.violatedDirective||"").trim().split(/\s+/)[0],i=null;return n==="frame-src"&&(i="frame_src"),n==="child-src"&&(i="child_src"),!i||typeof t.blockedURI!="string"?null:new URL(t.blockedURI).origin===e?i:null}catch{return null}}function pe(r){try{return ee(r)==="valid"?new URL(r).origin:null}catch{return null}}var Xe="/v1/sdk-telemetry/events",V=16,ye=64,Ze=1500,ge=1e3,et=64,tt="00000000-0000-4000-8000-000000000000",rt={technical_error:8,lifecycle:32,expected_outcome:32,performance:24},nt=48;function w(){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 it(r){try{return new TextEncoder().encode(r).byteLength}catch{return r.length}}function st(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 R(){return globalThis.performance?.now()??0}var E=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(/\/+$/,"")}${Xe}`,this.sdkPackage=e.sdkPackage??"@flopay/js",this.sdkVersion=e.sdkVersion,this.correlationId=w(),this.merchantEnabled=e.enabled!==!1,this.clock=e.clock??R,this.browserTransportAvailable=typeof window<"u"&&typeof document<"u",this.browserTransportAvailable&&(window.addEventListener("pagehide",this.pageExitHandler),document.addEventListener("visibilitychange",this.visibilityHandler))}log(e){this.notify({...e,class:"lifecycle"}),this.canCollect()&&this.enqueue((0,b.buildTelemetryLogEvent)({...this.checkoutContext,...e,eventId:w(),sequence:this.sequence++}))}error(e){if(this.notify({...e,class:"technical_error"}),!this.canCollect())return;let t=(0,b.buildTelemetryErrorEvent)({...this.checkoutContext,...e,eventId:tt,sequence:0}),n=st(t),i=this.now();this.pruneReportedFailures(i);let s=this.reportedFailures.get(n);if(s!==void 0&&i>=s&&i-s<ge){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,i),this.enqueue((0,b.buildTelemetryErrorEvent)({...this.checkoutContext,...e,eventId:w(),sequence:this.sequence++}))}performance(e){this.canCollect()&&this.enqueue((0,b.buildTelemetryPerformanceEvent)({...this.checkoutContext,...e,eventId:w(),sequence:this.sequence++}))}terminal(e){if(this.canCollect()&&(this.enqueue((0,b.buildTelemetryTerminalEvent)({...this.checkoutContext,...e,eventId:w(),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 de({now:()=>this.now(),newAttemptId:w,emit:(t,n)=>this.recordThreeDsChallenge(t,n)},e)}recordThreeDsChallenge(e,t){if(!this.canCollect()||this.threeDsChallengeCount>=nt)return;let n=(0,b.buildTelemetryLogEvent)({...this.checkoutContext,...e,name:"three_ds.challenge",stage:"three_ds_handoff",eventId:w(),sequence:this.sequence++});if(!(this.queue.length>=ye)){if(this.threeDsChallengeCount+=1,this.queue.push(n),t){this.drainQueue();return}if(this.queue.length>=V){this.flush();return}this.scheduleFlush()}}now(){try{return this.clock()}catch{return R()}}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>=ge)&&this.reportedFailures.delete(t)}rememberReportedFailure(e,t){for(;this.reportedFailures.size>=et;){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>=ye||this.eventCounts[e.class]>=rt[e.class])){if(this.eventCounts[e.class]+=1,this.queue.push(e),this.queue.length>=V){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,V);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,V);this.sendBatch(e)}}async sendBatch(e){if(!this.browserTransportAvailable||this.ingestionDisabled)return;let t=(0,b.serializeTelemetryBatch)(e,{correlationId:this.correlationId,sdkPackage:this.sdkPackage,sdkVersion:this.sdkVersion,batchId:w()});if(it(t)>b.TELEMETRY_MAX_BATCH_BYTES)return;let n=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:n?.signal}).then(async c=>{if(c.status!==202)return null;let d=null;try{d=await c.json()}catch{}return d?.status==="disabled"?"disabled":null}).catch(()=>null),o=new Promise(c=>{i=setTimeout(()=>{n?.abort(),c(null)},Ze)});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)}},fe=Symbol.for("@flopay/js.telemetry.reporter-factory.v1"),ve=globalThis;ve[fe]===void 0&&Object.defineProperty(ve,fe,{configurable:!0,enumerable:!1,writable:!1,value:r=>new E(r)});function ot(r){return r==="on_session"||r==="off_session"}function at(r){if(!r||typeof r!="object")return!1;let e=r;return typeof e.paymentMethodType=="string"&&typeof e.reason=="string"}function lt(r){let e=r.vaultOutcome;if(!(!e||e.code!==l.CHECKOUT_SESSION_BUYER_EMAIL_REQUIRED))return typeof e.message=="string"&&e.message.trim()!==""?e.message:void 0}var ct="x-flopay-process-result-source",dt="status",we=new WeakSet;function ut(r,e){let t=new l.FloPayError(r,"api_error",{code:e,statusCode:500});return we.add(t),t}function ht(r){return typeof r=="object"&&r!==null&&we.has(r)}function Ce(r){return r?.result==="DECLINE"||r?.result==="ERROR"}var mt=50,M=new Map;function pt(r,e){return M.get(r)?.has(e)===!0}function yt(r,e){let t=M.get(r)??new Set;if(t.add(e),M.delete(r),M.set(r,t),M.size>mt){let n=M.keys().next().value;n!==void 0&&M.delete(n)}}function gt(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 Te=0,be=500,B=15e3,_e=15e3,ft=3e3,vt=1e4,Ct=1e4;function x(r){return typeof r=="object"&&r!==null}function k(r,e){return se(r?.[e])}function Se(r,e){return oe(r?.[e])}function Tt(r,e){let t=r?.[e];return typeof t=="number"&&Number.isFinite(t)?t:void 0}function re(r,e){return e?new Promise((t,n)=>{let i=()=>{clearTimeout(s),n(e.reason??Object.assign(new Error("The operation was aborted."),{name:"AbortError"}))},s=setTimeout(()=>{e.removeEventListener("abort",i),t()},r);e.aborted?i():e.addEventListener("abort",i,{once:!0})}):new Promise(t=>setTimeout(t,r))}function te(r){return r instanceof Error&&r.name==="AbortError"}function S(){return new l.FloPayError(l.CHECKOUT_PROCESSING_TIMEOUT_MESSAGE,"api_error",{code:"checkout_processing_timeout"})}async function A(r,e){let t=await r.json().catch(()=>null),n=x(t?.error)?t.error:null,i=Se(t,"message")??Se(n,"message")??e,s=k(t,"code")??k(t,"gatewayErrorCode")??k(n,"code")??`http_${r.status}`;return(0,l.withTelemetryHttpDiagnostics)(new l.FloPayError(i,"api_error",{code:s,statusCode:r.status}),r)}async function bt(r){if(r.status!==403)return!1;let e=await r.clone().json().catch(()=>null),t=x(e?.error)?e.error:null;return(k(e,"code")??k(t,"code"))==="verification_required"}function _t(r){if(!(!x(r)||typeof r.required!="boolean"))return{required:r.required,provider:"turnstile"}}async function St(r){let e=r.status===400?await r.clone().json().catch(()=>null):null;return(0,l.classifyPaymentRejection)(r.status,e)}function Re(r){return r===400||r===422}var H=2;async function z(r,e,t=H,n,i){let s;for(let o=0;;o++)try{return i?.(o),await fetch(r,e)}catch(a){if(e?.signal?.aborted||a instanceof Error&&a.name==="AbortError")throw a;if(s=a,o>=t)throw s;try{n?.(o+1)}catch{}await re(150*2**o,e?.signal??void 0)}}var Rt=Symbol.for("@flopay/js.session-create.telemetry.v1");function At(r){return r[Rt]}function wt(r){return"now"in r||"onFirstByte"in r||"onSessionCreateFailure"in r||"onRetry"in r}function Ee(r){let e=(0,l.isCardHolderNamePlaceholder)(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 ke(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 Et(r,e){let t={clientId:r.clientId,checkoutVersion:l.SDK_VERSION,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}),ke(t,r),t}function Ae(r,e,t){return{currency:e,products:t.map(n=>(0,l.buildProductPayload)(n,e)),couponCodes:r.couponCodes??[],accountData:Ee(r.account)}}function kt(r,e,t){return{currency:e,products:t.map(n=>(0,l.buildProductPayload)(n,e)),couponCodes:r.couponCodes??[]}}function Mt(r){let e={},t=(0,l.isCardHolderNamePlaceholder)(r.firstName,r.lastName);for(let[n,i]of Object.entries(r)){if(t&&n.endsWith("Name")||typeof i!="string")continue;let s=i.trim();s&&(e[n]=s)}return{accountData:e}}var I=class I{constructor(e,t={}){this.baseUrl=e.replace(/\/+$/,"");let n=wt(t);this.telemetryHooks=n?t:void 0,this.directTelemetry=n||t.telemetry===!1?void 0:new E({billingApiUrl:this.baseUrl,sdkVersion:l.SDK_VERSION})}destroy(){this.directTelemetry?.destroy()}reportDirectFailure(e,t,n,i,s="unknown"){let o=(0,l.classifyTelemetryFailure)(e,t);this.directTelemetry?.error({...o,...ht(e)?{reason:"capture_failed"}:{},stage:n,requestCategory:i,paymentMethodCategory:s})}reportAccountSnapshotFailure(e,t){let n=(0,l.classifyTelemetryFailure)(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()??R()}catch{return R()}}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,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 c={[l.FLO_SDK_VERSION_HEADER]:l.SDK_VERSION};t&&(c["x-checkout-session-token"]=t);let d=!1;try{let u=await z(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}`,{headers:c,signal:i},H,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()});d=!0;let p=Math.max(0,this.telemetryTimestamp()-o);try{this.telemetryHooks?.onFirstByte?.(p,a)}catch{}let h=`${Math.floor(u.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}),!u.ok)throw await A(u,"Failed to get checkout session");let f=await u.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}),{...f,data:this.mergeCachedDisplayData(f.data)}}catch(u){throw d&&(0,l.markSessionResponseReceived)(u),n&&this.directTelemetry?.error({...(0,l.classifyTelemetryFailure)(u,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"}),u}}cacheSessionDisplayData(e,t,n){X(e,t,n)}clearSessionDisplayData(e){le(e)}async getVaultCapture(e,t){let n=`${this.baseUrl}\0${e}\0${t??""}`,i=I.activeVaultCaptureRequests.get(n);if(i!==void 0)return i;let s=this.requestVaultCapture(e,t);I.activeVaultCaptureRequests.set(n,s);try{return await s}finally{I.activeVaultCaptureRequests.get(n)===s&&I.activeVaultCaptureRequests.delete(n)}}async requestVaultCapture(e,t){let n=new AbortController,i=setTimeout(()=>n.abort(),Ct);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 z(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/vault/capture`,{method:"POST",headers:o,signal:n.signal},H,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 bt(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 A(a,"Failed to load the secure card form");let c=await a.json();return this.directTelemetry?.performance({stage:"vault_request",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"2xx"}),this.toVaultBlock(c)}catch(a){let c=n.signal.aborted?new l.FloPayError("Timed out while loading the secure card form. Please try again.","api_error",{code:"vault_capture_timeout"}):a;throw this.reportDirectFailure(c,"VAULT_LOAD_FAILED","vault_request","vault_capture","card"),c}finally{clearTimeout(i)}}async getUnifiedCheckoutSession(e,t){let n=await this.getCheckoutSession(e,t);return this.normalizeCheckoutSessionResponse(n)}async getUnifiedCheckoutSessionForRecovery(e,t,n){let i=await this.fetchCheckoutSession(e,t,!1,n);return this.normalizeCheckoutSessionResponse(i)}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(0,l.markSessionResponseReceived)(t)}}async processPayment(e,t,n){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 l.FloPayError("processPayment requires `nonce` \u2014 pass the value returned from session creation.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let s=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.processing.started",stage:"processing",requestCategory:"process_payment",paymentMethodCategory:i});let{nonce:o,paymentMethodCategory:a,...c}=t,d=gt(t.tokenizedData),u,p;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(c)}),p=u}catch(h){if(te(h))throw this.reportDirectFailure(h,"PAYMENT_PROCESSING_FAILED","processing","process_payment",i),h;u=await this.reconcileProcessPayment(t.sessionId,{...n,nonce:o,paymentMethodCategory:i,submittedIntentId:d})}if(!u.ok&&u.status!==202){let h=await St(u);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:(0,l.telemetryStatusClass)(u.status),failureCategory:u.status>=500?"server_error":void 0,paymentMethodCategory:i,...(0,l.readTelemetryHttpDiagnostics)(p)}),u}try{let h=await this.resolveProcessResponse(u,t.sessionId,{...n,nonce:o,paymentMethodCategory:i,submittedIntentId:d});return this.directTelemetry?.log({name:"payment.processing.completed",stage:"processing",requestCategory:"process_payment",statusClass:(0,l.telemetryStatusClass)(h.status),paymentMethodCategory:i}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"process_payment",statusClass:(0,l.telemetryStatusClass)(h.status),paymentMethodCategory:i}),h}catch(h){throw h instanceof l.FloPayError&&h.code==="checkout_processing_timeout"||this.reportDirectFailure(h,"PAYMENT_PROCESSING_FAILED","processing","process_payment",i),h}}async patchAccountSnapshot(e,t,n,i){this.beginDirectTelemetryCheckout(e);let s=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.state_transition",stage:"processing",requestCategory:"account_snapshot"});let o=i?.timeoutMs??vt,a=new AbortController,c=()=>a.abort();i?.signal&&(i.signal.aborted?a.abort():i.signal.addEventListener("abort",c,{once:!0}));let d=setTimeout(()=>a.abort(),o);try{let u;try{u=await z(`${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},H,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",c)}if(!u.ok)throw await A(u,"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(u){throw this.reportAccountSnapshotFailure(u,i?.telemetryMode??"blocking"),u}}async createSessionIntent(e,t,n,i){if(!t)throw new l.FloPayError("createSessionIntent requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let s=n,o=s.paymentMethodType,a=typeof o=="string"&&o.trim().toLowerCase()==="card",c=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"),u=s.provider==="paypal"&&s.paymentMethodCategory==="wallet"&&s.paymentMethodId===null&&(s.paymentMethodType==="paypal"&&s.intentKind==="payment"||s.paymentMethodType===l.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&(s.intentKind==="payment"||s.intentKind==="setup"));if(!c||!d&&!u)throw new l.FloPayError("Only wallet, APM, and PayPal session intents are supported.","validation_error",{code:"InvalidSessionIntentRequest"});let p=s.authorizationAttemptId;if(p!==void 0&&!(0,l.isUuidV4)(p))throw new l.FloPayError("authorizationAttemptId must be a v4 UUID identifying one buyer authorization attempt.","validation_error",{code:"InvalidAuthorizationAttemptId",param:"authorizationAttemptId"});let h=(0,l.isUuidV4)(p)?p:(0,l.randomUuidV4)();this.beginDirectTelemetryCheckout(e);let f=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,[l.IDEMPOTENCY_KEY_HEADER]:i?.idempotencyKey||h},g=!1;try{let v=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents`,{method:"POST",headers:m,body:JSON.stringify({...n,authorizationAttemptId:h}),signal:i?.signal});if(!v.ok){g=!0;let W=await A(v,"Failed to create checkout intent"),Le=(0,l.classifyTelemetryFailure)(W,"PAYMENT_PROCESSING_FAILED");throw Re(W.statusCode)?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"intent_create",statusClass:"4xx"}):this.directTelemetry?.error({...Le,stage:"processing",requestCategory:"intent_create"}),W}let C=await v.json();if(v.status===202&&x(C)&&C.type==="checkout_processing")return g=!0,await this.settleProcessingSessionIntent(C,v,e,t,n);let _=C.data;if(!_||typeof _!="object")throw new l.FloPayError("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});let y=_,ie=y.paymentMethodType,Fe=(y.paymentMethodCategory==="wallet"||y.paymentMethodCategory==="apm")&&typeof ie=="string"&&ie.trim().toLowerCase()!=="card"&&(typeof y.paymentMethodId=="string"||y.paymentMethodId===null)&&typeof y.providerObjectId=="string",xe=y.provider==="stripe"&&(y.intentKind==="payment"||y.intentKind==="setup")&&typeof y.clientSecret=="string",Ue=y.provider==="paypal"&&y.paymentMethodCategory==="wallet"&&y.paymentMethodId===null&&(y.paymentMethodType==="paypal"&&y.intentKind==="payment"&&(y.providerObjectType==="order"||y.providerObjectType==="subscription")||y.paymentMethodType===l.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&y.intentKind==="payment"&&y.providerObjectType==="order"||y.paymentMethodType===l.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&y.intentKind==="setup"&&y.providerObjectType==="setup_token")&&y.clientSecret===null,qe=y.provider===n.provider&&y.paymentMethodCategory===n.paymentMethodCategory&&y.paymentMethodType===n.paymentMethodType&&y.paymentMethodId===n.paymentMethodId&&y.intentKind===n.intentKind;if(!Fe||!xe&&!Ue||!qe)throw new l.FloPayError("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});return this.directTelemetry?.log({name:"payment.intent.completed",stage:"processing",requestCategory:"intent_create",statusClass:(0,l.telemetryStatusClass)(v.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-f),durationMode:"machine",requestCategory:"intent_create",statusClass:(0,l.telemetryStatusClass)(v.status)}),y}catch(v){throw g||this.reportDirectFailure(v,"PAYMENT_PROCESSING_FAILED","processing","intent_create"),v}}async settleProcessingSessionIntent(e,t,n,i,s){let o=this.toCheckoutProcessingPending(e,t,n);try{return{settled:!0,response:await this.resolveCheckoutProcessing(o,n,{nonce:i,paymentMethodCategory:s.provider==="paypal"?"paypal":s.paymentMethodCategory})}}catch(a){throw a instanceof l.FloPayError&&a.code==="checkout_processing_timeout"?new l.FloPayError(a.message,a.type,{code:a.code,statusCode:202,sessionId:o.sessionId,cause:a}):a}}async reportSessionIntentDecline(e,t,n,i){if(!t)throw new l.FloPayError("reportSessionIntentDecline requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let s=n,o=s.providerDeclineReason,a=s.paymentMethodType,c=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),u=typeof a=="string"&&a.length>0&&a.trim().toLowerCase()!=="card"&&d,p=s.provider==="stripe"&&(s.paymentMethodCategory==="wallet"||s.paymentMethodCategory==="apm")&&(c===void 0||typeof c=="string"&&/^pi_[a-z0-9_]{1,252}$/i.test(c)),h=s.provider==="paypal"&&s.paymentMethodCategory==="wallet"&&s.paymentMethodType==="paypal"&&c===void 0;if(!u||!p&&!h)throw new l.FloPayError("Invalid non-card decline classification.","validation_error",{code:"InvalidSessionIntentDeclineRequest"});let f=h?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:o}:{provider:"stripe",paymentMethodCategory:s.paymentMethodCategory,paymentMethodType:s.paymentMethodType,providerDeclineReason:o,...typeof c=="string"?{providerIntentId:c}:{}},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(f),signal:i?.signal});if(!m.ok)throw await A(m,"Failed to report checkout decline")}async resolvePaymentMethodLayout(e,t,n,i){if(!t)throw new l.FloPayError("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,[l.FLO_SDK_VERSION_HEADER]:l.SDK_VERSION},body:JSON.stringify(n),signal:i?.signal});if(s.status===404||s.status===405)return null;if(!s.ok)throw await A(s,"Failed to resolve the payment method layout");let o=await s.json();return(0,l.normalizePaymentMethodLayout)(o?.data)}async getPaymentsByEmail(e,t){this.beginDirectTelemetryOperation();let n=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(0,l.withTelemetryHttpDiagnostics)(new l.FloPayError("Failed to fetch payments","api_error",{statusCode:a.status}),a);let c=await a.json();return this.directTelemetry?.log({name:"operation.recovery.completed",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),this.directTelemetry?.performance({stage:"recovery",durationMs:Math.max(0,this.telemetryTimestamp()-n),durationMode:"machine",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),c}catch(a){throw this.reportDirectFailure(a,"RECOVERY_FAILED","recovery","other","saved"),a}}async createAndFetchSession(e){if((0,l.isDetachedSessionEligible)(e)){let s=e.account.email?.trim();if(s&&!(0,l.isValidEmail)(s))throw new l.FloPayError("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=P(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,n.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{n.clear()}}async createAndFetchSessionRequest(e,t,n){let i=e.products??(0,l.foldIntoProducts)(e.items,e.subscriptions);(0,l.assertCaptureMethodEligible)({captureMethod:e.captureMethod,products:i});let s=(0,l.resolveSessionCurrency)(e.currency,e.items,e.subscriptions,i);if(!s)throw new l.FloPayError("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});let o={clientId:e.clientId,checkoutVersion:l.SDK_VERSION,successUrl:e.successUrl,cancelUrl:e.cancelUrl,currency:s,checkoutMode:e.checkoutMode??"full",products:i.map(d=>(0,l.buildProductPayload)(d,s)),accountData:Ee(e.account),couponCodes:e.couponCodes??[]};e.captureMethod==="manual"&&(o.captureMethod=e.captureMethod),e.tokenizedData&&(o.tokenizedData=e.tokenizedData),ke(o,e);let a=await this.postCheckoutSessionCreate(o,e,t,n),c=!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),f=this.normalizeRawSession(h);return d.vault&&f.data.session&&(f.data.session.vault=this.toVaultBlock(d.vault)),{...f,autoProcessingError:d.autoProcessingError,autoProcessingAttempted:d.autoProcessingAttempted,autoProcessingPending:d.autoProcessingPending}}let u=d.data?.uuid;if(!u)throw new l.FloPayError("No session ID returned","api_error",{code:"InvalidCheckoutSessionResponse"});return this.autoCacheDisplayData(u,e),this.adoptDirectTelemetryCheckout(u),c=!0,{...await this.getUnifiedCheckoutSession(u),autoProcessingError:d.autoProcessingError,autoProcessingAttempted:d.autoProcessingAttempted,autoProcessingPending:d.autoProcessingPending}}catch(d){throw c?d:(0,l.markSessionResponseReceived)(d)}}async postCheckoutSessionCreate(e,t,n,i){let s={"Content-Type":"application/json",[l.FLO_SDK_VERSION_HEADER]:l.SDK_VERSION},o=(0,l.resolveIdempotencyKey)(t.idempotencyKey);o&&(s[l.IDEMPOTENCY_KEY_HEADER]=o),t.checkoutMode==="auto"&&(s[l.FLO_SDK_CAPABILITIES_HEADER]=l.ASYNC_AUTO_CHECKOUT_CAPABILITY);let a,c=!1,d=At(t),u=(h,f,m)=>{c||(c=!0,this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:m,attempt:h}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:Math.max(0,this.telemetryTimestamp()-f),durationMode:"machine",requestCategory:"session_create",statusClass:m,attempt:h}))},p=h=>{try{this.telemetryHooks?.onRetry?.("session_create",h),this.directTelemetry?.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:h})}catch{}};for(let h=0;h<3;h++){i.attempt=h;let f=this.telemetryTimestamp();try{d?.onAttempt?.(h)}catch{}try{a=await fetch(`${this.baseUrl}/v1/checkouts/sessions?expand=true`,{method:"POST",headers:s,body:JSON.stringify(e),signal:n})}catch(v){if(i.statusClass=n.aborted||v instanceof Error&&v.name==="AbortError"?"timeout":"network_error",n.aborted||v instanceof Error&&v.name==="AbortError"||h>=2)throw v;let C=h+1;p(C),await q(h,n);continue}let m=(0,l.telemetryStatusClass)(a.status);if(i.statusClass=m,a.status===204)throw u(h,f,m),new l.FloPayError("Session auto-completed \u2014 payment method already on file","api_error",{code:"session_auto_completed"});if(a.ok){u(h,f,m);break}let g=await A(a,"Failed to create checkout session");if(g.code===l.IDEMPOTENCY_IN_PROGRESS_CODE&&h<2){p(h+1),await q(h,n);continue}throw u(h,f,m),g}if(!a)throw new TypeError("Checkout-session creation exhausted its retry budget.");return a}async createDetachedSession(e){this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp(),n=P(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??(0,l.foldIntoProducts)(e.items,e.subscriptions);try{(0,l.assertCaptureMethodEligible)({captureMethod:e.captureMethod,products:s})}catch(C){throw n.clear(),this.reportSessionCreateFailure(C,t,i),C}let o=(0,l.resolveSessionCurrency)(e.currency,e.items,e.subscriptions,s);if(!o)throw n.clear(),this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),new l.FloPayError("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});try{Ae(e,o,s)}catch(C){throw n.clear(),this.reportSessionCreateFailure(C,t,i),C}let a,c,d=!1;try{let C=await this.postCheckoutSessionCreate(Et(e,o),e,n.signal,i);if(d=!0,c=await C.json(),!c.data||!("gateways"in c.data))throw new l.FloPayError("The billing API returned no session shell for a detached create. It must support `deferDataAttachment` (TeamFloPay/backend#1099).","api_error",{code:"InvalidCheckoutSessionResponse"});a=this.normalizeRawSession(this.mergeCachedDisplayData(c.data)),c.vault&&a.data.session&&(a.data.session.vault=this.toVaultBlock(c.vault))}catch(C){throw n.clear(),d&&(0,l.markSessionResponseReceived)(C),this.reportSessionCreateFailure(C,t,i),C}let u=a.data.session?.id??c.data.uuid??"",p=a.data.session?.clientSecret??c.data.nonce??"";if(!u||!p){n.clear();let C=new l.FloPayError("Checkout session shell was created without a session id or nonce.","api_error",{code:"InvalidCheckoutSessionResponse"});throw this.reportSessionCreateFailure(C,t,i),C}n.clear(),this.adoptDirectTelemetryCheckout(u),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(),f=P(e.timeoutMs??12e3),m=this.claimCheckoutSession(u,p,h?kt(e,o,s):Ae(e,o,s),{params:e,startedAt:t,deadline:f,createAttempt:i.attempt}),g=h?void 0:m,v=(C={})=>{if(g!==void 0)return g;let _={...e,account:{...e.account,...C,email:C.email?.trim()||e.account.email?.trim()}};return(0,l.isValidEmail)(_.account.email)?(g=m.then(()=>{let y=this.telemetryTimestamp();return this.claimCheckoutSession(u,p,Mt(_.account),{params:_,startedAt:y,deadline:P(e.timeoutMs??12e3),createAttempt:0})}),g.catch(()=>{}),g):Promise.reject(new l.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}))};return m.catch(()=>{}),{shell:a,sessionId:u,nonce:p,claimed:m,claim:v}}async claimCheckoutSession(e,t,n,i){let s=i?.startedAt??this.telemetryTimestamp(),o=this.telemetryTimestamp(),a=i?.deadline??P(12e3),c=JSON.stringify(n),d="unknown",u=0,p=!1;this.directTelemetry?.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"});try{let h;for(u=0;u<3;u++){try{h=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/claim`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":t,[l.FLO_SDK_VERSION_HEADER]:l.SDK_VERSION},body:c,signal:a.signal})}catch(g){let v=a.signal.aborted||g instanceof Error&&g.name==="AbortError";if(d=v?"timeout":"network_error",v||u>=2)throw g;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 q(u,a.signal);continue}if(d=(0,l.telemetryStatusClass)(h.status),h.ok)break;throw await A(h,"Failed to attach checkout session data")}if(!h)throw new TypeError("Checkout-session claim exhausted its retry budget.");p=!0;let f=await h.json();if(!f.data?.gateways)throw new l.FloPayError("The billing API returned no checkout session with gateways after claiming it.","api_error",{code:"InvalidCheckoutSessionResponse"});i?.params&&this.autoCacheDisplayData(f.data.uuid??e,i.params);let m=this.normalizeRawSession(this.mergeCachedDisplayData(f.data));return f.vault&&m.data.session&&(m.data.session.vault=this.toVaultBlock(f.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:u}),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??u}),m}catch(h){throw p&&(0,l.markSessionResponseReceived)(h),this.reportSessionCreateFailure(h,o,{attempt:u,statusClass:d},"session_claim"),h}finally{a.clear()}}reportSessionCreateFailure(e,t,n,i="session_create"){if(!(e instanceof l.FloPayError&&e.code==="session_auto_completed"))try{this.telemetryHooks?.onSessionCreateFailure?.(e)}catch{}let s=(0,l.classifyTelemetryFailure)(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:n.attempt}),e instanceof l.FloPayError&&e.type==="validation_error"||e instanceof l.FloPayError&&Re(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 l.FloPayError&&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 n=this.telemetryTimestamp(),i=t?.paymentMethodCategory??"saved";this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:i});let s=t?.timeoutMs??B,o=Date.now()+s,a=new AbortController,c=!1,d,u=setTimeout(()=>{d=setTimeout(()=>{c=!0,a.abort()},_e)},s),p=()=>a.abort(t?.signal?.reason);t?.signal?.aborted?p():t?.signal?.addEventListener("abort",p,{once:!0});let h=this.clampRetryAfterMs(t?.initialDelayMs??Te),f=0;try{if(t?.statusUrl){let m=await this.waitForCheckoutStatus(e,{initialDelayMs:h,timeoutMs:s,nonce:t.nonce,statusUrl:t.statusUrl,pollAfterAction:t.continueAfterActionRequired,signal:a.signal});if(m){let g=await this.resolveCheckoutSessionStatus(e,m,t.nonce,a.signal,()=>c);return this.reportRecoveryCompleted(n,i,t.challengeAttemptId),g}}for(;;){let m=o-Date.now();if(m<=0)throw S();if(h>0){try{f+=1,this.telemetryHooks?.onRetry?.("session_read",f),this.directTelemetry?.log({name:"operation.retry",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:i,attempt:f})}catch{}if(await re(Math.min(h,m),a.signal),Date.now()>=o)throw S()}let g=await this.getUnifiedCheckoutSessionForRecovery(e,t?.nonce,a.signal),v=g.data.session?.status;if(v==="authorized"||v==="complete"||v==="expired")return this.reportRecoveryCompleted(n,i,t?.challengeAttemptId),g;if(Date.now()>=o)throw S();h=this.clampRetryAfterMs(Math.max(h*2,be))}}catch(m){let g=c&&te(m)?S():m;throw this.reportDirectFailure(g,"RECOVERY_FAILED","recovery","session_read",i),g}finally{clearTimeout(u),clearTimeout(d),t?.signal?.removeEventListener("abort",p)}}reportRecoveryCompleted(e,t,n){let i={stage:"recovery",requestCategory:"session_read",paymentMethodCategory:t};if(this.directTelemetry?.log({name:"operation.recovery.completed",...i}),n)try{this.directTelemetry?.beginThreeDsChallenge({attemptId:n}).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,n,i,s){let o=t.latestTransactionAttempt;if(this.rememberReportedFailure(e,t),o?.result==="DECLINE"){let d=o.code===l.STORED_PAYMENT_METHOD_UNSUPPORTED_CODE;throw new l.FloPayError(d?l.STORED_PAYMENT_METHOD_UNSUPPORTED_MESSAGE:"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 ut("Payment could not be completed. Please try again.",o?.code??"payment_processing_error");let a;try{a=await this.getUnifiedCheckoutSessionForRecovery(e,n,i)}catch(d){if(!s?.()||!te(d))throw d;a={providers:[],mode:"tokenize",data:{},raw:t}}let c=a.data.session;return c&&o?.result==="SUCCESS"?{...a,data:{...a.data,session:{...c,status:"complete"}}}:c&&o?.result==="AUTHORIZED"?{...a,data:{...a.data,session:{...c,status:"authorized",paymentId:t.paymentId??void 0,authorizationExpiresAt:t.authorizationExpiresAt??void 0}}}:c&&t.status==="completed"?{...a,data:{...a.data,session:{...c,status:"complete"}}}:c&&t.status==="authorized"?{...a,data:{...a.data,session:{...c,status:"authorized",paymentId:t.paymentId??void 0,authorizationExpiresAt:t.authorizationExpiresAt??void 0}}}:c&&t.status==="expired"?{...a,data:{...a.data,session:{...c,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??B,i=Date.now()+n,s=this.clampRetryAfterMs(t.initialDelayMs);for(;;){let o=i-Date.now();if(o<=0||s>0&&(await re(Math.min(s,o),t.signal),Date.now()>=i))throw S();let a=i-Date.now();if(a<=0)throw S();let c=new AbortController,d,u=t.signal?new Promise((_,y)=>{d=y}):null,p=()=>{c.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,f=t.signal?null:new Promise((_,y)=>{h=setTimeout(()=>{y(S()),c.abort()},a+_e)}),m;try{let _=this.fetchCheckoutStatus(e,t.nonce,t.statusUrl,c.signal);m=await Promise.race([_,f,u].filter(y=>y!==null))}finally{h!==void 0&&clearTimeout(h),t.signal?.removeEventListener("abort",p)}if(!m)return null;let g=Ce(m.latestTransactionAttempt)&&!this.isOwnFailedAttempt(e,m,t.submittedIntentId);if(m.status==="completed"||m.status==="authorized"||m.status==="expired"||m.status==="voided")return g?{...m,latestTransactionAttempt:null}:m;let v=m.latestTransactionAttempt?.result,C=t.pollAfterAction===!0&&v==="ACTION_REQUIRED";if(!g&&v!==void 0&&v!=="PENDING"&&!C)return m;s=this.clampRetryAfterMs(Math.max(s*2,be))}}isOwnFailedAttempt(e,t,n){let i=t.latestTransactionAttempt?.providerIntentId??null;return n!==void 0?i===n:i===null?!0:!pt(t.uuid||e,i)}rememberReportedFailure(e,t){let n=t.latestTransactionAttempt;!Ce(n)||!n.providerIntentId||yt(t.uuid||e,n.providerIntentId)}async fetchCheckoutStatus(e,t,n,i){let s=`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/status`,o=s;if(n)try{let u=new URL(n,`${this.baseUrl}/`),p=new URL(s);u.origin===p.origin&&(o=u.toString())}catch{}let a={[l.FLO_SDK_VERSION_HEADER]:l.SDK_VERSION};t&&(a["x-checkout-session-token"]=t);let c=await z(o,{headers:a,signal:i});if(c.status===404||c.status===405)return null;if(!c.ok)throw await A(c,"Failed to get checkout session status");let d=await c.json();return x(d.data)&&"latestTransactionAttempt"in d.data?d.data:null}normalizeRawSession(e){let t=e.gateways??{},n=[],i={session:this.toCheckoutSession(e)},s=t.stripe;if(s?.publishableKey){n.push("stripe");let c=[e.stripeClientSecret,s.stripeClientSecret].find(d=>typeof d=="string"&&d.length>0);i.stripe={clientSecret:c??"",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&&(n.push("paypal"),i.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:i,raw:{data:e}}}toCheckoutSession(e){let t=e.products??[],n=typeof e.totalAmount=="number"&&Number.isFinite(e.totalAmount),i=t.reduce((d,u)=>d+(u.overrideAmount??u.totalAmount??0),0),s=n?e.totalAmount:i,o=Math.round(s*100),a=e.currency??t[0]?.currency??"USD",c="payment";return e.checkoutMode==="setup"?c="setup":t.some(d=>d.type==="subscription")&&(c="subscription"),{id:e.uuid,clientSecret:e.nonce,mode:c,status:this.toCheckoutSessionStatus(e.status),amount:o,currency:a,captureMethod:e.captureMethod,paymentId:e.paymentId,authorizationExpiresAt:e.authorizationExpiresAt,failureOutcome:(0,l.normalizeCheckoutFailureOutcome)(e.outcome)??(0,l.normalizeCheckoutFailureOutcome)(e.failureReason)??(e.status==="expired"&&e.captureMethod==="manual"?"authorization_expired":void 0),customer:{id:e.accountData.userId??void 0,email:e.accountData.email??void 0,firstName:e.accountData.firstName??void 0,lastName:e.accountData.lastName??void 0,country:e.accountData.country??void 0,city:e.accountData.city??void 0,state:e.accountData.state??void 0,zip:e.accountData.zip??void 0,gender:e.accountData.gender??void 0,line1:e.accountData.addressLine1??void 0,line2:e.accountData.addressLine2??void 0},...e.checkoutMetadata===void 0?{}:{checkoutMetadata:e.checkoutMetadata},metadata:{},checkoutMode:e.checkoutMode,...Array.isArray(e.advertisedPaymentMethods)?{advertisedPaymentMethods:e.advertisedPaymentMethods}:{},...ot(e.futureUse)?{futureUse:e.futureUse}:{},...Array.isArray(e.futureUseUnsupported)?{futureUseUnsupported:e.futureUseUnsupported.filter(at)}:{},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=_t(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 i=await e.json().catch(()=>null),s=this.toCheckoutProcessingPending(i,e,t);return this.resolveCheckoutProcessing(s,t,n)}async resolveCheckoutProcessing(e,t,n){let i=n?.pollTimeoutMs??B,s=Date.now()+i;if(e.statusUrl){let a=await this.waitForCheckoutStatus(e.sessionId,{initialDelayMs:e.retryAfterMs,timeoutMs:i,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:s-Date.now(),nonce:n?.nonce,paymentMethodCategory:n?.paymentMethodCategory});return this.toProcessResponseFromSession(o,t)}async toProcessResponseFromStatus(e,t,n){let i=e.latestTransactionAttempt?.result,s={[ct]:dt},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,n);return this.toProcessResponseFromSession(a,t)}if(this.rememberReportedFailure(t,e),i==="DECLINE"){let a=e.latestTransactionAttempt,c=a?.code===l.STORED_PAYMENT_METHOD_UNSUPPORTED_CODE,d=a?.declineReason??void 0;return new Response(JSON.stringify({type:d??"authorization_declined",message:c?l.STORED_PAYMENT_METHOD_UNSUPPORTED_MESSAGE:"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:lt(e)??"Payment could not be completed. Please try again."}),{status:500,headers:o});throw S()}async reconcileProcessPayment(e,t){let n=t?.pollTimeoutMs??B,i=Date.now()+n,s=null;try{s=await this.waitForCheckoutStatus(e,{initialDelayMs:0,timeoutMs:n,nonce:t?.nonce,submittedIntentId:t?.submittedIntentId})}catch(c){if(this.reportDirectFailure(c,"RECOVERY_FAILED","recovery","session_read",t?.paymentMethodCategory??"saved"),c instanceof l.FloPayError&&c.code==="checkout_processing_timeout")throw c}if(s)return this.toProcessResponseFromStatus(s,e,t?.nonce);let o=i-Date.now();if(o<=0)throw S();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 l.FloPayError(n?"Authorization has expired.":"Checkout session has expired.","api_error",{code:n?"authorization_expired":"checkout_session_expired"})}throw S()}toCheckoutProcessingPending(e,t,n){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")??n,retryAfterMs:this.clampRetryAfterMs(Tt(e,"retryAfterMs")??o??Te),statusUrl:k(e,"statusUrl"),sessionUrl:k(e,"sessionUrl")}}clampRetryAfterMs(e){return Math.max(0,Math.min(e,ft))}autoCacheDisplayData(e,t){if(!e)return;let n=t.products??(0,l.foldIntoProducts)(t.items,t.subscriptions);if(n.length===0&&!t.currency)return;let i=t.products!==void 0,s=(0,l.resolveSessionCurrency)(t.currency,i?void 0:t.items,i?void 0:t.subscriptions,n);X(e,{currency:s??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??s??void 0}))})}mergeCachedDisplayData(e){let t=ae(e.uuid),n=new Map,i=o=>o?`code:${o}`:void 0;for(let o of t?.products??[]){let a=i(o.code);a&&n.set(a,o)}let s=(e.products??[]).map(o=>{let a=i(o.code),c=a?n.get(a):void 0;return{...o,name:o.name??c?.name??null,totalAmount:o.totalAmount??c?.totalAmount,overrideAmount:o.overrideAmount??c?.overrideAmount,currency:o.currency??c?.currency}});return{...e,currency:e.currency??t?.currency,products:s}}};I.activeVaultCaptureRequests=new Map;var j=I;var T=require("@flopay/shared");var K=require("@flopay/shared");function Me(r){if(!r)return null;try{let e=new URL(r,window.location.href);return e.origin==="null"?null:e.origin}catch{return null}}var G=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=(0,K.resolveCardFieldsTimeoutMs)(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,n=[];for(let s of Array.from(e.querySelectorAll("script[src], iframe[src]"))){let o=Me(s.getAttribute("src"));if(o&&t.add(o),s.tagName==="SCRIPT"){let a=()=>this.fail("load_error");s.addEventListener("error",a),n.push(()=>s.removeEventListener("error",a))}}let i=s=>{let o=Me(s.blockedURI);o&&t.has(o)&&this.fail("blocked")};document.addEventListener("securitypolicyviolation",i),n.push(()=>document.removeEventListener("securitypolicyviolation",i)),this.detach=()=>{for(let s of n)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))(0,K.invokeMerchantCallback)(()=>t(e))}};var It=4,Y="flopay-vault",Pt=3e4,Dt=T.THREE_DS_CHALLENGE_WINDOW_MS+Pt,Ot="Card authentication timed out.",Ie={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 Ft(r){return r.class==="lifecycle"?r.name:r.class==="technical_error"?r.code:r.class==="expected_outcome"?r.outcome:"sdk.performance"}function D(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:Ft(r),data:e})}catch{}}function U(r,e){return(0,T.buildTelemetryLogEvent)({eventId:"11111111-1111-4111-8111-111111111111",name:r,stage:e,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}var xt=new Set(["authorization_declined","authentication_required","authorization_expired","capture_failed"]);function Ut(r){return typeof r=="string"&&xt.has(r)?r:"unknown"}var qt=new Set(["verification_failed","verification_expired"]);function Lt(r){return r==null?!0:typeof r=="string"&&qt.has(r)}var Nt="vault_mount";function Vt(r){return r.failureStage===Nt}function ne(r,e){return r&&!Vt(e)?{errorCode:"VAULT_SUBMIT_FAILED",stage:"vault_submit",failureCategory:"provider_runtime",reason:Ut(e.failureOutcome)}:{errorCode:"VAULT_LOAD_FAILED",stage:"vault_mount",failureCategory:"provider_runtime"}}function Pe(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 Bt(r,e,t,n="checkout"){let{type:i}=r;if(i==="complete"||i==="decline")return(0,T.buildTelemetryTerminalEvent)({eventId:"22222222-2222-4222-8222-222222222222",outcome:Pe(r,t,n),sequence:0,provider:"pcivault",paymentMethodCategory:"card"});if(i==="error"){let a=ne(e,r);return(0,T.buildTelemetryErrorEvent)({eventId:"33333333-3333-4333-8333-333333333333",...a,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}let[s,o]=Ie[i];return U(s,o)}function zt(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===Y&&(e.type==="ready"||e.type==="submitting"||e.type==="blocked"||e.type==="complete"||e.type==="decline"||e.type==="error"||e.type==="action_required")}function Ht(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 jt(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 Gt(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===Y&&e.type==="validation"&&Array.isArray(e.messages)}function Kt(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===Y&&e.type==="resize"&&typeof e.height=="number"&&Number.isFinite(e.height)}function $t(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===Y&&e.type==="fields_interactive"}function Yt(r){let e=r.capabilities;return Array.isArray(e)&&e.includes("fields_interactive")}var $=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.cardBrandIcons=!1;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.cardFields=new G({timeoutMs:e.cardFieldsTimeoutMs,now:()=>this.telemetryReporter?.now?.()??R(),report:n=>this.reportCardFields(n)}),this.ownsTelemetryReporter=!t&&e.telemetry!==!1,this.telemetryReporter=t?.reporter??(this.ownsTelemetryReporter?new E({billingApiUrl:(0,T.resolveBillingApiUrl)(e.billingApiUrl),sdkVersion:T.SDK_VERSION}):void 0)}async mount(e,t){this.ownsTelemetryReporter&&!this.telemetryReporter&&(this.telemetryReporter=new E({billingApiUrl:(0,T.resolveBillingApiUrl)(this.config.billingApiUrl),sdkVersion:T.SDK_VERSION}));let n=this.telemetryReporter;if(this.config.operation==="card_setup"&&n&&this.setupTelemetryReporter!==n){this.setupTelemetryReporter=n;try{n.beginCheckout({checkoutMode:"setup"})}catch{}}if(this.mountStartedAt=this.telemetryReporter?.now?.()??R(),this.vaultReadyReported=!1,this.submissionStarted=!1,this.submissionStartedAt=null,this.cardFields.begin(),typeof window>"u"||typeof document>"u")throw this.reportVaultLoadFailure(),this.failCardFieldsMount(),new T.FloPayError("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 T.FloPayError("No vault capture widget HTML was provided to mount the secure card form.","api_error",{code:"card_capture_no_widget_html"});this.container=e,this.verificationRequired=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.postSubmitLabel(),D(U("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?.()??R())-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)}}onCardFields(e){return this.cardFields.subscribe(e)}failCardFieldsMount(){this.cardFields.fail("other"),this.cardFields.end()}reportCardFields(e){let t=e.type==="card_fields_ready",n=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}:{},...n?{checkoutSessionId:n}:{}})}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 n=Array.from(e.querySelectorAll("script"));for(let i of n){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 n=t.data;if(Kt(n)){if(this.messageToken&&n.messageToken!==this.messageToken)return;this.applyHeight(n.height);return}if(Gt(n)){if(this.messageToken&&n.messageToken!==this.messageToken)return;let d=n.messages.filter(u=>typeof u=="string"&&u.trim()).join(" ");this.emit("validation",{sessionId:this.config.sessionId,message:d||void 0});return}if($t(n)){if(this.messageToken&&n.messageToken!==this.messageToken)return;let d=typeof n.sessionId=="string"?n.sessionId:void 0;if(this.config.sessionId&&d&&d!==this.config.sessionId)return;this.cardFields.ready();return}if(!zt(n)||this.messageToken&&n.messageToken!==this.messageToken)return;let i=this.config.sessionId,s=typeof n.sessionId=="string"?n.sessionId:void 0;if(i&&s&&s!==i||(n.type==="complete"||n.type==="decline")&&i&&s!==i)return;let o=jt(n.paymentMethod),a=Ht(n.vaultOutcome),c={...n.sessionId??this.config.sessionId?{sessionId:n.sessionId??this.config.sessionId}:{},...n.outcome?{outcome:n.outcome}:{},...n.paymentId?{paymentId:n.paymentId}:{},...n.authorizationExpiresAt?{authorizationExpiresAt:n.authorizationExpiresAt}:{},...n.failureOutcome?{failureOutcome:n.failureOutcome}:{},...n.intentId?{intentId:n.intentId}:{},...n.declineReason?{declineReason:n.declineReason}:{},...n.message?{message:n.message}:{},...a?{vaultOutcome:a}:{},...o?{paymentMethod:o}:{}};n.type==="submitting"&&(this.submissionStarted=!0,this.submissionStartedAt=this.telemetryReporter?.now?.()??R()),this.isVerificationStateError(n)?(D(U("operation.state_transition","vault_mount")),this.telemetryReporter?.log({name:"operation.state_transition",stage:"vault_mount",provider:"pcivault",paymentMethodCategory:"card"})):(D(Bt(n,this.submissionStarted,this.config.captureMethod,this.config.operation)),this.reportOutcome(n),n.type==="error"&&ne(this.submissionStarted,n).errorCode==="VAULT_LOAD_FAILED"&&this.cardFields.fail("load_error")),n.type==="ready"&&(this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),this.postCardBrandIcons(),this.postSubmitLabel(),Yt(n)||this.cardFields.ready()),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,c)};this.messageHandler=e,window.addEventListener("message",e)}isVerificationStateError(e){return e.type==="error"&&this.verificationRequired&&!this.submissionStarted&&Lt(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:Pe(e,this.config.captureMethod,this.config.operation),provider:"pcivault",paymentMethodCategory:"card"});return}if(n==="error"){let o=ne(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[i,s]=Ie[n];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()}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:n,expectedOrigin:i}=this;e===void 0||!t||!n||!i||this.postToHostedWindow({source:"flopay-vault-host",type:"submitLabel",sessionId:t,messageToken:n,label:e},i)}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=ue(this.beginActionChallengeAttempt()),n=pe(e),i=!1,s=m=>{if(i)return;let g=me(m,n);g&&(i=!0,t.record("policy_violation",{reason:g,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 c=document.createElement("div");c.setAttribute("data-flopay-action-required","1"),c.setAttribute("role","dialog"),c.setAttribute("aria-modal","true"),c.setAttribute("aria-label","Card authentication"),c.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let 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,c.appendChild(d);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()),c.appendChild(u),c.addEventListener("click",m=>{m.target===c&&this.abandonActionRequiredOverlay()});let p=0,h=m=>{let g=m.data,v=!!g&&typeof g=="object"&&g.source==="flopay-vault-3ds-return";if(m.source!==d.contentWindow){v&&p<It&&(p+=1,t.record("return_rejected",{reason:"untrusted_source",evidenceBasis:"message_origin_check"}));return}v&&(t.record("trusted_return",{evidenceBasis:"message_origin_check"}),t.terminal("trusted_return",{evidenceBasis:"message_origin_check"}),D(U("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(c)}catch(m){throw t.record("render_failed"),this.hideActionRequiredOverlay(),this.actionOverlayPreviousFocus=null,m}t.record("container_attached"),t.record("navigation_assigned");let f=he(c);f&&t.record("container_visibility",{reason:f,evidenceBasis:"parent_computed_style"}),this.actionOverlay=c,d.focus(),this.armActionRequiredTimeout(),D(U("vault.three_ds.handoff","three_ds_handoff"))}armActionRequiredTimeout(){this.actionOverlayTimer&&clearTimeout(this.actionOverlayTimer),this.actionOverlayTimer=setTimeout(()=>{this.actionOverlayTimer=null,this.actionOverlay&&this.timeOutActionRequiredOverlay()},Dt)}reportChallengeAbandoned(){D((0,T.buildTelemetryTerminalEvent)({eventId:"77777777-7777-4777-8777-777777777777",outcome:"customer_abandoned",stage:"three_ds_handoff",sequence:0,provider:"pcivault",paymentMethodCategory:"card"})),this.telemetryReporter?.terminal({outcome:"customer_abandoned",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"})}timeOutActionRequiredOverlay(){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:Ot})}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`}};var Wt=["setup_intent","setup_intent_client_secret","redirect_status"];function De(){if(typeof window>"u")return null;let r=new URLSearchParams(window.location.search);return!r.has("setup_intent")||!r.has("redirect_status")?null:{failed:r.get("redirect_status")==="failed"}}function Oe(){if(typeof window>"u")return;let r=new URL(window.location.href),e=!1;for(let t of Wt)r.searchParams.has(t)&&(r.searchParams.delete(t),e=!0);e&&window.history.replaceState(window.history.state,"",r.toString())}0&&(module.exports={PaymentAPI,PciVaultCardCapture,clearSetupRedirectParams,readSetupRedirectReturn});
|
package/dist/card-setup.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{q as a,s as n}from"./chunk-
|
|
1
|
+
import{q as a,s as n}from"./chunk-H4BJFWDW.mjs";var i=["setup_intent","setup_intent_client_secret","redirect_status"];function o(){if(typeof window>"u")return null;let e=new URLSearchParams(window.location.search);return!e.has("setup_intent")||!e.has("redirect_status")?null:{failed:e.get("redirect_status")==="failed"}}function u(){if(typeof window>"u")return;let e=new URL(window.location.href),t=!1;for(let r of i)e.searchParams.has(r)&&(e.searchParams.delete(r),t=!0);t&&window.history.replaceState(window.history.state,"",e.toString())}export{a as PaymentAPI,n as PciVaultCardCapture,u as clearSetupRedirectParams,o as readSetupRedirectReturn};
|