@flopay/js 1.5.0 → 1.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -1
- package/dist/card-setup.cjs +1 -1
- package/dist/card-setup.mjs +1 -1
- package/dist/chunk-CR4J5H7I.mjs +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +20 -20
- package/dist/index.d.ts +20 -20
- package/dist/index.mjs +1 -1
- package/package.json +2 -2
- package/dist/chunk-G6M32WZN.mjs +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as E,b as K,c as Re,d as Te,e as x,f as g,g as j,h as Z,i as ke,j as O,k as ee,l as z,m as te}from"./chunk-G6M32WZN.mjs";import{FloPayError as qe,resolveBillingApiUrl as $,SDK_VERSION as de}from"@flopay/shared";import{loadStripe as be}from"@stripe/stripe-js";import{FloPayError as p,isMoneySettledOutcome as Ae,isSetupIntentClientSecret as Ie}from"@flopay/shared";function re(r){return{payment:"payment",address:"address"}[r]}function U(r){switch(r){case"night":return"night";case"flat":return"flat";default:return"stripe"}}function Fe(r){return{...r,theme:U(r.theme)}}function B(r){return r?JSON.stringify(r.map(e=>e.trim().toLowerCase())):null}function ne(r){let e=r;return{mount(n){e.mount(n)},unmount(){e.unmount()},update(n){e.update(n)},on(n,t){e.on?.(n,t)},off(n,t){e.off?.(n,t)},destroy(){e.destroy()}}}function xe(r){return{billing_details:{...r.email?{email:r.email}:{},...r.name?{name:r.name}:{},...r.address?{address:{...r.address.country?{country:r.address.country}:{},...r.address.postal_code?{postal_code:r.address.postal_code}:{},...r.address.city?{city:r.address.city}:{},...r.address.line1?{line1:r.address.line1}:{},...r.address.line2?{line2:r.address.line2}:{},...r.address.state?{state:r.address.state}:{}}}:{}}}}var R=class{constructor(){this.name="stripe";this.stripe=null;this.elements=null;this.appliedAppearanceKey=null;this.appliedPaymentMethodTypesKey=null;this.appliedClientSecret=null;this.verifiedClientSecret=null;this.verifiedPaymentMethodTypesKey=null}async initialize(e){if(typeof window>"u")return;let n=await be(e.publishableKey,{locale:e.locale??"auto"});if(!n)throw new p("Failed to initialize Stripe. Check your publishable key.","authentication_error");this.stripe=n}getElements(e){if(!this.stripe)throw new p("StripeAdapter not initialized. Call initialize() first.","api_error");let n=e?.appearance?{theme:U(e.appearance.theme),variables:e.appearance.variables,rules:e.appearance.rules}:void 0,t=n?JSON.stringify(n):null,a=B(e?.paymentMethodTypes),o=e?.clientSecret??null;if(this.elements&&a&&(a!==this.appliedPaymentMethodTypesKey||o!==this.appliedClientSecret)&&(this.elements=null,this.appliedAppearanceKey=null,this.appliedPaymentMethodTypesKey=null,this.appliedClientSecret=null,this.verifiedClientSecret=null,this.verifiedPaymentMethodTypesKey=null),this.elements)t!==this.appliedAppearanceKey&&(this.elements.update({appearance:n??{}}),this.appliedAppearanceKey=t);else{let l,s=e?.amount??0,i=(e?.currency??"usd").toLowerCase(),d=e?.paymentMethodCreation??"manual";e?.clientSecret?l={clientSecret:e.clientSecret}:s>0?(l={mode:"payment",amount:s,currency:i,paymentMethodCreation:d},e?.setupFutureUsage&&(l.setupFutureUsage=e.setupFutureUsage)):l={mode:"setup",currency:i,paymentMethodCreation:d},!e?.clientSecret&&e?.paymentMethodTypes&&(l.paymentMethodTypes=e.paymentMethodTypes),n&&(l.appearance=n),this.elements=this.stripe.elements(l),this.appliedAppearanceKey=t,this.appliedPaymentMethodTypesKey=a,this.appliedClientSecret=o,this.verifiedClientSecret=null,this.verifiedPaymentMethodTypesKey=null}return this.elements}async assertClientSecretPaymentMethods(e,n){if(!this.stripe)throw new p("StripeAdapter not initialized. Call initialize() first.","api_error");let t,a=!1;if(Ie(e)){let{setupIntent:i,error:d}=await this.stripe.retrieveSetupIntent(e);t=i,a=!!d}else{let{paymentIntent:i,error:d}=await this.stripe.retrievePaymentIntent(e);t=i,a=!!d}let o=t?.payment_method_types;if(a||!Array.isArray(o))throw new p("Unable to verify the payment methods configured for this client secret.","api_error",{param:"clientSecret"});let l=new Set(n.map(i=>i.toLowerCase()));if(o.some(i=>typeof i!="string"||!l.has(i.trim().toLowerCase()))||o.length===0)throw new p("The client-secret intent must enable only declared non-card payment methods.","validation_error",{param:"clientSecret"})}async createElement(e,n){let t=n;if(e==="payment"){let i=n.paymentMethodTypes?.map(d=>d.trim()).filter(d=>d&&d.toLowerCase()!=="card");if(!i?.length)throw new p("At least one supported non-card payment method is required.","validation_error",{param:"paymentMethodTypes"});if(t={...n,paymentMethodTypes:i},t.clientSecret){let d=B(i);this.elements&&this.appliedClientSecret===t.clientSecret&&this.appliedPaymentMethodTypesKey===d&&this.verifiedClientSecret===t.clientSecret&&this.verifiedPaymentMethodTypesKey===d||await this.assertClientSecretPaymentMethods(t.clientSecret,i)}}let a=this.getElements(t);e==="payment"&&t.clientSecret&&(this.verifiedClientSecret=t.clientSecret,this.verifiedPaymentMethodTypesKey=B(t.paymentMethodTypes));let o=re(e),l={};t.layout&&(l.layout=t.layout),t.defaultValues&&(l.defaultValues=t.defaultValues),t.readOnly&&(l.readOnly=t.readOnly),t.mode&&(l.mode=t.mode);let s=a.create(o,l);return ne(s)}getElement(e){if(!this.elements)return null;let n=re(e),t=this.elements.getElement(n);return t?ne(t):null}async submitElements(){if(!this.stripe||!this.elements)return{error:new p("Stripe not initialized","api_error")};let{error:e}=await this.elements.submit();return e?{error:new p(e.message??"Validation failed","validation_error")}:{}}async confirmPayment(e){if(!this.stripe||!this.elements)throw new p("StripeAdapter not initialized or no elements created.","api_error");let n=e.billingDetails,t=n?xe(n):void 0,{error:a,paymentIntent:o}=await this.stripe.confirmPayment({elements:this.elements,clientSecret:e.clientSecret,confirmParams:{return_url:e.returnUrl??window.location.href,...t?{payment_method_data:t}:{}},redirect:"if_required"});return a?{status:"failed",error:new p(a.message??"Payment failed","api_error",{code:a.code,declineCode:a.decline_code})}:o?{status:{succeeded:"succeeded",processing:"processing",requires_action:"requires_action",requires_payment_method:"failed",canceled:"failed"}[o.status]??"failed",paymentIntentId:o.id,paymentMethodId:this.extractPaymentMethodId(o.payment_method)}:{status:"failed",error:new p("No payment intent returned","api_error")}}extractPaymentMethodId(e){if(typeof e=="string"&&e.startsWith("pm_"))return e;if(e&&typeof e=="object"&&typeof e.id=="string")return e.id}async confirmPayPalPayment(e){if(!this.stripe)return{status:"failed",error:new p("Stripe not initialized","api_error")};let n=e.billingApiUrl.replace(/\/+$/,"");if(this.elements){let{error:o}=await this.elements.submit();if(o)return{status:"failed",error:new p(o.message??"PayPal payment failed","validation_error",{code:o.code})}}let t;try{let o=await new O(n).createSessionIntent(e.sessionId,e.nonce??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"});if(o.provider!=="stripe")throw new p("Invalid provider returned for PayPal intent","api_error");t=o.clientSecret}catch(o){return{status:"failed",error:o instanceof p?o:new p("Failed to create PayPal payment intent","api_error")}}let{error:a}=await this.stripe.confirmPayment({clientSecret:t,elements:this.elements??void 0,confirmParams:{return_url:e.returnUrl}});if(a){if(e.nonce)try{await new O(n).reportSessionIntentDecline(e.sessionId,e.nonce,{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:a.code??"provider_declined"})}catch{}return{status:"failed",error:new p(a.message??"PayPal payment failed","api_error",{code:a.code})}}return{status:"processing"}}async resumePayPalPayment(){if(!this.stripe||typeof window>"u")return null;let e=new URLSearchParams(window.location.search),n=e.get("payment_intent"),t=e.get("payment_intent_client_secret"),a=e.get("redirect_status");if(!n||!t)return null;if(a==="failed")return{status:"failed",error:new p("PayPal payment was declined. Please try again.","api_error")};let{paymentIntent:o,error:l}=await this.stripe.retrievePaymentIntent(t);if(l)return{status:"failed",error:new p(l.message??"Failed to retrieve PayPal payment","api_error")};if(o&&Ae(o.status)){let s=typeof o.payment_method=="string"?o.payment_method:o.payment_method?.id,i=new URL(window.location.href);return i.searchParams.delete("payment_intent"),i.searchParams.delete("payment_intent_client_secret"),i.searchParams.delete("redirect_status"),window.history.replaceState({},"",i.toString()),{status:o.status,paymentIntentId:o.id,paymentMethodId:s}}return{status:"failed",error:new p("PayPal payment was not completed. Please try again.","api_error")}}getRawProvider(){return this.stripe}createPayPalElements(e){if(!this.stripe)return null;let n={mode:"payment",amount:e.amount??0,currency:(e.currency??"usd").toLowerCase(),captureMethod:"manual"};return e.setupFutureUsage&&(n.setupFutureUsage=e.setupFutureUsage),e.appearance&&(n.appearance={theme:U(e.appearance.theme),variables:e.appearance.variables,rules:e.appearance.rules}),this.stripe.elements(n)}destroy(){this.elements=null,this.appliedAppearanceKey=null,this.appliedPaymentMethodTypesKey=null,this.appliedClientSecret=null,this.verifiedClientSecret=null,this.verifiedPaymentMethodTypesKey=null,this.stripe=null}};import{FloPayError as m,classifyTelemetryFailure as V,resolveBillingApiUrl as se,SDK_VERSION as Ue}from"@flopay/shared";import{FloPayError as Oe}from"@flopay/shared";var T=class{constructor(e,n){this.elementMap=new Map;this.provider=e,this.baseOptions=n??{}}async create(e,n){let t={...this.baseOptions,...n};if(e==="payment"){let s=t.paymentMethodTypes?.map(i=>i.trim()).filter(i=>i&&i.toLowerCase()!=="card");if(!s?.length)throw new Oe("At least one supported non-card payment method is required.","validation_error",{param:"paymentMethodTypes"});t.paymentMethodTypes=s}let a=this.provider.getElement(e);if(a)return this.elementMap.set(e,a),a;let o=this.elementMap.get(e);o&&o.destroy();let l=await this.provider.createElement(e,t);return this.elementMap.set(e,l),l}getElement(e){return this.elementMap.get(e)??null}async submit(){return{}}destroy(){for(let e of this.elementMap.values())e.destroy();this.elementMap.clear()}};var ae=Symbol.for("@flopay/js.telemetry.bridge.v1");function oe(r,e,n){let t=()=>e?.now()??n();Object.defineProperty(r,ae,{configurable:!1,enumerable:!1,writable:!1,value:{error:o=>e?.error(o),log:o=>e?.log(o),performance:o=>e?.performance(o),terminal:o=>e?.terminal(o),now:t,elapsed:o=>Math.max(0,t()-o),setCheckoutContext:o=>e?.setCheckoutContext(o),beginCheckout:(o={})=>e?.beginCheckout(o)??t(),disable:()=>e?.disable()}})}function ie(r){return r[ae]}function v(r){if(!r)return!1;let e=r.code?.toLowerCase()??"";return!!r.declineCode||e.includes("declin")}function De(r){return r==="stripe"||r==="paypal"||r==="pcivault"?r:"other"}var D=class{constructor(e,n,t){this.currentElements=null;this.provider=e,this.config=n,this.telemetryReporter=t??new g({billingApiUrl:se(n.billingApiUrl),sdkVersion:Ue,enabled:n.telemetry!==!1}),oe(this,this.telemetryReporter,x)}now(){return this.telemetryReporter?.now?.()??x()}elements(e){return this.currentElements&&this.currentElements.destroy(),this.currentElements=new T(this.provider,{appearance:this.config.appearance,...e}),this.currentElements}async submitElements(){return this.provider.submitElements()}cardCapture(e){return this.telemetryReporter?.log({name:"vault.capture.requested",stage:"vault_request",provider:"pcivault",paymentMethodCategory:"card"}),this.telemetryReporter?te({sessionId:e?.sessionId,captureMethod:e?.captureMethod},this.telemetryReporter):new z({sessionId:e?.sessionId,captureMethod:e?.captureMethod,telemetry:!1})}async confirmPayPalPayment(e){let n=this.now();this.telemetryReporter?.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),this.telemetryReporter?.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});try{let t=await this.provider.confirmPayPalPayment(e);return this.telemetryReporter?.performance({stage:"processing",durationMs:this.now()-n,durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),t.error||this.telemetryReporter?.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),t.status==="requires_action"?(this.telemetryReporter?.log({name:"provider.redirect.started",stage:"redirect",provider:"paypal",paymentMethodCategory:"paypal"}),this.telemetryReporter?.terminal({outcome:"action_required",stage:"redirect",provider:"paypal",paymentMethodCategory:"paypal"})):t.status==="succeeded"?this.telemetryReporter?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}):t.status!=="processing"&&(v(t.error)?this.telemetryReporter?.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):t.error?.type==="validation_error"?this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal"}):t.error&&this.telemetryReporter?.error({errorCode:"PAYMENT_PROCESSING_FAILED",failureCategory:"provider_runtime",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"})),t}catch(t){if(this.telemetryReporter?.performance({stage:"processing",durationMs:this.now()-n,durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),t instanceof m&&v(t))this.telemetryReporter?.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"});else if(t instanceof m&&t.type==="validation_error")this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal"});else{let a=V(t,"PAYMENT_PROCESSING_FAILED","unknown");this.telemetryReporter?.error({...a,failureCategory:a.failureCategory??"provider_runtime",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"})}throw t}}async resumePayPalPayment(){let e=this.now();try{let n=await this.provider.resumePayPalPayment();return n===null?null:(this.telemetryReporter?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),this.telemetryReporter?.performance({stage:"redirect_resume",durationMs:this.now()-e,durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),n.status==="succeeded"?this.telemetryReporter?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}):v(n.error)?this.telemetryReporter?.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):n.error?.type==="validation_error"?this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal"}):n.error&&this.telemetryReporter?.error({errorCode:"REDIRECT_RESUME_FAILED",failureCategory:"provider_runtime",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),n)}catch(n){if(this.telemetryReporter?.performance({stage:"redirect_resume",durationMs:this.now()-e,durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),n instanceof m&&v(n))this.telemetryReporter?.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"});else if(n instanceof m&&n.type==="validation_error")this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal"});else{let t=V(n,"REDIRECT_RESUME_FAILED","unknown");this.telemetryReporter?.error({...t,failureCategory:t.failureCategory??"provider_runtime",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"})}throw n}}async confirmPayment(e){if(e.paymentMethodCategory!=="wallet"&&e.paymentMethodCategory!=="apm"||!e.paymentMethodType?.trim()||e.paymentMethodType.trim().toLowerCase()==="card")throw new m("A supported non-card payment method is required.","validation_error",{param:"paymentMethodType"});let n=this.now(),t=De(this.provider.name);this.telemetryReporter?.log({name:"payment.processing.started",stage:"processing",provider:t,paymentMethodCategory:e.paymentMethodCategory});try{let a=await this.provider.confirmPayment(e),o=this.now()-n;return this.telemetryReporter?.performance({stage:"processing",durationMs:o,durationMode:"machine",provider:t,paymentMethodCategory:e.paymentMethodCategory}),a.status==="succeeded"?this.telemetryReporter?.terminal({outcome:"payment_succeeded",provider:t,paymentMethodCategory:e.paymentMethodCategory}):v(a.error)?this.telemetryReporter?.terminal({outcome:"payment_declined",provider:t,paymentMethodCategory:e.paymentMethodCategory}):a.error?.type==="validation_error"?this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:t,paymentMethodCategory:e.paymentMethodCategory}):a.status==="requires_action"?this.telemetryReporter?.terminal({outcome:"action_required",stage:"three_ds_handoff",provider:t,paymentMethodCategory:e.paymentMethodCategory}):a.status==="failed"&&a.error&&this.telemetryReporter?.error({errorCode:"PAYMENT_PROCESSING_FAILED",failureCategory:"provider_runtime",stage:"processing",provider:t,paymentMethodCategory:e.paymentMethodCategory}),a.status==="succeeded"||a.status==="failed"?this.telemetryReporter?.log({name:"payment.processing.completed",stage:"processing",provider:t,paymentMethodCategory:e.paymentMethodCategory}):this.telemetryReporter?.log({name:"operation.state_transition",stage:a.status==="requires_action"?"three_ds_handoff":"processing",provider:t,paymentMethodCategory:e.paymentMethodCategory}),a}catch(a){throw this.telemetryReporter?.performance({stage:"processing",durationMs:this.now()-n,durationMode:"machine",provider:t,paymentMethodCategory:e.paymentMethodCategory}),a instanceof m&&v(a)?this.telemetryReporter?.terminal({outcome:"payment_declined",provider:t,paymentMethodCategory:e.paymentMethodCategory}):a instanceof m&&a.type==="validation_error"?this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:t,paymentMethodCategory:e.paymentMethodCategory}):this.telemetryReporter?.error({errorCode:"PAYMENT_PROCESSING_FAILED",failureCategory:"provider_runtime",stage:"processing",provider:t,paymentMethodCategory:e.paymentMethodCategory}),a}}async retrieveSession(e,n){if(!e)throw new m("sessionId is required to retrieve a session.","validation_error",{param:"sessionId"});let t=await this.retrieveUnifiedSession(e,n);if(!t.data.session)throw new m("Session not found","api_error");return t.data.session}async retrieveUnifiedSession(e,n){if(!e)throw new m("sessionId is required.","validation_error",{param:"sessionId"});let t=se(n??this.config.billingApiUrl),a=this.now();this.telemetryReporter?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let o,l=ee(t,{now:()=>this.telemetryReporter?.now()??x(),onFirstByte:s=>{o=s},onRetry:(s,i)=>{this.telemetryReporter?.log({name:"operation.retry",stage:s==="session_read"?"session_read":"processing",requestCategory:s,attempt:i})}});try{let s=await l.getUnifiedCheckoutSession(e);return o!==void 0&&(this.telemetryReporter?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:"2xx"}),this.telemetryReporter?.performance({stage:"session_first_byte",durationMs:o,durationMode:"machine",requestCategory:"session_read",statusClass:"2xx"})),this.telemetryReporter?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:"2xx"}),this.telemetryReporter?.log({name:"checkout.data.ready",stage:"checkout_data_ready"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-a,durationMode:"machine",requestCategory:"session_read",statusClass:"2xx"}),s}catch(s){let i=V(s,s instanceof m&&s.code==="checkout_processing_timeout"?"REQUEST_TIMEOUT":"NETWORK_REQUEST_FAILED");throw this.telemetryReporter?.error({...i,stage:"session_read",provider:"flo",paymentMethodCategory:"unknown"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-a,durationMode:"machine",requestCategory:"session_read",statusClass:i.statusClass}),s}}getRawProvider(){return this.provider.getRawProvider()}destroy(){this.telemetryReporter?.log({name:"checkout.unmount",stage:"unmount"}),this.telemetryReporter?.destroy(),this.currentElements?.destroy(),this.currentElements=null,this.provider.destroy()}};function le(r,e,n){let t=D;return new t(r,e,n)}var pe=new Map;function Y(r){return Array.isArray(r)?r.map(Y):r&&typeof r=="object"?Object.fromEntries(Object.entries(r).filter(([,e])=>e!==void 0).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>[e,Y(n)])):r}function Le(r,e){return JSON.stringify([r,$(e?.billingApiUrl),e?.telemetry!==!1,e?.locale??"auto",e?.apiVersion??null,Y(e?.appearance??null)])}var q=new Map;async function Ne(r,e){if(!r){let s=new g({billingApiUrl:$(e?.billingApiUrl),sdkVersion:de,enabled:e?.telemetry!==!1});throw s.error({errorCode:"CONFIGURATION_INVALID",stage:"sdk_initialize",paymentMethodCategory:"unknown"}),s.flush().catch(()=>{}).finally(()=>s.destroy()),new qe("A publishable key is required to initialize FloPay.","validation_error",{param:"publishableKey"})}let n=Le(r,e),t=pe.get(n);if(t)return e?.telemetry!==!1&&ie(t)?.log({name:"sdk.cache.hit",stage:"sdk_initialize"}),t;let a=q.get(n);if(a)return a;let o={...e,publishableKey:r},l=(async()=>{let s=new g({billingApiUrl:$(o.billingApiUrl),sdkVersion:de,enabled:o.telemetry!==!1}),i=s.now();s.log({name:"sdk.initialize.started",stage:"sdk_initialize"}),s.log({name:"sdk.cache.miss",stage:"sdk_initialize"}),s.log({name:"provider.load.started",stage:"provider_load",provider:"stripe"});let d=new R,h=s.now();try{await d.initialize(o)}catch(f){throw s.error({errorCode:"SDK_INITIALIZATION_FAILED",failureCategory:"provider_runtime",stage:"sdk_initialize",provider:"stripe",paymentMethodCategory:"unknown"}),s.destroy(),f}let C=s.now();s.log({name:"provider.ready",stage:"provider_ready",provider:"stripe"}),s.log({name:"provider.availability.checked",stage:"provider_ready",provider:"stripe"}),s.log({name:"sdk.initialize.ready",stage:"sdk_initialize"}),s.performance({stage:"sdk_initialize",durationMs:C-i,durationMode:"machine",provider:"stripe"}),s.performance({stage:"provider_ready",durationMs:C-h,durationMode:"machine",provider:"stripe"});let y=le(d,o,s);return pe.set(n,y),y})();q.set(n,l);try{return await l}finally{q.get(n)===l&&q.delete(n)}}import{FloPayError as S,IDEMPOTENCY_IN_PROGRESS_CODE as Ke,IDEMPOTENCY_KEY_HEADER as je,SDK_VERSION as ce,assertCaptureMethodEligible as ze,buildProductPayload as Be,classifyTelemetryFailure as Ve,foldIntoProducts as $e,resolveIdempotencyKey as me,resolveSessionCurrency as Ye,telemetryStatusClass as ye}from"@flopay/shared";var H=5,ue=new WeakSet;function Ge(r){(typeof r=="object"&&r!==null||typeof r=="function")&&ue.add(r)}function He(r){return(typeof r=="object"&&r!==null||typeof r=="function")&&ue.has(r)}function Je(r,e){let n=e?.error,t=E(e?.code)??E(n?.code)??`http_${r}`,a=E(e?.message)??E(n?.message)??We(t,r);return new S(a,"api_error",{code:t,statusCode:r})}function We(r,e){switch(r){case"CouponLimitExceeded":return`Too many coupon codes \u2014 a checkout session accepts at most ${H}.`;case"CouponCurrencyUnsupported":return"One of the applied coupons has no price configured for the cart currency.";default:return`Failed to create checkout session (HTTP ${e}).`}}async function he(r,e,n){let{billingApiUrl:t,checkoutBaseUrl:a,items:o=[],subscriptions:l=[],products:s,account:i,successUrl:d,cancelUrl:h,checkoutMode:C="confirm",captureMethod:y,couponCodes:f=[],tagsData:J,redirectParams:Pe={},setCookie:we=!0,clientId:ve,currency:_e,utmMetadata:W,idempotencyKey:Se}=r,Q=me(Se);if(f.length>H)throw new S(`Too many coupon codes \u2014 a checkout session accepts at most ${H}.`,"validation_error",{code:"CouponLimitExceeded",param:"couponCodes"});let M=s??$e(o,l);ze({captureMethod:y,products:M});let P=Ye(_e,o,l,M);if(!P)throw new S("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 k={clientId:ve,checkoutVersion:ce,successUrl:d,cancelUrl:h,currency:P,checkoutMode:C,products:M.map(u=>Be(u,P)),accountData:{userId:i.userId,firstName:i.firstName??null,lastName:i.lastName??null,email:i.email,country:i.country??null,gender:i.gender??null,city:i.city??null,state:i.state??null,zip:i.zip??null,addressLine1:i.addressLine1??null,addressLine2:i.addressLine2??null},couponCodes:f};y==="manual"&&(k.captureMethod=y),J&&(k.tagsData=J),W?.length&&(k.utmMetadata=W);let Me=`${t.replace(/\/+$/,"")}/v1/checkouts/sessions`,X={"Content-Type":"application/json"};Q&&(X[je]=Q);let w,b,Ee={method:"POST",headers:X,body:JSON.stringify(k),signal:e},A;try{A=await fetch(Me,Ee)}catch(u){throw Ge(u),u}try{n?.(A.status)}catch{}w=A.status;try{b=await A.json()}catch{}if(w>=400)throw Je(w,b);if(w===201){let u=b?.data?.uuid,N=b?.data?.nonce;if(!u)throw new Error("Checkout session created but no UUID was returned by the billing API");if(!N)throw new S("Checkout session created but no `nonce` was returned by the billing API. Upgrade the billing service to TeamFloPay/backend#640 or later.","api_error",{code:"MissingCheckoutSessionToken"});(M.length||P)&&K(u,{currency:P,products:M.map(c=>({code:c.code??c.providerItemId??c.providerPlanId,type:c.type,name:c.name??c.itemName??c.providerItemName??c.subscriptionName??c.providerPlanName??null,totalAmount:c.totalAmount,overrideAmount:c.overrideAmount,currency:c.currency??P}))});let I=new URL(`${a.replace(/\/+$/,"")}/secure`);I.searchParams.set("id",u);for(let[c,F]of Object.entries(Pe))I.searchParams.set(c,F);if(we&&typeof window<"u"&&typeof document<"u"){let c=JSON.stringify({origin_url:h}),F=window.location.hostname.split(".").slice(-2).join(".");document.cookie=`checkout_data=${encodeURIComponent(c)}; domain=.${F}; path=/; max-age=3600; SameSite=Lax; Secure;`,document.cookie=`flopay_checkout_token=${encodeURIComponent(N)}; domain=.${F}; path=/; max-age=3600; SameSite=Lax; Secure;`}return typeof window<"u"&&(window.location.href=I.toString()),{status:201,redirectUrl:I.toString(),nonce:N}}return w===204?(typeof window<"u"&&(window.location.href=d),{status:204}):{status:w}}async function Qe(r){let e=ge(r),n=fe(e),t=j(r.timeoutMs);try{let a=await he(r,t.signal,n);return Ce(e,a),a}catch(a){throw L(e,a),a}finally{t.clear(),_(e.reporter)}}function fe(r){let e=!1;return n=>{if(e)return;e=!0;let t=ye(n);r.reporter.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:t,attempt:r.attempt}),r.reporter.performance({stage:"session_first_byte",durationMs:r.reporter.now()-r.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:t,attempt:r.attempt})}}function ge(r){let e=new g({billingApiUrl:r.billingApiUrl,sdkVersion:ce,enabled:r.telemetry!==!1}),n=e.now();return e.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"}),{reporter:e,startedAt:n,attempt:0}}function Ce(r,e){let n=ye(e.status);r.reporter.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:n}),r.reporter.performance({stage:"session_create",durationMs:r.reporter.now()-r.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:n,attempt:r.attempt})}function L(r,e){let{reporter:n}=r,t=Ve(e,"CHECKOUT_SESSION_CREATE_FAILED");if(n.performance({stage:"session_create",durationMs:n.now()-r.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:t.statusClass,attempt:r.attempt}),e instanceof S&&e.type==="validation_error"){n.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"});return}if(t.statusClass==="4xx"){n.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create",statusClass:"4xx"});return}n.error({...t,stage:"session_create",requestCategory:"session_create"})}function _(r){r.flush().catch(()=>{}).finally(()=>r.destroy())}async function Xe(r){let{maxRetries:e=2,...n}=r,t=ge(r),a=fe(t);if(!Number.isFinite(e)||!Number.isInteger(e)||e<0||e>=3)throw t.reporter.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),_(t.reporter),new Error(`Number of retries must be an integer between 0 and ${2}`);let o={...n,idempotencyKey:me(n.idempotencyKey)},l=j(n.timeoutMs),s;for(let i=0;i<=e;i++){t.attempt=i;try{let d=await he(o,l.signal,a);return Ce(t,d),l.clear(),_(t.reporter),d}catch(d){s=d;let h=d instanceof Error&&d.name==="AbortError",C=He(d),y=d instanceof S&&d.code===Ke;if((h||C||y)&&!l.signal.aborted&&i<e){t.reporter.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:i+1});try{await Z(i,l.signal)}catch(f){throw L(t,f),l.clear(),_(t.reporter),f}continue}throw L(t,d),l.clear(),_(t.reporter),d}}throw L(t,s),l.clear(),_(t.reporter),s??new Error("Unknown error during checkout session creation")}import{dropThirdPartyOnlyError as Dt}from"@flopay/shared";export{D as FloPay,T as FloPayElements,O as PaymentAPI,z as PciVaultCardCapture,ke as SESSION_CREATE_TELEMETRY,R as StripeAdapter,K as cacheSessionDisplayData,Te as clearSessionDisplayData,Qe as createCheckoutSession,Xe as createCheckoutSessionWithRetries,Dt as dropThirdPartyOnlyError,Re as getSessionDisplayData,Ne as loadFloPay,Fe as toStripeAppearance,U as toStripeAppearanceTheme};
|
|
1
|
+
import{a as E,b as K,c as Z,d as j,e as Re,f as Te,g as x,h as g,i as ke,j as O,k as ee,l as z,m as te}from"./chunk-CR4J5H7I.mjs";import{dropThirdPartyOnlyError as Tt}from"@flopay/shared";import{assertCaptureMethodEligible as be,buildProductPayload as Ae,classifyTelemetryFailure as Ie,FloPayError as _,foldIntoProducts as Fe,IDEMPOTENCY_IN_PROGRESS_CODE as xe,IDEMPOTENCY_KEY_HEADER as Oe,resolveIdempotencyKey as re,resolveSessionCurrency as Ue,SDK_VERSION as ne,telemetryStatusClass as ae}from"@flopay/shared";var V=5,oe=new WeakSet;function De(r){(typeof r=="object"&&r!==null||typeof r=="function")&&oe.add(r)}function qe(r){return(typeof r=="object"&&r!==null||typeof r=="function")&&oe.has(r)}function Le(r,e){let n=e?.error,t=E(e?.code)??E(n?.code)??`http_${r}`,o=E(e?.message)??E(n?.message)??Ne(t,r);return new _(o,"api_error",{code:t,statusCode:r})}function Ne(r,e){switch(r){case"CouponLimitExceeded":return`Too many coupon codes \u2014 a checkout session accepts at most ${V}.`;case"CouponCurrencyUnsupported":return"One of the applied coupons has no price configured for the cart currency.";default:return`Failed to create checkout session (HTTP ${e}).`}}async function ie(r,e,n){let{billingApiUrl:t,checkoutBaseUrl:o,items:a=[],subscriptions:l=[],products:s,account:i,successUrl:d,cancelUrl:h,checkoutMode:C="confirm",captureMethod:y,couponCodes:f=[],tagsData:J,redirectParams:Pe={},setCookie:ve=!0,clientId:we,currency:_e,utmMetadata:W,idempotencyKey:Se}=r,Q=re(Se);if(f.length>V)throw new _(`Too many coupon codes \u2014 a checkout session accepts at most ${V}.`,"validation_error",{code:"CouponLimitExceeded",param:"couponCodes"});let M=s??Fe(a,l);be({captureMethod:y,products:M});let P=Ue(_e,a,l,M);if(!P)throw new _("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 k={clientId:we,checkoutVersion:ne,successUrl:d,cancelUrl:h,currency:P,checkoutMode:C,products:M.map(u=>Ae(u,P)),accountData:{userId:i.userId,firstName:i.firstName??null,lastName:i.lastName??null,email:i.email,country:i.country??null,gender:i.gender??null,city:i.city??null,state:i.state??null,zip:i.zip??null,addressLine1:i.addressLine1??null,addressLine2:i.addressLine2??null},couponCodes:f};y==="manual"&&(k.captureMethod=y),J&&(k.tagsData=J),W?.length&&(k.utmMetadata=W);let Me=`${t.replace(/\/+$/,"")}/v1/checkouts/sessions`,X={"Content-Type":"application/json"};Q&&(X[Oe]=Q);let v,b,Ee={method:"POST",headers:X,body:JSON.stringify(k),signal:e},A;try{A=await fetch(Me,Ee)}catch(u){throw De(u),u}try{n?.(A.status)}catch{}v=A.status;try{b=await A.json()}catch{}if(v>=400)throw Le(v,b);if(v===201){let u=b?.data?.uuid,N=b?.data?.nonce;if(!u)throw new Error("Checkout session created but no UUID was returned by the billing API");if(!N)throw new _("Checkout session created but no `nonce` was returned by the billing API. Upgrade the billing service to TeamFloPay/backend#640 or later.","api_error",{code:"MissingCheckoutSessionToken"});(M.length||P)&&j(u,{currency:P,products:M.map(c=>({code:c.code??c.providerItemId??c.providerPlanId,type:c.type,name:c.name??c.itemName??c.providerItemName??c.subscriptionName??c.providerPlanName??null,totalAmount:c.totalAmount,overrideAmount:c.overrideAmount,currency:c.currency??P}))});let I=new URL(`${o.replace(/\/+$/,"")}/secure`);I.searchParams.set("id",u);for(let[c,F]of Object.entries(Pe))I.searchParams.set(c,F);if(ve&&typeof window<"u"&&typeof document<"u"){let c=JSON.stringify({origin_url:h}),F=window.location.hostname.split(".").slice(-2).join(".");document.cookie=`checkout_data=${encodeURIComponent(c)}; domain=.${F}; path=/; max-age=3600; SameSite=Lax; Secure;`,document.cookie=`flopay_checkout_token=${encodeURIComponent(N)}; domain=.${F}; path=/; max-age=3600; SameSite=Lax; Secure;`}return typeof window<"u"&&(window.location.href=I.toString()),{status:201,redirectUrl:I.toString(),nonce:N}}return v===204?(typeof window<"u"&&(window.location.href=d),{status:204}):{status:v}}async function Ke(r){let e=le(r),n=se(e),t=K(r.timeoutMs);try{let o=await ie(r,t.signal,n);return de(e,o),o}catch(o){throw U(e,o),o}finally{t.clear(),w(e.reporter)}}function se(r){let e=!1;return n=>{if(e)return;e=!0;let t=ae(n);r.reporter.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:t,attempt:r.attempt}),r.reporter.performance({stage:"session_first_byte",durationMs:r.reporter.now()-r.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:t,attempt:r.attempt})}}function le(r){let e=new g({billingApiUrl:r.billingApiUrl,sdkVersion:ne,enabled:r.telemetry!==!1}),n=e.now();return e.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"}),{reporter:e,startedAt:n,attempt:0}}function de(r,e){let n=ae(e.status);r.reporter.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:n}),r.reporter.performance({stage:"session_create",durationMs:r.reporter.now()-r.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:n,attempt:r.attempt})}function U(r,e){let{reporter:n}=r,t=Ie(e,"CHECKOUT_SESSION_CREATE_FAILED");if(n.performance({stage:"session_create",durationMs:n.now()-r.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:t.statusClass,attempt:r.attempt}),e instanceof _&&e.type==="validation_error"){n.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"});return}if(t.statusClass==="4xx"){n.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create",statusClass:"4xx"});return}n.error({...t,stage:"session_create",requestCategory:"session_create"})}function w(r){r.flush().catch(()=>{}).finally(()=>r.destroy())}async function je(r){let{maxRetries:e=2,...n}=r,t=le(r),o=se(t);if(!Number.isFinite(e)||!Number.isInteger(e)||e<0||e>=3)throw t.reporter.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),w(t.reporter),new Error(`Number of retries must be an integer between 0 and ${2}`);let a={...n,idempotencyKey:re(n.idempotencyKey)},l=K(n.timeoutMs),s;for(let i=0;i<=e;i++){t.attempt=i;try{let d=await ie(a,l.signal,o);return de(t,d),l.clear(),w(t.reporter),d}catch(d){s=d;let h=d instanceof Error&&d.name==="AbortError",C=qe(d),y=d instanceof _&&d.code===xe;if((h||C||y)&&!l.signal.aborted&&i<e){t.reporter.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:i+1});try{await Z(i,l.signal)}catch(f){throw U(t,f),l.clear(),w(t.reporter),f}continue}throw U(t,d),l.clear(),w(t.reporter),d}}throw U(t,s),l.clear(),w(t.reporter),s??new Error("Unknown error during checkout session creation")}import{FloPayError as ze}from"@flopay/shared";var R=class{constructor(e,n){this.elementMap=new Map;this.provider=e,this.baseOptions=n??{}}async create(e,n){let t={...this.baseOptions,...n};if(e==="payment"){let s=t.paymentMethodTypes?.map(i=>i.trim()).filter(i=>i&&i.toLowerCase()!=="card");if(!s?.length)throw new ze("At least one supported non-card payment method is required.","validation_error",{param:"paymentMethodTypes"});t.paymentMethodTypes=s}let o=this.provider.getElement(e);if(o)return this.elementMap.set(e,o),o;let a=this.elementMap.get(e);a&&a.destroy();let l=await this.provider.createElement(e,t);return this.elementMap.set(e,l),l}getElement(e){return this.elementMap.get(e)??null}async submit(){return{}}destroy(){for(let e of this.elementMap.values())e.destroy();this.elementMap.clear()}};import{classifyTelemetryFailure as $,FloPayError as m,resolveBillingApiUrl as ye,SDK_VERSION as Be}from"@flopay/shared";var pe=Symbol.for("@flopay/js.telemetry.bridge.v1");function ce(r,e,n){let t=()=>e?.now()??n();Object.defineProperty(r,pe,{configurable:!1,enumerable:!1,writable:!1,value:{error:a=>e?.error(a),log:a=>e?.log(a),performance:a=>e?.performance(a),terminal:a=>e?.terminal(a),now:t,elapsed:a=>Math.max(0,t()-a),setCheckoutContext:a=>e?.setCheckoutContext(a),beginCheckout:(a={})=>e?.beginCheckout(a)??t(),disable:()=>e?.disable(),subscribe:a=>e?.subscribe(a)??(()=>{})}})}function me(r){return r[pe]}function S(r){if(!r)return!1;let e=r.code?.toLowerCase()??"";return!!r.declineCode||e.includes("declin")}function Ve(r){return r==="stripe"||r==="paypal"||r==="pcivault"?r:"other"}var D=class{constructor(e,n,t){this.currentElements=null;this.provider=e,this.config=n,this.telemetryReporter=t??new g({billingApiUrl:ye(n.billingApiUrl),sdkVersion:Be,enabled:n.telemetry!==!1}),ce(this,this.telemetryReporter,x)}now(){return this.telemetryReporter?.now?.()??x()}elements(e){return this.currentElements&&this.currentElements.destroy(),this.currentElements=new R(this.provider,{appearance:this.config.appearance,...e}),this.currentElements}async submitElements(){return this.provider.submitElements()}cardCapture(e){return this.telemetryReporter?.log({name:"vault.capture.requested",stage:"vault_request",provider:"pcivault",paymentMethodCategory:"card"}),this.telemetryReporter?te({sessionId:e?.sessionId,captureMethod:e?.captureMethod},this.telemetryReporter):new z({sessionId:e?.sessionId,captureMethod:e?.captureMethod,telemetry:!1})}async confirmPayPalPayment(e){let n=this.now();this.telemetryReporter?.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),this.telemetryReporter?.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});try{let t=await this.provider.confirmPayPalPayment(e);return this.telemetryReporter?.performance({stage:"processing",durationMs:this.now()-n,durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),t.error||this.telemetryReporter?.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),t.status==="requires_action"?(this.telemetryReporter?.log({name:"payment.three_ds.handoff",stage:"three_ds_handoff",provider:"paypal",paymentMethodCategory:"paypal"}),this.telemetryReporter?.log({name:"provider.redirect.started",stage:"redirect",provider:"paypal",paymentMethodCategory:"paypal"}),this.telemetryReporter?.terminal({outcome:"action_required",stage:"redirect",provider:"paypal",paymentMethodCategory:"paypal"})):t.status==="succeeded"?this.telemetryReporter?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}):t.status!=="processing"&&(S(t.error)?this.telemetryReporter?.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):t.error?.type==="validation_error"?this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal"}):t.error&&this.telemetryReporter?.error({errorCode:"PAYMENT_PROCESSING_FAILED",failureCategory:"provider_runtime",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"})),t}catch(t){if(this.telemetryReporter?.performance({stage:"processing",durationMs:this.now()-n,durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),t instanceof m&&S(t))this.telemetryReporter?.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"});else if(t instanceof m&&t.type==="validation_error")this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal"});else{let o=$(t,"PAYMENT_PROCESSING_FAILED","unknown");this.telemetryReporter?.error({...o,failureCategory:o.failureCategory??"provider_runtime",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"})}throw t}}async resumePayPalPayment(){let e=this.now();try{let n=await this.provider.resumePayPalPayment();return n===null?null:(this.telemetryReporter?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),this.telemetryReporter?.performance({stage:"redirect_resume",durationMs:this.now()-e,durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),n.status==="succeeded"?this.telemetryReporter?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}):S(n.error)?this.telemetryReporter?.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):n.error?.type==="validation_error"?this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal"}):n.error&&this.telemetryReporter?.error({errorCode:"REDIRECT_RESUME_FAILED",failureCategory:"provider_runtime",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),n)}catch(n){if(this.telemetryReporter?.performance({stage:"redirect_resume",durationMs:this.now()-e,durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),n instanceof m&&S(n))this.telemetryReporter?.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"});else if(n instanceof m&&n.type==="validation_error")this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal"});else{let t=$(n,"REDIRECT_RESUME_FAILED","unknown");this.telemetryReporter?.error({...t,failureCategory:t.failureCategory??"provider_runtime",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"})}throw n}}async confirmPayment(e){if(e.paymentMethodCategory!=="wallet"&&e.paymentMethodCategory!=="apm"||!e.paymentMethodType?.trim()||e.paymentMethodType.trim().toLowerCase()==="card")throw new m("A supported non-card payment method is required.","validation_error",{param:"paymentMethodType"});let n=this.now(),t=Ve(this.provider.name);this.telemetryReporter?.log({name:"payment.processing.started",stage:"processing",provider:t,paymentMethodCategory:e.paymentMethodCategory});try{let o=await this.provider.confirmPayment(e),a=this.now()-n;return this.telemetryReporter?.performance({stage:"processing",durationMs:a,durationMode:"machine",provider:t,paymentMethodCategory:e.paymentMethodCategory}),o.status==="succeeded"?this.telemetryReporter?.terminal({outcome:"payment_succeeded",provider:t,paymentMethodCategory:e.paymentMethodCategory}):S(o.error)?this.telemetryReporter?.terminal({outcome:"payment_declined",provider:t,paymentMethodCategory:e.paymentMethodCategory}):o.error?.type==="validation_error"?this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:t,paymentMethodCategory:e.paymentMethodCategory}):o.status==="requires_action"?(this.telemetryReporter?.log({name:"payment.three_ds.handoff",stage:"three_ds_handoff",provider:t,paymentMethodCategory:e.paymentMethodCategory}),this.telemetryReporter?.terminal({outcome:"action_required",stage:"three_ds_handoff",provider:t,paymentMethodCategory:e.paymentMethodCategory})):o.status==="failed"&&o.error&&this.telemetryReporter?.error({errorCode:"PAYMENT_PROCESSING_FAILED",failureCategory:"provider_runtime",stage:"processing",provider:t,paymentMethodCategory:e.paymentMethodCategory}),o.status==="succeeded"||o.status==="failed"?this.telemetryReporter?.log({name:"payment.processing.completed",stage:"processing",provider:t,paymentMethodCategory:e.paymentMethodCategory}):this.telemetryReporter?.log({name:"operation.state_transition",stage:o.status==="requires_action"?"three_ds_handoff":"processing",provider:t,paymentMethodCategory:e.paymentMethodCategory}),o}catch(o){throw this.telemetryReporter?.performance({stage:"processing",durationMs:this.now()-n,durationMode:"machine",provider:t,paymentMethodCategory:e.paymentMethodCategory}),o instanceof m&&S(o)?this.telemetryReporter?.terminal({outcome:"payment_declined",provider:t,paymentMethodCategory:e.paymentMethodCategory}):o instanceof m&&o.type==="validation_error"?this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:t,paymentMethodCategory:e.paymentMethodCategory}):this.telemetryReporter?.error({errorCode:"PAYMENT_PROCESSING_FAILED",failureCategory:"provider_runtime",stage:"processing",provider:t,paymentMethodCategory:e.paymentMethodCategory}),o}}async retrieveSession(e,n){if(!e)throw new m("sessionId is required to retrieve a session.","validation_error",{param:"sessionId"});let t=await this.retrieveUnifiedSession(e,n);if(!t.data.session)throw new m("Session not found","api_error");return t.data.session}async retrieveUnifiedSession(e,n){if(!e)throw new m("sessionId is required.","validation_error",{param:"sessionId"});let t=ye(n??this.config.billingApiUrl),o=this.now();this.telemetryReporter?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let a,l=ee(t,{now:()=>this.telemetryReporter?.now()??x(),onFirstByte:s=>{a=s},onRetry:(s,i)=>{this.telemetryReporter?.log({name:"operation.retry",stage:s==="session_read"?"session_read":"processing",requestCategory:s,attempt:i})}});try{let s=await l.getUnifiedCheckoutSession(e);return a!==void 0&&(this.telemetryReporter?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:"2xx"}),this.telemetryReporter?.performance({stage:"session_first_byte",durationMs:a,durationMode:"machine",requestCategory:"session_read",statusClass:"2xx"})),this.telemetryReporter?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:"2xx"}),this.telemetryReporter?.log({name:"checkout.data.ready",stage:"checkout_data_ready"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-o,durationMode:"machine",requestCategory:"session_read",statusClass:"2xx"}),s}catch(s){let i=$(s,s instanceof m&&s.code==="checkout_processing_timeout"?"REQUEST_TIMEOUT":"NETWORK_REQUEST_FAILED");throw this.telemetryReporter?.error({...i,stage:"session_read",provider:"flo",paymentMethodCategory:"unknown"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-o,durationMode:"machine",requestCategory:"session_read",statusClass:i.statusClass}),s}}getRawProvider(){return this.provider.getRawProvider()}destroy(){this.telemetryReporter?.log({name:"checkout.unmount",stage:"unmount"}),this.telemetryReporter?.destroy(),this.currentElements?.destroy(),this.currentElements=null,this.provider.destroy()}};function ue(r,e,n){let t=D;return new t(r,e,n)}import{FloPayError as We,resolveBillingApiUrl as G,SDK_VERSION as ge}from"@flopay/shared";import{FloPayError as p,isMoneySettledOutcome as $e,isSetupIntentClientSecret as Ye}from"@flopay/shared";import{loadStripe as Ge}from"@stripe/stripe-js";function he(r){return{payment:"payment",address:"address"}[r]}function q(r){switch(r){case"night":return"night";case"flat":return"flat";default:return"stripe"}}function He(r){return{...r,theme:q(r.theme)}}function Y(r){return r?JSON.stringify(r.map(e=>e.trim().toLowerCase())):null}function fe(r){let e=r;return{mount(n){e.mount(n)},unmount(){e.unmount()},update(n){e.update(n)},on(n,t){e.on?.(n,t)},off(n,t){e.off?.(n,t)},destroy(){e.destroy()}}}function Je(r){return{billing_details:{...r.email?{email:r.email}:{},...r.name?{name:r.name}:{},...r.address?{address:{...r.address.country?{country:r.address.country}:{},...r.address.postal_code?{postal_code:r.address.postal_code}:{},...r.address.city?{city:r.address.city}:{},...r.address.line1?{line1:r.address.line1}:{},...r.address.line2?{line2:r.address.line2}:{},...r.address.state?{state:r.address.state}:{}}}:{}}}}var T=class{constructor(){this.name="stripe";this.stripe=null;this.elements=null;this.appliedAppearanceKey=null;this.appliedPaymentMethodTypesKey=null;this.appliedClientSecret=null;this.verifiedClientSecret=null;this.verifiedPaymentMethodTypesKey=null}async initialize(e){if(typeof window>"u")return;let n=await Ge(e.publishableKey,{locale:e.locale??"auto"});if(!n)throw new p("Failed to initialize Stripe. Check your publishable key.","authentication_error");this.stripe=n}getElements(e){if(!this.stripe)throw new p("StripeAdapter not initialized. Call initialize() first.","api_error");let n=e?.appearance?{theme:q(e.appearance.theme),variables:e.appearance.variables,rules:e.appearance.rules}:void 0,t=n?JSON.stringify(n):null,o=Y(e?.paymentMethodTypes),a=e?.clientSecret??null;if(this.elements&&o&&(o!==this.appliedPaymentMethodTypesKey||a!==this.appliedClientSecret)&&(this.elements=null,this.appliedAppearanceKey=null,this.appliedPaymentMethodTypesKey=null,this.appliedClientSecret=null,this.verifiedClientSecret=null,this.verifiedPaymentMethodTypesKey=null),this.elements)t!==this.appliedAppearanceKey&&(this.elements.update({appearance:n??{}}),this.appliedAppearanceKey=t);else{let l,s=e?.amount??0,i=(e?.currency??"usd").toLowerCase(),d=e?.paymentMethodCreation??"manual";e?.clientSecret?l={clientSecret:e.clientSecret}:s>0?(l={mode:"payment",amount:s,currency:i,paymentMethodCreation:d},e?.setupFutureUsage&&(l.setupFutureUsage=e.setupFutureUsage)):l={mode:"setup",currency:i,paymentMethodCreation:d},!e?.clientSecret&&e?.paymentMethodTypes&&(l.paymentMethodTypes=e.paymentMethodTypes),n&&(l.appearance=n),this.elements=this.stripe.elements(l),this.appliedAppearanceKey=t,this.appliedPaymentMethodTypesKey=o,this.appliedClientSecret=a,this.verifiedClientSecret=null,this.verifiedPaymentMethodTypesKey=null}return this.elements}async assertClientSecretPaymentMethods(e,n){if(!this.stripe)throw new p("StripeAdapter not initialized. Call initialize() first.","api_error");let t,o=!1;if(Ye(e)){let{setupIntent:i,error:d}=await this.stripe.retrieveSetupIntent(e);t=i,o=!!d}else{let{paymentIntent:i,error:d}=await this.stripe.retrievePaymentIntent(e);t=i,o=!!d}let a=t?.payment_method_types;if(o||!Array.isArray(a))throw new p("Unable to verify the payment methods configured for this client secret.","api_error",{param:"clientSecret"});let l=new Set(n.map(i=>i.toLowerCase()));if(a.some(i=>typeof i!="string"||!l.has(i.trim().toLowerCase()))||a.length===0)throw new p("The client-secret intent must enable only declared non-card payment methods.","validation_error",{param:"clientSecret"})}async createElement(e,n){let t=n;if(e==="payment"){let i=n.paymentMethodTypes?.map(d=>d.trim()).filter(d=>d&&d.toLowerCase()!=="card");if(!i?.length)throw new p("At least one supported non-card payment method is required.","validation_error",{param:"paymentMethodTypes"});if(t={...n,paymentMethodTypes:i},t.clientSecret){let d=Y(i);this.elements&&this.appliedClientSecret===t.clientSecret&&this.appliedPaymentMethodTypesKey===d&&this.verifiedClientSecret===t.clientSecret&&this.verifiedPaymentMethodTypesKey===d||await this.assertClientSecretPaymentMethods(t.clientSecret,i)}}let o=this.getElements(t);e==="payment"&&t.clientSecret&&(this.verifiedClientSecret=t.clientSecret,this.verifiedPaymentMethodTypesKey=Y(t.paymentMethodTypes));let a=he(e),l={};t.layout&&(l.layout=t.layout),t.defaultValues&&(l.defaultValues=t.defaultValues),t.readOnly&&(l.readOnly=t.readOnly),t.mode&&(l.mode=t.mode);let s=o.create(a,l);return fe(s)}getElement(e){if(!this.elements)return null;let n=he(e),t=this.elements.getElement(n);return t?fe(t):null}async submitElements(){if(!this.stripe||!this.elements)return{error:new p("Stripe not initialized","api_error")};let{error:e}=await this.elements.submit();return e?{error:new p(e.message??"Validation failed","validation_error")}:{}}async confirmPayment(e){if(!this.stripe||!this.elements)throw new p("StripeAdapter not initialized or no elements created.","api_error");let n=e.billingDetails,t=n?Je(n):void 0,{error:o,paymentIntent:a}=await this.stripe.confirmPayment({elements:this.elements,clientSecret:e.clientSecret,confirmParams:{return_url:e.returnUrl??window.location.href,...t?{payment_method_data:t}:{}},redirect:"if_required"});return o?{status:"failed",error:new p(o.message??"Payment failed","api_error",{code:o.code,declineCode:o.decline_code})}:a?{status:{succeeded:"succeeded",processing:"processing",requires_action:"requires_action",requires_payment_method:"failed",canceled:"failed"}[a.status]??"failed",paymentIntentId:a.id,paymentMethodId:this.extractPaymentMethodId(a.payment_method)}:{status:"failed",error:new p("No payment intent returned","api_error")}}extractPaymentMethodId(e){if(typeof e=="string"&&e.startsWith("pm_"))return e;if(e&&typeof e=="object"&&typeof e.id=="string")return e.id}async confirmPayPalPayment(e){if(!this.stripe)return{status:"failed",error:new p("Stripe not initialized","api_error")};let n=e.billingApiUrl.replace(/\/+$/,"");if(this.elements){let{error:a}=await this.elements.submit();if(a)return{status:"failed",error:new p(a.message??"PayPal payment failed","validation_error",{code:a.code})}}let t;try{let a=await new O(n).createSessionIntent(e.sessionId,e.nonce??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"});if(a.provider!=="stripe")throw new p("Invalid provider returned for PayPal intent","api_error");t=a.clientSecret}catch(a){return{status:"failed",error:a instanceof p?a:new p("Failed to create PayPal payment intent","api_error")}}let{error:o}=await this.stripe.confirmPayment({clientSecret:t,elements:this.elements??void 0,confirmParams:{return_url:e.returnUrl}});if(o){if(e.nonce)try{await new O(n).reportSessionIntentDecline(e.sessionId,e.nonce,{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:o.code??"provider_declined"})}catch{}return{status:"failed",error:new p(o.message??"PayPal payment failed","api_error",{code:o.code})}}return{status:"processing"}}async resumePayPalPayment(){if(!this.stripe||typeof window>"u")return null;let e=new URLSearchParams(window.location.search),n=e.get("payment_intent"),t=e.get("payment_intent_client_secret"),o=e.get("redirect_status");if(!n||!t)return null;if(o==="failed")return{status:"failed",error:new p("PayPal payment was declined. Please try again.","api_error")};let{paymentIntent:a,error:l}=await this.stripe.retrievePaymentIntent(t);if(l)return{status:"failed",error:new p(l.message??"Failed to retrieve PayPal payment","api_error")};if(a&&$e(a.status)){let s=typeof a.payment_method=="string"?a.payment_method:a.payment_method?.id,i=new URL(window.location.href);return i.searchParams.delete("payment_intent"),i.searchParams.delete("payment_intent_client_secret"),i.searchParams.delete("redirect_status"),window.history.replaceState({},"",i.toString()),{status:a.status,paymentIntentId:a.id,paymentMethodId:s}}return{status:"failed",error:new p("PayPal payment was not completed. Please try again.","api_error")}}getRawProvider(){return this.stripe}createPayPalElements(e){if(!this.stripe)return null;let n={mode:"payment",amount:e.amount??0,currency:(e.currency??"usd").toLowerCase(),captureMethod:"manual"};return e.setupFutureUsage&&(n.setupFutureUsage=e.setupFutureUsage),e.appearance&&(n.appearance={theme:q(e.appearance.theme),variables:e.appearance.variables,rules:e.appearance.rules}),this.stripe.elements(n)}destroy(){this.elements=null,this.appliedAppearanceKey=null,this.appliedPaymentMethodTypesKey=null,this.appliedClientSecret=null,this.verifiedClientSecret=null,this.verifiedPaymentMethodTypesKey=null,this.stripe=null}};var Ce=new Map;function H(r){return Array.isArray(r)?r.map(H):r&&typeof r=="object"?Object.fromEntries(Object.entries(r).filter(([,e])=>e!==void 0).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>[e,H(n)])):r}function Qe(r,e){return JSON.stringify([r,G(e?.billingApiUrl),e?.telemetry!==!1,e?.locale??"auto",e?.apiVersion??null,H(e?.appearance??null)])}var L=new Map;async function Xe(r,e){if(!r){let s=new g({billingApiUrl:G(e?.billingApiUrl),sdkVersion:ge,enabled:e?.telemetry!==!1});throw s.error({errorCode:"CONFIGURATION_INVALID",stage:"sdk_initialize",paymentMethodCategory:"unknown"}),s.flush().catch(()=>{}).finally(()=>s.destroy()),new We("A publishable key is required to initialize FloPay.","validation_error",{param:"publishableKey"})}let n=Qe(r,e),t=Ce.get(n);if(t)return e?.telemetry!==!1&&me(t)?.log({name:"sdk.cache.hit",stage:"sdk_initialize"}),t;let o=L.get(n);if(o)return o;let a={...e,publishableKey:r},l=(async()=>{let s=new g({billingApiUrl:G(a.billingApiUrl),sdkVersion:ge,enabled:a.telemetry!==!1}),i=s.now();s.log({name:"sdk.initialize.started",stage:"sdk_initialize"}),s.log({name:"sdk.cache.miss",stage:"sdk_initialize"}),s.log({name:"provider.load.started",stage:"provider_load",provider:"stripe"});let d=new T,h=s.now();try{await d.initialize(a)}catch(f){throw s.error({errorCode:"SDK_INITIALIZATION_FAILED",failureCategory:"provider_runtime",stage:"sdk_initialize",provider:"stripe",paymentMethodCategory:"unknown"}),s.destroy(),f}let C=s.now();s.log({name:"provider.ready",stage:"provider_ready",provider:"stripe"}),s.log({name:"provider.availability.checked",stage:"provider_ready",provider:"stripe"}),s.log({name:"sdk.initialize.ready",stage:"sdk_initialize"}),s.performance({stage:"sdk_initialize",durationMs:C-i,durationMode:"machine",provider:"stripe"}),s.performance({stage:"provider_ready",durationMs:C-h,durationMode:"machine",provider:"stripe"});let y=ue(d,a,s);return Ce.set(n,y),y})();L.set(n,l);try{return await l}finally{L.get(n)===l&&L.delete(n)}}export{D as FloPay,R as FloPayElements,O as PaymentAPI,z as PciVaultCardCapture,ke as SESSION_CREATE_TELEMETRY,T as StripeAdapter,j as cacheSessionDisplayData,Te as clearSessionDisplayData,Ke as createCheckoutSession,je as createCheckoutSessionWithRetries,Tt as dropThirdPartyOnlyError,Re as getSessionDisplayData,Xe as loadFloPay,He as toStripeAppearance,q as toStripeAppearanceTheme};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@flopay/js",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.7.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"sideEffects": false,
|
|
6
6
|
"publishConfig": {
|
|
@@ -32,7 +32,7 @@
|
|
|
32
32
|
],
|
|
33
33
|
"dependencies": {
|
|
34
34
|
"@stripe/stripe-js": "^9.8.0",
|
|
35
|
-
"@flopay/shared": "1.
|
|
35
|
+
"@flopay/shared": "1.7.0"
|
|
36
36
|
},
|
|
37
37
|
"devDependencies": {
|
|
38
38
|
"jsdom": "^29.1.1",
|
package/dist/chunk-G6M32WZN.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var we="flopay_session_display:";var I=new Map;function P(s){return`${we}${s}`}function V(){if(typeof window>"u")return null;try{return window.sessionStorage}catch{return null}}function N(s,e,t){if(!s)return;let r=t?.ttlMs??36e5,n={data:e,expiresAt:Date.now()+r},o=V();if(o)try{o.setItem(P(s),JSON.stringify(n));return}catch{}I.set(s,n)}function Q(s){if(!s)return null;let e=V();if(e)try{let r=e.getItem(P(s));if(r){let n=JSON.parse(r);if(n&&typeof n.expiresAt=="number"&&n.expiresAt>Date.now())return n.data;e.removeItem(P(s))}}catch{}let t=I.get(s);if(t){if(t.expiresAt>Date.now())return t.data;I.delete(s)}return null}function X(s){if(!s)return;I.delete(s);let e=V();if(e)try{e.removeItem(P(s))}catch{}}import{FloPayError as h,SDK_VERSION as M,FLO_SDK_VERSION_HEADER as j,IDEMPOTENCY_KEY_HEADER as oe,IDEMPOTENCY_IN_PROGRESS_CODE as je,assertCaptureMethodEligible as ie,buildProductPayload as me,classifyPaymentRejection as He,classifyTelemetryFailure as w,foldIntoProducts as H,isDetachedSessionEligible as Ke,isUuidV4 as ae,normalizeCheckoutFailureOutcome as ce,randomUuidV4 as $e,resolveIdempotencyKey as Ge,resolveSessionCurrency as K,telemetryStatusClass as b}from"@flopay/shared";function Z(s){return typeof s=="string"&&s.trim()?s:void 0}function ee(s){if(typeof s=="string")return s.trim()?s:void 0;if(Array.isArray(s))return s.filter(t=>typeof t=="string"&&t.trim().length>0).join("; ")||void 0}import{buildTelemetryErrorEvent as te,buildTelemetryLogEvent as Re,buildTelemetryPerformanceEvent as Ie,buildTelemetryTerminalEvent as Pe,serializeTelemetryBatch as De,TELEMETRY_MAX_BATCH_BYTES as xe}from"@flopay/shared";var qe="/v1/sdk-telemetry/events",z=16,Oe=64,Fe=1500,re=1e3,Ue=64,Le="00000000-0000-4000-8000-000000000000",Ve={technical_error:8,lifecycle:32,expected_outcome:32,performance:24};function S(){try{return globalThis.crypto.randomUUID()}catch{let s=new Uint8Array(16);try{globalThis.crypto.getRandomValues(s)}catch{for(let t=0;t<s.length;t+=1)s[t]=Math.floor(Math.random()*256)}s[6]=s[6]&15|64,s[8]=s[8]&63|128;let e=[...s].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 Ne(s){try{return new TextEncoder().encode(s).byteLength}catch{return s.length}}function ze(s){return JSON.stringify([s.code,s.failureCategory,s.stage,s.provider,s.attempt,s.statusClass,s.requestCategory,s.paymentMethodCategory,s.checkoutMode,s.layout])}function v(){return globalThis.performance?.now()??0}var T=class{constructor(e){this.ingestionDisabled=!1;this.queue=[];this.sequence=0;this.flushTimer=null;this.flushInFlight=null;this.reportedFailures=new Map;this.checkoutContext={};this.checkoutStartedAt=null;this.destroyed=!1;this.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(/\/+$/,"")}${qe}`,this.sdkPackage=e.sdkPackage??"@flopay/js",this.sdkVersion=e.sdkVersion,this.correlationId=S(),this.merchantEnabled=e.enabled!==!1,this.clock=e.clock??v,this.browserTransportAvailable=typeof window<"u"&&typeof document<"u",this.browserTransportAvailable&&(window.addEventListener("pagehide",this.pageExitHandler),document.addEventListener("visibilitychange",this.visibilityHandler))}log(e){this.canCollect()&&this.enqueue(Re({...this.checkoutContext,...e,eventId:S(),sequence:this.sequence++}))}error(e){if(!this.canCollect())return;let t=te({...this.checkoutContext,...e,eventId:Le,sequence:0}),r=ze(t),n=this.now();this.pruneReportedFailures(n);let o=this.reportedFailures.get(r);if(o!==void 0&&n>=o&&n-o<re){this.log({name:"operation.deduplicated",stage:e.stage,provider:e.provider,paymentMethodCategory:e.paymentMethodCategory,attempt:e.attempt});return}this.rememberReportedFailure(r,n),this.enqueue(te({...this.checkoutContext,...e,eventId:S(),sequence:this.sequence++}))}performance(e){this.canCollect()&&this.enqueue(Ie({...this.checkoutContext,...e,eventId:S(),sequence:this.sequence++}))}terminal(e){if(this.canCollect()&&(this.enqueue(Pe({...this.checkoutContext,...e,eventId:S(),sequence:this.sequence++})),e.outcome!=="action_required"&&this.checkoutStartedAt!==null)){let t=this.checkoutStartedAt;this.checkoutStartedAt=null,this.performance({stage:"total_journey",durationMs:Math.max(0,this.now()-t),durationMode:"total",provider:e.provider,paymentMethodCategory:e.paymentMethodCategory})}}now(){try{return this.clock()}catch{return v()}}pruneReportedFailures(e){for(let[t,r]of this.reportedFailures)(e<r||e-r>=re)&&this.reportedFailures.delete(t)}rememberReportedFailure(e,t){for(;this.reportedFailures.size>=Ue;){let r=this.reportedFailures.keys().next();if(r.done)break;this.reportedFailures.delete(r.value)}this.reportedFailures.set(e,t)}setCheckoutContext(e){this.checkoutContext={checkoutMode:e.checkoutMode,layout:e.layout}}beginCheckout(e={}){return this.canCollect()?(this.drainQueue(),this.setCheckoutContext(e),this.sequence=0,this.reportedFailures.clear(),this.eventCounts={technical_error:0,lifecycle:0,expected_outcome:0,performance:0},this.checkoutStartedAt=this.now(),this.checkoutStartedAt):0}enqueue(e){if(this.canCollect()&&!(this.queue.length>=Oe||this.eventCounts[e.class]>=Ve[e.class])){if(this.eventCounts[e.class]+=1,this.queue.push(e),this.queue.length>=z){this.flush();return}this.scheduleFlush()}}canCollect(){return this.browserTransportAvailable&&this.merchantEnabled&&!this.ingestionDisabled&&!this.destroyed}async flush(){if(this.flushInFlight)return this.flushInFlight;if(!this.browserTransportAvailable||this.destroyed||this.ingestionDisabled||this.queue.length===0)return;this.clearFlushTimer();let e=this.queue.splice(0,z);return this.flushInFlight=this.sendBatch(e).finally(()=>{this.flushInFlight=null,this.queue.length>0&&this.scheduleFlush()}),this.flushInFlight}destroy(){this.destroyed||(this.drainQueue(),this.destroyed=!0,this.clearFlushTimer(),this.browserTransportAvailable&&(window.removeEventListener("pagehide",this.pageExitHandler),document.removeEventListener("visibilitychange",this.visibilityHandler)),this.queue.splice(0),this.reportedFailures.clear())}disable(){this.merchantEnabled=!1,this.queue.splice(0),this.reportedFailures.clear(),this.clearFlushTimer()}drainQueue(){if(!(!this.browserTransportAvailable||this.destroyed||this.ingestionDisabled||this.queue.length===0))for(this.clearFlushTimer();this.queue.length>0;){let e=this.queue.splice(0,z);this.sendBatch(e)}}async sendBatch(e){if(!this.browserTransportAvailable||this.ingestionDisabled)return;let t=De(e,{correlationId:this.correlationId,sdkPackage:this.sdkPackage,sdkVersion:this.sdkVersion,batchId:S()});if(Ne(t)>xe)return;let r=typeof AbortController>"u"?null:new AbortController,n=null;try{let o=fetch(this.endpoint,{method:"POST",headers:{"content-type":"text/plain;charset=UTF-8"},body:t,credentials:"omit",keepalive:!0,referrerPolicy:"no-referrer",signal:r?.signal}).then(async c=>c.status!==202?null:(await c.json().catch(()=>null))?.status==="disabled"?"disabled":null).catch(()=>null),i=new Promise(c=>{n=setTimeout(()=>{r?.abort(),c(null)},Fe)});await Promise.race([o,i])==="disabled"&&this.disableFromIngestion()}catch{}finally{n&&clearTimeout(n)}}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)}},se=Symbol.for("@flopay/js.telemetry.reporter-factory.v1"),ne=globalThis;ne[se]===void 0&&Object.defineProperty(ne,se,{configurable:!0,enumerable:!1,writable:!1,value:s=>new T(s)});function D(s=12e3){let e=Number.isFinite(s)&&s>=0?s:12e3,t=new AbortController,r=setTimeout(()=>t.abort(),e);return{signal:t.signal,clear:()=>clearTimeout(r)}}function Be(){return Object.assign(new Error("The operation was aborted."),{name:"AbortError"})}function x(s,e){let t=150*2**s,r=Math.round(t*(.75+Math.random()*.5));return new Promise((n,o)=>{let i,a=()=>e.removeEventListener("abort",c),c=()=>{i!==void 0&&clearTimeout(i),a(),o(Be())};if(e.aborted){c();return}i=setTimeout(()=>{a(),n()},r),e.addEventListener("abort",c,{once:!0})})}var ue=1e3,Ye=500,We=15e3,Je=3e3,Qe=1e4,Xe=1e4;function Ze(s){return typeof s=="object"&&s!==null}function A(s,e){return Z(s?.[e])}function le(s,e){return ee(s?.[e])}function et(s,e){let t=s?.[e];return typeof t=="number"&&Number.isFinite(t)?t:void 0}function pe(s){return new Promise(e=>setTimeout(e,s))}function q(){return new h("Checkout is still processing. Please try again shortly.","api_error",{code:"checkout_processing_timeout"})}async function _(s,e){let t=await s.json().catch(()=>null),r=Ze(t?.error)?t.error:null,n=le(t,"message")??le(r,"message")??e,o=A(t,"code")??A(t,"gatewayErrorCode")??A(r,"code")??`http_${s.status}`;return new h(n,"api_error",{code:o,statusCode:s.status})}async function tt(s){let e=s.status===400?await s.clone().json().catch(()=>null):null;return He(s.status,e)}function de(s){return s===400||s===422}var O=2;async function $(s,e,t=O,r){let n;for(let o=0;;o++)try{return await fetch(s,e)}catch(i){if(e?.signal?.aborted||i instanceof Error&&i.name==="AbortError")throw i;if(n=i,o>=t)throw n;try{r?.(o+1)}catch{}await pe(150*2**o)}}var rt=Symbol.for("@flopay/js.session-create.telemetry.v1");function st(s){return s[rt]}function nt(s){return"now"in s||"onFirstByte"in s||"onSessionCreateFailure"in s||"onRetry"in s}function he(s){return{userId:s.userId,firstName:s.firstName??null,lastName:s.lastName??null,email:s.email,country:s.country??null,gender:s.gender??null,city:s.city??null,state:s.state??null,zip:s.zip??null,addressLine1:s.addressLine1??null,addressLine2:s.addressLine2??null}}function ye(s,e){e.tagsData&&(s.tagsData=e.tagsData),e.utmMetadata?.length&&(s.utmMetadata=e.utmMetadata),e.avsCheck!==void 0&&(s.avsCheck=e.avsCheck),e.checkoutType&&(s.checkoutType=e.checkoutType),e.checkoutLayout&&(s.checkoutLayout=e.checkoutLayout),e.avsConfig&&(s.avsConfig=e.avsConfig)}function ot(s,e){let t={clientId:s.clientId,checkoutVersion:M,successUrl:s.successUrl,cancelUrl:s.cancelUrl,currency:e,checkoutMode:"full",deferDataAttachment:!0};return s.captureMethod==="manual"&&(t.captureMethod=s.captureMethod),s.account.country&&(t.accountData={country:s.account.country}),ye(t,s),t}function it(s,e,t){return{currency:e,products:t.map(r=>me(r,e)),couponCodes:s.couponCodes??[],accountData:he(s.account)}}var k=class k{constructor(e,t={}){this.baseUrl=e.replace(/\/+$/,"");let r=nt(t);this.telemetryHooks=r?t:void 0,this.directTelemetry=r||t.telemetry===!1?void 0:new T({billingApiUrl:this.baseUrl,sdkVersion:M})}destroy(){this.directTelemetry?.destroy()}reportDirectFailure(e,t,r,n,o="unknown"){let i=w(e,t);this.directTelemetry?.error({...i,stage:r,requestCategory:n,paymentMethodCategory:o})}reportAccountSnapshotFailure(e,t){let r=w(e,"NETWORK_REQUEST_FAILED");if(t==="best_effort"&&r.errorCode==="REQUEST_TIMEOUT"){this.directTelemetry?.log({name:"operation.fallback",stage:"processing",requestCategory:"account_snapshot",statusClass:"timeout"});return}this.directTelemetry?.error({...r,stage:"processing",requestCategory:"account_snapshot",paymentMethodCategory:"unknown"})}telemetryTimestamp(){try{return this.telemetryHooks?.now?.()??this.directTelemetry?.now()??v()}catch{return v()}}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){this.beginDirectTelemetryCheckout(e);let r=this.telemetryTimestamp();this.directTelemetry?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let n={[j]:M};t&&(n["x-checkout-session-token"]=t);try{let o=await $(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}`,{headers:n},O,u=>{this.telemetryHooks?.onRetry?.("session_read",u),this.directTelemetry?.log({name:"operation.retry",stage:"session_read",requestCategory:"session_read",attempt:u})}),i=Math.max(0,this.telemetryTimestamp()-r);try{this.telemetryHooks?.onFirstByte?.(i)}catch{}let a=`${Math.floor(o.status/100)}xx`;if(this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:a}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:i,durationMode:"machine",requestCategory:"session_read",statusClass:a}),!o.ok)throw await _(o,"Failed to get checkout session");let c=await o.json();return this.directTelemetry?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:a}),this.directTelemetry?.performance({stage:"session_complete",durationMs:Math.max(0,this.telemetryTimestamp()-r),durationMode:"machine",requestCategory:"session_read",statusClass:a}),{...c,data:this.mergeCachedDisplayData(c.data)}}catch(o){throw this.directTelemetry?.error({...w(o,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"}),o}}cacheSessionDisplayData(e,t,r){N(e,t,r)}clearSessionDisplayData(e){X(e)}async getVaultCapture(e,t){let r=`${this.baseUrl}\0${e}\0${t??""}`,n=k.activeVaultCaptureRequests.get(r);if(n)return n;let o=this.requestVaultCapture(e,t);k.activeVaultCaptureRequests.set(r,o);try{return await o}finally{k.activeVaultCaptureRequests.get(r)===o&&k.activeVaultCaptureRequests.delete(r)}}async requestVaultCapture(e,t){let r=new AbortController,n=setTimeout(()=>r.abort(),Xe);this.beginDirectTelemetryCheckout(e);let o=this.telemetryTimestamp();this.directTelemetry?.log({name:"vault.capture.requested",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card"});let i={"Content-Type":"application/json"};t&&(i["x-checkout-session-token"]=t);try{let a=await $(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/vault/capture`,{method:"POST",headers:i,signal:r.signal},O,u=>{this.telemetryHooks?.onRetry?.("vault_capture",u),this.directTelemetry?.log({name:"operation.retry",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card",attempt:u})});if(!a.ok)throw await _(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()-o),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"2xx"}),this.toVaultBlock(c)}catch(a){let c=r.signal.aborted?new h("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(n)}}async getUnifiedCheckoutSession(e,t){let r=await this.getCheckoutSession(e,t),n=this.normalizeRawSession(r.data),o=r.vault;return o&&n.data.session&&(n.data.session.vault=this.toVaultBlock(o)),n}async processPayment(e,t,r){if(this.beginDirectTelemetryCheckout(t.sessionId),!t.nonce)throw this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"process_payment"}),new h("processPayment requires `nonce` \u2014 pass the value returned from session creation.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let n=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.processing.started",stage:"processing",requestCategory:"process_payment"});let{nonce:o,...i}=t,a;try{a=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(i)})}catch(c){throw this.reportDirectFailure(c,"PAYMENT_PROCESSING_FAILED","processing","process_payment"),c}if(!a.ok&&a.status!==202){let c=await tt(a);return c?this.directTelemetry?.terminal({outcome:c,stage:"processing",requestCategory:"process_payment",statusClass:"4xx"}):this.directTelemetry?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",requestCategory:"process_payment",statusClass:b(a.status),failureCategory:a.status>=500?"server_error":void 0}),a}try{let c=await this.resolveProcessResponse(a,t.sessionId,{...r,nonce:o});return this.directTelemetry?.log({name:"payment.processing.completed",stage:"processing",requestCategory:"process_payment",statusClass:b(c.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-n),durationMode:"machine",requestCategory:"process_payment",statusClass:b(c.status)}),c}catch(c){throw c instanceof h&&c.code==="checkout_processing_timeout"||this.reportDirectFailure(c,"PAYMENT_PROCESSING_FAILED","processing","process_payment"),c}}async patchAccountSnapshot(e,t,r,n){this.beginDirectTelemetryCheckout(e);let o=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.state_transition",stage:"processing",requestCategory:"account_snapshot"});let i=n?.timeoutMs??Qe,a=new AbortController,c=()=>a.abort();n?.signal&&(n.signal.aborted?a.abort():n.signal.addEventListener("abort",c,{once:!0}));let u=setTimeout(()=>a.abort(),i);try{let l;try{l=await $(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/account`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":t},body:JSON.stringify(r),signal:a.signal},O,p=>{this.telemetryHooks?.onRetry?.("account_snapshot",p),this.directTelemetry?.log({name:"operation.retry",stage:"processing",requestCategory:"account_snapshot",attempt:p})})}finally{clearTimeout(u),n?.signal?.removeEventListener("abort",c)}if(!l.ok)throw await _(l,"Failed to persist account snapshot");this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"account_snapshot",statusClass:"2xx"})}catch(l){throw this.reportAccountSnapshotFailure(l,n?.telemetryMode??"blocking"),l}}async createSessionIntent(e,t,r,n){if(!t)throw new h("createSessionIntent requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let o=r,i=o.paymentMethodType,a=typeof i=="string"&&i.trim().toLowerCase()==="card",c=typeof i=="string"&&i.length>0&&!a&&(typeof o.paymentMethodId=="string"||o.paymentMethodId===null),u=o.provider==="stripe"&&(o.paymentMethodCategory==="wallet"||o.paymentMethodCategory==="apm")&&(o.intentKind==="payment"||o.intentKind==="setup"),l=o.provider==="paypal"&&o.paymentMethodCategory==="wallet"&&o.paymentMethodType==="paypal"&&o.paymentMethodId===null&&o.intentKind==="payment";if(!c||!u&&!l)throw new h("Only wallet, APM, and PayPal session intents are supported.","validation_error",{code:"InvalidSessionIntentRequest"});let p=o.authorizationAttemptId;if(p!==void 0&&!ae(p))throw new h("authorizationAttemptId must be a v4 UUID identifying one buyer authorization attempt.","validation_error",{code:"InvalidAuthorizationAttemptId",param:"authorizationAttemptId"});let d=ae(p)?p:$e();this.beginDirectTelemetryCheckout(e);let m=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.intent.started",stage:"processing",requestCategory:"intent_create"});let C={"Content-Type":"application/json","x-checkout-session-token":t,[oe]:n?.idempotencyKey||d},g=!1;try{let f=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents`,{method:"POST",headers:C,body:JSON.stringify({...r,authorizationAttemptId:d}),signal:n?.signal});if(!f.ok){g=!0;let L=await _(f,"Failed to create checkout intent"),Ee=w(L,"PAYMENT_PROCESSING_FAILED");throw de(L.statusCode)?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"intent_create",statusClass:"4xx"}):this.directTelemetry?.error({...Ee,stage:"processing",requestCategory:"intent_create"}),L}let U=(await f.json()).data;if(!U||typeof U!="object")throw new h("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});let y=U,J=y.paymentMethodType,ke=(y.paymentMethodCategory==="wallet"||y.paymentMethodCategory==="apm")&&typeof J=="string"&&J.trim().toLowerCase()!=="card"&&(typeof y.paymentMethodId=="string"||y.paymentMethodId===null)&&typeof y.providerObjectId=="string",Se=y.provider==="stripe"&&(y.intentKind==="payment"||y.intentKind==="setup")&&typeof y.clientSecret=="string",Me=y.provider==="paypal"&&y.paymentMethodCategory==="wallet"&&y.paymentMethodType==="paypal"&&y.paymentMethodId===null&&y.intentKind==="payment"&&(y.providerObjectType==="order"||y.providerObjectType==="subscription")&&y.clientSecret===null,Ae=y.provider===r.provider&&y.paymentMethodCategory===r.paymentMethodCategory&&y.paymentMethodType===r.paymentMethodType&&y.paymentMethodId===r.paymentMethodId&&y.intentKind===r.intentKind;if(!ke||!Se&&!Me||!Ae)throw new h("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});return this.directTelemetry?.log({name:"payment.intent.completed",stage:"processing",requestCategory:"intent_create",statusClass:b(f.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-m),durationMode:"machine",requestCategory:"intent_create",statusClass:b(f.status)}),y}catch(f){throw g||this.reportDirectFailure(f,"PAYMENT_PROCESSING_FAILED","processing","intent_create"),f}}async reportSessionIntentDecline(e,t,r,n){if(!t)throw new h("reportSessionIntentDecline requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let o=r,i=o.providerDeclineReason,a=o.paymentMethodType,c=typeof i=="string"&&/^[a-z0-9][a-z0-9_.:-]{0,63}$/i.test(i)&&!/^(?:pm|pi|seti|tok|src|cus|sess|sk|pk)_/i.test(i),u=typeof a=="string"&&a.length>0&&a.trim().toLowerCase()!=="card"&&c,l=o.provider==="stripe"&&(o.paymentMethodCategory==="wallet"||o.paymentMethodCategory==="apm"),p=o.provider==="paypal"&&o.paymentMethodCategory==="wallet"&&o.paymentMethodType==="paypal";if(!u||!l&&!p)throw new h("Invalid non-card decline classification.","validation_error",{code:"InvalidSessionIntentDeclineRequest"});let d=p?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:i}:{provider:"stripe",paymentMethodCategory:o.paymentMethodCategory,paymentMethodType:o.paymentMethodType,providerDeclineReason:i},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(d),signal:n?.signal});if(!m.ok)throw await _(m,"Failed to report checkout decline")}async getPaymentsByEmail(e,t){this.beginDirectTelemetryOperation();let r=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved"});let n=t?.page??1,o=t?.limit??1,i=new URLSearchParams({email:e,page:String(n),limit:String(o),sortField:"createdAt",sortDirection:"DESC"});try{let a=await fetch(`${this.baseUrl}/v1/payments?${i.toString()}`,{method:"GET",signal:t?.signal,keepalive:!0});if(!a.ok)throw new h("Failed to fetch payments","api_error",{statusCode:a.status});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()-r),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(Ke(e))return(await this.createDetachedSession(e)).claimed;this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp(),r=D(e.timeoutMs??12e3),n={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});try{let o=await this.createAndFetchSessionRequest(e,t,r.signal,n);return this.adoptDirectTelemetryCheckout(o.data.session?.id),this.directTelemetry?.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:n.statusClass}),this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:"session_create",statusClass:n.statusClass,attempt:n.attempt}),o}catch(o){throw this.reportSessionCreateFailure(o,t,n),o}finally{r.clear()}}async createAndFetchSessionRequest(e,t,r,n){let o=e.products??H(e.items,e.subscriptions);ie({captureMethod:e.captureMethod,products:o});let i=K(e.currency,e.items,e.subscriptions,o);if(!i)throw new h("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 a={clientId:e.clientId,checkoutVersion:M,successUrl:e.successUrl,cancelUrl:e.cancelUrl,currency:i,checkoutMode:e.checkoutMode??"full",products:o.map(d=>me(d,i)),accountData:he(e.account),couponCodes:e.couponCodes??[]};e.captureMethod==="manual"&&(a.captureMethod=e.captureMethod),e.tokenizedData&&(a.tokenizedData=e.tokenizedData),ye(a,e);let u=await(await this.postCheckoutSessionCreate(a,e,t,r,n)).json();if(u.data&&"gateways"in u.data){this.autoCacheDisplayData(u.data.uuid,e);let d=this.mergeCachedDisplayData(u.data),m=this.normalizeRawSession(d);return u.vault&&m.data.session&&(m.data.session.vault=this.toVaultBlock(u.vault)),{...m,autoProcessingError:u.autoProcessingError,autoProcessingAttempted:u.autoProcessingAttempted,autoProcessingPending:u.autoProcessingPending}}let l=u.data?.uuid;if(!l)throw new h("No session ID returned","api_error",{code:"InvalidCheckoutSessionResponse"});return this.autoCacheDisplayData(l,e),this.adoptDirectTelemetryCheckout(l),{...await this.getUnifiedCheckoutSession(l),autoProcessingError:u.autoProcessingError,autoProcessingAttempted:u.autoProcessingAttempted,autoProcessingPending:u.autoProcessingPending}}async postCheckoutSessionCreate(e,t,r,n,o){let i={"Content-Type":"application/json",[j]:M},a=Ge(t.idempotencyKey);a&&(i[oe]=a);let c,u=!1,l=st(t),p=d=>{try{this.telemetryHooks?.onRetry?.("session_create",d),this.directTelemetry?.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:d})}catch{}};for(let d=0;d<3;d++){o.attempt=d;try{l?.onAttempt?.(d)}catch{}try{c=await fetch(`${this.baseUrl}/v1/checkouts/sessions?expand=true`,{method:"POST",headers:i,body:JSON.stringify(e),signal:n})}catch(g){if(o.statusClass=n.aborted||g instanceof Error&&g.name==="AbortError"?"timeout":"network_error",n.aborted||g instanceof Error&&g.name==="AbortError"||d>=2)throw g;let f=d+1;p(f),await x(d,n);continue}let m=b(c.status);if(o.statusClass=m,u||(u=!0,this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:m,attempt:d}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:Math.max(0,this.telemetryTimestamp()-r),durationMode:"machine",requestCategory:"session_create",statusClass:m,attempt:d})),c.status===204)throw new h("Session auto-completed \u2014 payment method already on file","api_error",{code:"session_auto_completed"});if(c.ok)break;let C=await _(c,"Failed to create checkout session");if(C.code===je&&d<2){p(d+1),await x(d,n);continue}throw C}if(!c)throw new TypeError("Checkout-session creation exhausted its retry budget.");return c}async createDetachedSession(e){this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp(),r=D(e.timeoutMs??12e3),n={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let o=e.products??H(e.items,e.subscriptions);try{ie({captureMethod:e.captureMethod,products:o})}catch(m){throw r.clear(),this.reportSessionCreateFailure(m,t,n),m}let i=K(e.currency,e.items,e.subscriptions,o);if(!i)throw r.clear(),this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),new h("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 a;try{a=it(e,i,o)}catch(m){throw r.clear(),this.reportSessionCreateFailure(m,t,n),m}let c,u;try{if(u=await(await this.postCheckoutSessionCreate(ot(e,i),e,t,r.signal,n)).json(),!u.data||!("gateways"in u.data))throw new h("The billing API returned no session shell for a detached create. It must support `deferDataAttachment` (TeamFloPay/backend#1099).","api_error",{code:"InvalidCheckoutSessionResponse"});c=this.normalizeRawSession(this.mergeCachedDisplayData(u.data)),u.vault&&c.data.session&&(c.data.session.vault=this.toVaultBlock(u.vault))}catch(m){throw r.clear(),this.reportSessionCreateFailure(m,t,n),m}let l=c.data.session?.id??u.data.uuid??"",p=c.data.session?.clientSecret??u.data.nonce??"";if(!l||!p){r.clear();let m=new h("Checkout session shell was created without a session id or nonce.","api_error",{code:"InvalidCheckoutSessionResponse"});throw this.reportSessionCreateFailure(m,t,n),m}this.adoptDirectTelemetryCheckout(l),this.directTelemetry?.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",statusClass:n.statusClass,paymentMethodCategory:"card"}),this.directTelemetry?.performance({stage:"session_shell",durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:"session_create",statusClass:n.statusClass,attempt:n.attempt,paymentMethodCategory:"card"});let d=this.claimCheckoutSession(l,p,a,{params:e,startedAt:t,deadline:r,createAttempt:n.attempt});return d.catch(()=>{}),{shell:c,sessionId:l,nonce:p,claimed:d}}async claimCheckoutSession(e,t,r,n){let o=n?.startedAt??this.telemetryTimestamp(),i=this.telemetryTimestamp(),a=n?.deadline??D(12e3),c=JSON.stringify(r),u="unknown",l=0;this.directTelemetry?.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"});try{let p;for(l=0;l<3;l++){try{p=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/claim`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":t,[j]:M},body:c,signal:a.signal})}catch(C){let g=a.signal.aborted||C instanceof Error&&C.name==="AbortError";if(u=g?"timeout":"network_error",g||l>=2)throw C;try{this.telemetryHooks?.onRetry?.("session_claim",l+1),this.directTelemetry?.log({name:"operation.retry",stage:"session_claim",requestCategory:"session_claim",attempt:l+1})}catch{}await x(l,a.signal);continue}if(u=b(p.status),p.ok)break;throw await _(p,"Failed to attach checkout session data")}if(!p)throw new TypeError("Checkout-session claim exhausted its retry budget.");let d=await p.json();if(!d.data||!d.data.gateways)throw new h("The billing API returned no checkout session with gateways after claiming it.","api_error",{code:"InvalidCheckoutSessionResponse"});n?.params&&this.autoCacheDisplayData(d.data.uuid??e,n.params);let m=this.normalizeRawSession(this.mergeCachedDisplayData(d.data));return d.vault&&m.data.session&&(m.data.session.vault=this.toVaultBlock(d.vault)),this.directTelemetry?.log({name:"session.claim.completed",stage:"session_claim",requestCategory:"session_claim",statusClass:u}),this.directTelemetry?.performance({stage:"session_claim",durationMs:Math.max(0,this.telemetryTimestamp()-i),durationMode:"machine",requestCategory:"session_claim",statusClass:u,attempt:l}),this.directTelemetry?.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:u}),this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"session_create",statusClass:u,attempt:n?.createAttempt??l}),m}catch(p){throw this.reportSessionCreateFailure(p,o,{attempt:l,statusClass:u},"session_claim"),p}finally{a.clear()}}reportSessionCreateFailure(e,t,r,n="session_create"){if(!(e instanceof h&&e.code==="session_auto_completed"))try{this.telemetryHooks?.onSessionCreateFailure?.(e)}catch{}let o=w(e,"CHECKOUT_SESSION_CREATE_FAILED");if(this.directTelemetry?.performance({stage:n,durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:n==="session_claim"?"session_claim":"session_create",statusClass:o.statusClass,attempt:r.attempt}),e instanceof h&&e.type==="validation_error"||e instanceof h&&de(e.statusCode)){this.directTelemetry?.terminal({outcome:"validation_rejected",stage:n,requestCategory:n==="session_claim"?"session_claim":"session_create",...e.type==="validation_error"?{}:{statusClass:"4xx"}});return}e instanceof h&&e.code==="session_auto_completed"||this.directTelemetry?.error({...o,stage:n,requestCategory:n==="session_claim"?"session_claim":"session_create"})}async waitForCheckoutSessionCompletion(e,t){this.beginDirectTelemetryCheckout(e);let r=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:"saved"});let n=t?.timeoutMs??We,o=Date.now()+n,i=this.clampRetryAfterMs(t?.initialDelayMs??ue),a=0;try{for(;;){let c=o-Date.now();if(c<=0)throw q();if(i>0){try{a+=1,this.telemetryHooks?.onRetry?.("session_read",a),this.directTelemetry?.log({name:"operation.retry",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:"saved",attempt:a})}catch{}if(await pe(Math.min(i,c)),Date.now()>=o)throw q()}let u=await this.getUnifiedCheckoutSession(e,t?.nonce),l=u.data.session?.status;if(l==="authorized"||l==="complete"||l==="expired")return this.directTelemetry?.log({name:"operation.recovery.completed",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:"saved"}),this.directTelemetry?.performance({stage:"recovery",durationMs:Math.max(0,this.telemetryTimestamp()-r),durationMode:"machine",requestCategory:"session_read",paymentMethodCategory:"saved"}),u;if(Date.now()>=o)throw q();i=this.clampRetryAfterMs(Math.max(i*2,Ye))}}catch(c){throw c instanceof h&&c.code==="checkout_processing_timeout"&&this.reportDirectFailure(c,"RECOVERY_FAILED","recovery","session_read","saved"),c}}normalizeRawSession(e){let t=e.gateways??{},r=[],n={session:this.toCheckoutSession(e)},o=t.stripe;if(o?.publishableKey){r.push("stripe");let c=[e.stripeClientSecret,o.stripeClientSecret].find(u=>typeof u=="string"&&u.length>0);n.stripe={clientSecret:c??"",publishableKey:o.publishableKey??void 0,paypalPublishableKey:o.paypalPublishableKey??void 0,environment:o.environment,enabledPaymentMethods:Array.isArray(o.enabledPaymentMethods)?o.enabledPaymentMethods.filter(u=>typeof u=="string"):void 0}}let i=t.paypal;return i?.publishableKey&&(r.push("paypal"),n.paypal={publishableKey:i.publishableKey,environment:i.environment}),{providers:r,mode:"tokenize",data:n,raw:{data:e}}}toCheckoutSession(e){let t=e.products??[],r=typeof e.totalAmount=="number"&&Number.isFinite(e.totalAmount),n=t.reduce((u,l)=>u+(l.overrideAmount??l.totalAmount??0),0),o=r?e.totalAmount:n,i=Math.round(o*100),a=e.currency??t[0]?.currency??"USD",c=e.checkoutMode==="setup"?"setup":t.some(u=>u.type==="subscription")?"subscription":"payment";return{id:e.uuid,clientSecret:e.nonce,mode:c,status:this.toCheckoutSessionStatus(e.status),amount:i,currency:a,captureMethod:e.captureMethod,paymentId:e.paymentId,authorizationExpiresAt:e.authorizationExpiresAt,failureOutcome:ce(e.outcome)??ce(e.failureReason)??(e.status==="expired"&&e.captureMethod==="manual"?"authorization_expired":void 0),customer:{id:e.accountData.userId,email:e.accountData.email,firstName:e.accountData.firstName,lastName:e.accountData.lastName,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},metadata:{},checkoutMode:e.checkoutMode,providerPaymentMethodId:typeof e.providerPaymentMethodId=="string"?e.providerPaymentMethodId:null,products:t.map(u=>({...u,totalAmount:typeof u.totalAmount=="number"?u.totalAmount:void 0,overrideAmount:typeof u.overrideAmount=="number"?u.overrideAmount:null,currency:typeof u.currency=="string"?u.currency:void 0,metadata:u.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){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}}toCheckoutSessionStatus(e){return e==="completed"?"complete":e==="authorized"?"authorized":e==="expired"?"expired":"open"}async resolveProcessResponse(e,t,r){if(e.status!==202)return e;let n=await e.json().catch(()=>null),o=this.toCheckoutProcessingPending(n,e,t),i=await this.waitForCheckoutSessionCompletion(o.sessionId,{initialDelayMs:o.retryAfterMs,timeoutMs:r?.pollTimeoutMs,nonce:r?.nonce});if(i.data.session?.status==="complete")return new Response(null,{status:204,statusText:"No Content"});if(i.data.session?.status==="authorized"){let a=i.data.session;return new Response(JSON.stringify({status:"authorized",paymentId:a.paymentId,sessionId:a.id||t,authorizationExpiresAt:a.authorizationExpiresAt}),{status:200,headers:{"Content-Type":"application/json"}})}if(i.data.session?.status==="expired"){let a=i.data.session.failureOutcome==="authorization_expired"||i.data.session.captureMethod==="manual";throw new h(a?"Authorization has expired.":"Checkout session has expired.","api_error",{code:a?"authorization_expired":"checkout_session_expired"})}throw q()}toCheckoutProcessingPending(e,t,r){let n=t.headers.get("Retry-After"),o=n===null||n.trim()===""?void 0:Number(n),i=o!==void 0&&Number.isFinite(o)?o*1e3:void 0;return{type:"checkout_processing",sessionId:A(e,"sessionId")??r,retryAfterMs:this.clampRetryAfterMs(et(e,"retryAfterMs")??i??ue),statusUrl:A(e,"statusUrl"),sessionUrl:A(e,"sessionUrl")}}clampRetryAfterMs(e){return Math.max(0,Math.min(e,Je))}autoCacheDisplayData(e,t){if(!e)return;let r=t.products??H(t.items,t.subscriptions);if(r.length===0&&!t.currency)return;let n=t.products!==void 0,o=K(t.currency,n?void 0:t.items,n?void 0:t.subscriptions,r);N(e,{currency:o??void 0,products:r.map(i=>({code:i.code??i.providerItemId??i.providerPlanId,type:i.type,name:i.name??i.itemName??i.providerItemName??i.subscriptionName??i.providerPlanName??null,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency??o??void 0}))})}mergeCachedDisplayData(e){let t=Q(e.uuid),r=new Map,n=i=>i?`code:${i}`:void 0;for(let i of t?.products??[]){let a=n(i.code);a&&r.set(a,i)}let o=(e.products??[]).map(i=>{let a=n(i.code),c=a?r.get(a):void 0;return{...i,name:i.name??c?.name??null,totalAmount:i.totalAmount??c?.totalAmount,overrideAmount:i.overrideAmount??c?.overrideAmount,currency:i.currency??c?.currency}});return{...e,currency:e.currency??t?.currency,products:o}}};k.activeVaultCaptureRequests=new Map;var G=k;function At(s,e){let t=G;return new t(s,e)}import{buildTelemetryErrorEvent as at,buildTelemetryLogEvent as ct,buildTelemetryTerminalEvent as ve,FloPayError as ge,resolveBillingApiUrl as fe,SDK_VERSION as Ce}from"@flopay/shared";var W="flopay-vault",Te={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 R(s){let e={class:s.class,stage:s.stage};"code"in s&&(e.code=s.code),"provider"in s&&s.provider&&(e.provider=s.provider),"paymentMethodCategory"in s&&s.paymentMethodCategory&&(e.paymentMethodCategory=s.paymentMethodCategory),"outcome"in s&&(e.outcome=s.outcome),"durationMs"in s&&s.durationMs!==void 0&&(e.durationMs=s.durationMs),"durationMode"in s&&s.durationMode&&(e.durationMode=s.durationMode);try{globalThis.Sentry?.addBreadcrumb?.({category:"flopay.telemetry",level:s.class==="technical_error"?"error":"info",message:s.class==="lifecycle"?s.name:s.class==="technical_error"?s.code:s.class==="expected_outcome"?s.outcome:"sdk.performance",data:e})}catch{}}function F(s,e){return ct({eventId:"11111111-1111-4111-8111-111111111111",name:s,stage:e,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}function be(s){return s?{errorCode:"VAULT_SUBMIT_FAILED",stage:"vault_submit",failureCategory:"provider_runtime"}:{errorCode:"VAULT_LOAD_FAILED",stage:"vault_mount",failureCategory:"provider_runtime"}}function _e(s,e,t="checkout"){return t==="card_setup"?s.type==="decline"?"card_setup_declined":"card_setup_succeeded":s.type==="decline"?"payment_declined":s.outcome==="authorized"||e==="manual"?"payment_authorized":"payment_succeeded"}function ut(s,e,t,r="checkout"){let{type:n}=s;if(n==="complete"||n==="decline")return ve({eventId:"22222222-2222-4222-8222-222222222222",outcome:_e(s,t,r),sequence:0,provider:"pcivault",paymentMethodCategory:"card"});if(n==="error"){let a=be(e);return at({eventId:"33333333-3333-4333-8333-333333333333",...a,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}let[o,i]=Te[n];return F(o,i)}function lt(s){if(typeof s!="object"||s===null)return!1;let e=s;return e.source===W&&(e.type==="ready"||e.type==="submitting"||e.type==="blocked"||e.type==="complete"||e.type==="decline"||e.type==="error"||e.type==="action_required")}function dt(s){if(typeof s!="object"||s===null)return;let e=s,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 mt(s){if(typeof s!="object"||s===null)return!1;let e=s;return e.source===W&&e.type==="validation"&&Array.isArray(e.messages)}function pt(s){if(typeof s!="object"||s===null)return!1;let e=s;return e.source===W&&e.type==="resize"&&typeof e.height=="number"&&Number.isFinite(e.height)}var Y=class{constructor(e={},t){this.provider="pcivault";this.container=null;this.messageHandler=null;this.actionOverlay=null;this.threeDsReturnHandler=null;this.messageToken=null;this.expectedOrigin=null;this.theme=null;this.submitGateBlocked=!1;this.cardFieldOrder=null;this.cardAutoFocus=!0;this.mountStartedAt=0;this.vaultReadyReported=!1;this.submissionStarted=!1;this.submissionStartedAt=null;this.listeners=new Map;this.config=e,this.ownsTelemetryReporter=!t&&e.telemetry!==!1,this.telemetryReporter=t?.reporter??(this.ownsTelemetryReporter?new T({billingApiUrl:fe(),sdkVersion:Ce}):void 0)}async mount(e,t){this.ownsTelemetryReporter&&!this.telemetryReporter&&(this.telemetryReporter=new T({billingApiUrl:fe(),sdkVersion:Ce}));let r=this.telemetryReporter;if(this.config.operation==="card_setup"&&r&&this.setupTelemetryReporter!==r){this.setupTelemetryReporter=r;try{r.beginCheckout({checkoutMode:"setup"})}catch{}}if(this.mountStartedAt=this.telemetryReporter?.now?.()??v(),this.vaultReadyReported=!1,this.submissionStarted=!1,this.submissionStartedAt=null,typeof window>"u"||typeof document>"u")throw this.reportVaultLoadFailure(),new ge("The vault card form is only available in the browser.","api_error",{code:"card_capture_no_window"});if(!t?.html||!t.html.trim())throw this.reportVaultLoadFailure(),new ge("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.messageToken=t.messageToken??null,this.expectedOrigin=t.expectedOrigin??this.config.expectedOrigin??null,this.theme=t.theme??null;try{this.attachMessageListener(),this.injectWidget(e,t.html)}catch(n){throw this.reportVaultLoadFailure(),n}this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),R(F("vault.widget.mounted","vault_mount")),this.telemetryReporter?.log({name:"vault.widget.mounted",stage:"vault_mount",provider:"pcivault",paymentMethodCategory:"card"}),this.emit("ready",{sessionId:this.config.sessionId})}reportVaultLoadFailure(){this.telemetryReporter?.error({errorCode:"VAULT_LOAD_FAILED",failureCategory:"provider_runtime",stage:"vault_mount",provider:"pcivault",paymentMethodCategory:"card"})}on(e,t){let r=this.listeners.get(e);return r||(r=new Set,this.listeners.set(e,r)),r.add(t),()=>{this.listeners.get(e)?.delete(t)}}unmount(){this.hideActionRequiredOverlay(),this.messageHandler&&(window.removeEventListener("message",this.messageHandler),this.messageHandler=null),this.container&&(this.container.replaceChildren(),this.container=null),this.messageToken=null,this.expectedOrigin=null,this.ownsTelemetryReporter&&(this.telemetryReporter?.destroy(),this.telemetryReporter=void 0)}injectWidget(e,t){e.innerHTML=t;let r=Array.from(e.querySelectorAll("script"));for(let n of r){let o=document.createElement("script");for(let i of Array.from(n.attributes))o.setAttribute(i.name,i.value);o.text=n.text,n.replaceWith(o)}}attachMessageListener(){if(this.messageHandler)return;let e=t=>{if(this.expectedOrigin&&t.origin!==this.expectedOrigin)return;let r=t.data;if(pt(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;this.applyHeight(r.height);return}if(mt(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;let c=r.messages.filter(u=>typeof u=="string"&&u.trim()).join(" ");this.emit("validation",{sessionId:this.config.sessionId,message:c||void 0});return}if(!lt(r)||this.messageToken&&r.messageToken!==this.messageToken)return;let n=this.config.sessionId,o=typeof r.sessionId=="string"?r.sessionId:void 0;if(n&&o&&o!==n||(r.type==="complete"||r.type==="decline")&&n&&o!==n)return;let i=dt(r.paymentMethod),a={...r.sessionId??this.config.sessionId?{sessionId:r.sessionId??this.config.sessionId}:{},...r.outcome?{outcome:r.outcome}:{},...r.paymentId?{paymentId:r.paymentId}:{},...r.authorizationExpiresAt?{authorizationExpiresAt:r.authorizationExpiresAt}:{},...r.failureOutcome?{failureOutcome:r.failureOutcome}:{},...r.intentId?{intentId:r.intentId}:{},...r.declineReason?{declineReason:r.declineReason}:{},...r.message?{message:r.message}:{},...i?{paymentMethod:i}:{}};r.type==="submitting"&&(this.submissionStarted=!0,this.submissionStartedAt=this.telemetryReporter?.now?.()??v()),R(ut(r,this.submissionStarted,this.config.captureMethod,this.config.operation)),this.reportOutcome(r),r.type==="ready"&&(this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder()),r.type==="action_required"&&r.nextActionRedirectUrl&&this.showActionRequiredOverlay(r.nextActionRedirectUrl),(r.type==="complete"||r.type==="decline"||r.type==="error"||r.type==="submitting")&&this.hideActionRequiredOverlay(),r.type!=="action_required"&&this.emit(r.type,a)};this.messageHandler=e,window.addEventListener("message",e)}reportOutcome(e){let t=this.telemetryReporter;if(!t)return;let{type:r}=e;if(r==="ready"&&!this.vaultReadyReported&&(this.vaultReadyReported=!0,t.performance({stage:"vault_ready",durationMs:Math.max(0,t.now()-this.mountStartedAt),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card"})),r==="complete"||r==="decline"){t.log({name:"vault.terminal",stage:"completion",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:_e(e,this.config.captureMethod,this.config.operation),provider:"pcivault",paymentMethodCategory:"card"});return}if(r==="error"){let i=be(this.submissionStarted);t.log({name:"vault.terminal",stage:i.stage,provider:"pcivault",paymentMethodCategory:"card"}),t.error({...i,provider:"pcivault",paymentMethodCategory:"card"});return}if(r==="action_required"){t.log({name:"vault.action.required",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"}),t.log({name:"vault.three_ds.handoff",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"});let i=this.submissionStartedAt;this.submissionStartedAt=null,i!==null&&t.performance({stage:"three_ds_handoff",durationMs:Math.max(0,t.now()-i),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:"action_required",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"});return}let[n,o]=Te[r];t.log({name:n,stage:o,provider:"pcivault",paymentMethodCategory:"card"})}applyTheme(e){this.theme=e,this.postTheme()}postTheme(){if(!this.theme||!this.container)return;let t=this.container.querySelector("iframe")?.contentWindow;if(t)try{t.postMessage({source:"flopay-vault-host",type:"theme",theme:this.theme},"*")}catch{}}setSubmitGate(e){this.submitGateBlocked=e,this.postSubmitGate()}postSubmitGate(){if(!this.container)return;let t=this.container.querySelector("iframe")?.contentWindow;if(t)try{t.postMessage({source:"flopay-vault-host",type:"gate",blocked:this.submitGateBlocked},"*")}catch{}}setCardFieldOrder(e,t){this.cardFieldOrder=e,this.cardAutoFocus=t,this.postCardFieldOrder()}postCardFieldOrder(){if(!this.container)return;let t=this.container.querySelector("iframe")?.contentWindow;if(t)try{t.postMessage({source:"flopay-vault-host",type:"fieldOrder",order:this.cardFieldOrder,autoFocus:this.cardAutoFocus},"*")}catch{}}emit(e,t){for(let r of this.listeners.get(e)??[])r(t)}showActionRequiredOverlay(e){if(typeof document>"u")return;if(this.actionOverlay){let i=this.actionOverlay.querySelector("iframe");i instanceof HTMLIFrameElement&&(i.src=e);return}let t=document.createElement("div");t.setAttribute("data-flopay-action-required","1"),t.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let r=document.createElement("iframe");r.setAttribute("title","Card authentication"),r.setAttribute("allow","payment"),r.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";"),r.src=e,t.appendChild(r);let n=document.createElement("button");n.type="button",n.setAttribute("aria-label","Close card authentication"),n.textContent="\xD7",n.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(";"),n.addEventListener("click",()=>this.abandonActionRequiredOverlay()),t.appendChild(n),t.addEventListener("click",i=>{i.target===t&&this.abandonActionRequiredOverlay()});let o=i=>{if(i.source!==r.contentWindow)return;let a=i.data;if(!a||typeof a!="object")return;let c=a;c.source==="flopay-vault-3ds-return"&&(R(F("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(),this.postActionCompleted(c.status))};window.addEventListener("message",o),this.threeDsReturnHandler=o,document.body.appendChild(t),this.actionOverlay=t,R(F("vault.three_ds.handoff","three_ds_handoff"))}postActionCompleted(e){if(!this.container)return;let r=this.container.querySelector("iframe")?.contentWindow;if(r)try{r.postMessage({source:"flopay-vault-host",type:"action_completed",status:typeof e=="string"?e:"unknown"},"*")}catch{}}abandonActionRequiredOverlay(){if(!this.actionOverlay)return;let e=ve({eventId:"77777777-7777-4777-8777-777777777777",outcome:"customer_abandoned",stage:"three_ds_handoff",sequence:0,provider:"pcivault",paymentMethodCategory:"card"});R(e),this.telemetryReporter?.terminal({outcome:"customer_abandoned",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"}),this.hideActionRequiredOverlay(),this.postActionCompleted("abandoned")}hideActionRequiredOverlay(){this.threeDsReturnHandler&&(window.removeEventListener("message",this.threeDsReturnHandler),this.threeDsReturnHandler=null),this.actionOverlay&&(this.actionOverlay.parentNode?.removeChild(this.actionOverlay),this.actionOverlay=null)}applyHeight(e){let t=this.container?.querySelector("iframe");if(!t)return;let r=Math.max(0,Math.min(Math.ceil(e),2e3));t.style.height=`${r}px`}};function It(s,e){let t=Y;return new t(s,{reporter:e})}export{Z as a,N as b,Q as c,X as d,v as e,T as f,D as g,x as h,rt as i,G as j,At as k,Y as l,It as m};
|