@flopay/react 1.10.1 → 1.10.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import{a as Pl}from"./chunk-R73QOXY5.mjs";import{c as At,d as wr,e as ta,f as Ti,g as na,h as ul,i as pl,j as Qc,l as ed}from"./chunk-I4TPZWBS.mjs";import{a as gl}from"./chunk-U3PMJDD4.mjs";import{a as hl}from"./chunk-OYOJA6FI.mjs";import{a as Da,b as ml,c as Ur,d as ra,e as Na,f as yl,g as Ai,h as qr,i as oa,j as fl,k as Oa}from"./chunk-M7R46EDF.mjs";import{dropThirdPartyOnlyError as $y}from"@flopay/shared";import{PaymentAPI as Es}from"@flopay/js";import{FloPayError as wa,resolveBillingApiUrl as cp,resolveButtonsLayoutTheme as dp,resolveTheme as up}from"@flopay/shared";import{useCallback as Or,useEffect as zo,useMemo as Sa,useRef as Uo,useState as qo}from"react";import{Fragment as wo,jsx as Jn,jsxs as vl}from"react/jsx-runtime";function td(){return vl(wo,{children:[vl("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[Jn("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),Jn("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",Jn("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"#9ca3af",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem"},"aria-hidden":"true",children:Jn("path",{d:"M9 18l6-6-6-6"})})]})}function nd(){return Jn(wo,{children:"Go back"})}function rd(){return Jn(wo,{children:"Secure card checkout"})}function bo(e){return e!==void 0&&(e===""||e===null||e===!1)}function Co({content:e}){return Jn(wo,{children:e===void 0?Jn(td,{}):e})}function So({content:e}){return Jn(wo,{children:e===void 0?Jn(nd,{}):e})}function aa({content:e}){return Jn(wo,{children:e===void 0?Jn(rd,{}):e})}import{CHECKOUT_PROCESSING_TIMEOUT_MESSAGE as od,classifyTelemetryFailure as ad,FloPayError as _n,isCardHolderNamePlaceholder as bl,isMoneySettledOutcome as id,isSetupIntentClientSecret as sd,isValidEmail as ld}from"@flopay/shared";var cd="Checkout is temporarily unavailable. Please try again later.";function Mi(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof _n&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function dd(e){return e.type==="validation_error"||e.code==="checkout_session_not_found"||e.code==="checkout_session_expired"||e.code==="checkout_session_completed"||e.code==="session_auto_completed"}function Cl(){return new _n(cd,"api_error",{code:"CheckoutInitializationFailed"})}function xi(e){return!!e?.gateways?.worldpayCorporateGateway}function jr(e){return e?.status==="open"&&xi(e)}function Sl(e,t,n){let r=e?.data.session,o=r?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(n&&(r?.vault?.html||r?.gateways?.pcivault||o?.includes("card")||jr(r))||t&&e?.data.paypal?.publishableKey)}function wl(e,t){if(t&&(!(e instanceof _n)||e.type==="authentication_error"))return Mi(e);if(!(e instanceof _n&&dd(e))){if(!t&&!(e instanceof _n)&&(e instanceof TypeError||e instanceof SyntaxError))return{...ad(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof _n)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof _n))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function ko(e,t,n,r={}){let o;return(i={})=>{if(o)return o;let s={...r,...i,email:i.email?.trim()||r.email?.trim()},l=bl(s.firstName,s.lastName);if(!ld(s.email))return Promise.reject(new _n("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let y={};for(let[u,b]of Object.entries(s)){if(l&&u.endsWith("Name")||typeof b!="string")continue;let P=b.trim();P&&(y[u]=P)}return o=e.claimCheckoutSession(t,n,{accountData:y}),o.catch(()=>{}),o}}function kl(e,t){if(!t)return e;if(!e)return t;let n;return"checkoutMetadata"in t?n=t:"checkoutMetadata"in e&&(n=e),{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,...n?{checkoutMetadata:n.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}}function Bi(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,..."checkoutMetadata"in t?{checkoutMetadata:t.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function Il(e,t){let n=e.products??[...(e.subscriptions??[]).map(i=>({type:"subscription",code:i.code??i.providerPlanId,name:i.subscriptionName??i.providerPlanName??i.code??i.providerPlanId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata})),...(e.items??[]).map(i=>({type:"item",code:i.code??i.providerItemId,name:i.itemName??i.providerItemName??i.code??i.providerItemId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata}))],r=n.reduce((i,s)=>i+(s.overrideAmount??s.totalAmount??0),0),o=e.currency??n.find(i=>i.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(i=>i.type==="subscription")?"subscription":"payment",amount:Math.round(r*100),currency:o,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((i,s)=>({uuid:`synthetic-${i.type??"item"}-${s}`,checkoutSessionId:"",type:i.type??"item",code:i.code,name:i.name??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount??null,currency:i.currency??o,metadata:i.metadata??null}))}}function no(e){if(bl(e))return{};let[t,...n]=e?.trim().split(/\s+/)??[];return t?{firstName:t,lastName:n.join(" ")||void 0}:{}}function Fi(e,t){return t?{...e,...t}:e}function ln(e,t,n){let r=typeof t=="string"?t:t.message,o=typeof t=="string"?n?.code:n?.code??t.code,i=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode,s=typeof t=="string"?void 0:t.sessionId;return{method:e,message:r,...o?{code:o}:{},...i?{declineCode:i}:{},...s?{sessionId:s}:{}}}function $r(e,t){return t&&e.sessionId===void 0&&Object.defineProperty(e,"sessionId",{value:t,enumerable:!0}),e}var ud=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function Kr(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of ud)if(n.test(t))return r;return e}function Fr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function Dr(e){return e?.status==="authorized"||e?.status==="complete"}function Hr(e,t){if(e.data.session)return e.data.session;let n=e.raw,r=n?.latestTransactionAttempt?.result,o=n?.status==="authorized"||r==="AUTHORIZED";return o||n?.status==="completed"||r==="SUCCESS"?{...t,status:o?"authorized":"complete"}:n?.status==="expired"?{...t,status:"expired"}:void 0}function Rl(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function La(e){let t=Rl(e);return new _n(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function za(e){return e instanceof _n||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function Io(e){return Rl(e)?new _n("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new _n("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new _n(od,"api_error",{code:"checkout_processing_timeout"})}function ia(e,t){return e==="processing"||id(e,t)}function _l(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function El(e,t){let n=e;if(sd(t)){if(!n?.retrieveSetupIntent)return null;let{setupIntent:i,error:s}=await n.retrieveSetupIntent(t);if(s)throw new _n(s.message??"Failed to retrieve setup intent.","api_error",{...s.code?{code:s.code}:{}});return i??null}if(!n?.retrievePaymentIntent)return null;let{paymentIntent:r,error:o}=await n.retrievePaymentIntent(t);if(o)throw new _n(o.message??"Failed to retrieve payment intent.","api_error",{...o.code?{code:o.code}:{}});return r??null}function Tl(e,t="automatic"){return{...typeof e=="number"&&Number.isFinite(e)&&e>0?{mode:"payment",amount:e,captureMethod:t==="manual"?"manual":"automatic_async"}:{mode:"setup"},paymentMethodTypes:["card"],setupFutureUsage:"off_session"}}function Di(e){let t=e&&typeof e=="object"?e:null;return t?.name==="IntegrationError"||t?.code==="elements_intent_mismatch"||t?.type==="invalid_request_error"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function sa(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}import{FloPay as Wu,PaymentAPI as li,SESSION_CREATE_TELEMETRY as Gu}from"@flopay/js";import{buildCheckoutDisplayData as Yu,classifyTelemetryFailure as Mc,FloPayError as Cn,isDetachedSessionEligible as Ju,resolveBillingApiUrl as Xu,resolveButtonsLayoutTheme as Zu,resolveIdempotencyKey as kc,resolveTheme as xc,SDK_VERSION as Bc,telemetryStatusClass as Qu}from"@flopay/shared";import vs,{useCallback as bn,useEffect as mr,useMemo as Zn,useRef as Mt,useState as $t}from"react";import{createContext as Al}from"react";var Xn=Al({flopay:null,paypalFlopay:null,billingApiUrl:""}),dr=Al({session:null,loading:!1,error:null});import{PaymentAPI as Li}from"@flopay/js";import{classifyTelemetryFailure as Rd,FloPayError as zi,generateIdempotencyKey as _d,isValidEmail as ua,normalizeGatewayEnvironment as Ed,PAYPAL_VAULTED_PAYMENT_METHOD_TYPE as Ui,SDK_VERSION as Td}from"@flopay/shared";import{loadScript as Ad}from"@paypal/paypal-js";import{useCallback as kr,useContext as Md,useEffect as Ot,useMemo as pa,useRef as nt,useState as Gr}from"react";import{isValidEmail as pd}from"@flopay/shared";import{useCallback as Ml,useEffect as md,useRef as xl,useState as Fl}from"react";import{jsx as Bl,jsxs as la}from"react/jsx-runtime";function Dn(e,t=!1){let{firstName:n,lastName:r,...o}=e,i=n?.trim(),s=r?.trim();return{...o,...i||t?{firstName:i??""}:{},...s||t?{lastName:s??""}:{}}}function Ro(){let[e,t]=Fl(null),n=xl(null),r=xl(0),o=Ml((s,l)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:s,identity:l}),new Promise(y=>{n.current=y})),[]),i=Ml(s=>{let l=n.current;n.current=null,t(null),l?.(s)},[]);return md(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:i}}function _o({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:i="flopay-buyer-identity-pane"}){let[s,l]=Fl(e.email?.trim()??""),y=pd(s.trim());return la("div",{"data-testid":i,style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"0.875rem",border:"1px solid #d1d5db",borderRadius:8,background:"#fff",color:"#262833"},children:[la("div",{style:{fontWeight:700},children:["Continue with ",t]}),la("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",Bl("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:s,onChange:u=>l(u.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),la("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&Bl("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),la("button",{type:"button",disabled:!y||o,onClick:()=>{n(Dn({...e,email:s.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}import{resolveBillingApiUrl as yd}from"@flopay/shared";import{useContext as Ua}from"react";function Vr(){return Ua(Xn).flopay}function Ni(){return Ua(Xn).paypalFlopay??null}function fd(){return Ua(dr)}function Dl(){return Ua(Xn).billingApiUrl||yd()}import{FLO_INSTRUMENT_SCHEMA_VERSION as gd}from"@flopay/shared";import{useCallback as hd,useRef as qa}from"react";var Pd={"checkout.mount":"checkout_mount","sdk.initialize.ready":"sdk_loaded","provider.ready":"sdk_loaded","checkout.rendered":"form_rendered","vault.widget.ready":"form_rendered","vault.submission.started":"tokenize","payment.tokenization.started":"tokenize","payment.processing.started":"process_attempt","payment.intent.started":"process_attempt","vault.action.required":"3ds_challenge","payment.three_ds.handoff":"3ds_challenge"};function vd(e){return e==="stripe"||e==="paypal"?e:void 0}function bd(e){let t=vd(e.provider),n={schemaVersion:gd,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=Pd[e.name];return r?{...n,name:r}:null}return e.class==="card_surface"?{...n,name:"card_expanded"}:e.errorCode==="CHECKOUT_SESSION_CREATE_FAILED"?{...n,name:"checkout_error",phase:"session_create"}:e.errorCode==="SDK_INITIALIZATION_FAILED"||e.errorCode==="PROVIDER_LOAD_FAILED"?{...n,name:"checkout_error",phase:"sdk_load"}:e.errorCode==="PAYMENT_PROCESSING_FAILED"?{...n,name:"checkout_error",phase:e.requestCategory==="intent_create"?"wallets":"process"}:null}var Oi=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function Eo(e,t){let n=qa(e);n.current=e;let r=qa(new Set),o=qa(t),i=qa(t);return ta(()=>{i.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),hd(s=>{if(i.current!==t)return;let l=bd(s);if(l){if(Oi.has(l.name)){if(r.current.has(l.name))return;r.current.add(l.name)}At(()=>n.current?.(l))}},[t])}import{createContext as Cd}from"react";var ca=Cd(null);function ja(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var Sd=Symbol.for("@flopay/js.telemetry.bridge.v1"),wd=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function kd(){return{error:()=>{},log:()=>{},performance:()=>{},terminal:()=>{},now:()=>globalThis.performance?.now()??0,elapsed:e=>Math.max(0,(globalThis.performance?.now()??e)-e),setCheckoutContext:()=>{},beginCheckout:()=>globalThis.performance?.now()??0,disable:()=>{},subscribe:()=>()=>{},flush:async()=>{},destroy:()=>{}}}function Id(e){let t=kd(),n=(o,i)=>o?o.bind(e):i,r=n(e.now,t.now);return{error:n(e.error,t.error),log:n(e.log,t.log),performance:n(e.performance,t.performance),terminal:n(e.terminal,t.terminal),now:r,elapsed:e.elapsed?e.elapsed.bind(e):o=>Math.max(0,r()-o),setCheckoutContext:n(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:n(e.beginCheckout,t.beginCheckout),disable:n(e.disable,t.disable),subscribe:n(e.subscribe,t.subscribe),flush:n(e.flush,t.flush),destroy:n(e.destroy,t.destroy)}}function $a(e){let t=globalThis[wd];return Id(t?.(e)??{})}function cn(e){if(e)return e[Sd]}import{useCallback as Wr,useEffect as Nl,useRef as ro}from"react";function da(e,t){let n=ro(0),r=ro(null),o=ro(null),i=ro(e),s=ro(t?.onHandoffObserved),l=ro(t?.defersMissingTerminal),y=ro(t?.onMissingTerminalDeferred);Nl(()=>{i.current=e,s.current=t?.onHandoffObserved,l.current=t?.defersMissingTerminal,y.current=t?.onMissingTerminalDeferred},[e,t?.onHandoffObserved,t?.defersMissingTerminal,t?.onMissingTerminalDeferred]);let u=Wr((g=o.current)=>{g?.timer&&(clearTimeout(g.timer),g.timer=null)},[]),b=Wr(g=>{u();let v=n.current+1;return n.current=v,r.current=null,o.current={generation:v,method:g,timer:null,yieldedControl:!1},v},[u]),P=Wr(g=>{let v=o.current;return g!==void 0&&v?.generation!==g?!1:(u(v),o.current=null,(g===void 0||r.current===g)&&(r.current=null),!0)},[u]),D=Wr(g=>{let v=o.current,X=g??v?.generation??n.current;(g===void 0||v?.generation===g)&&(u(v),o.current=null),r.current=X},[u]),N=Wr(g=>r.current===(g??n.current),[]),R=Wr(g=>o.current?.generation===g&&r.current!==g,[]),O=Wr(()=>{let g=o.current;g&&(u(g),!g.yieldedControl&&(g.yieldedControl=!0,s.current?.(g.method)))},[u]),$=Wr(()=>{let g=o.current;!g?.yieldedControl||document.visibilityState!=="visible"||(u(g),g.timer=setTimeout(()=>{if(g.timer=null,o.current?.generation===g.generation){if(l.current?.(g.method)){y.current?.(g.method,g.generation);return}o.current=null,r.current=g.generation,i.current(g.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"})}},600))},[u]);return Nl(()=>{let g=()=>{document.visibilityState==="visible"?$():O()};return document.addEventListener("visibilitychange",g),window.addEventListener("blur",O),window.addEventListener("focus",$),()=>{document.removeEventListener("visibilitychange",g),window.removeEventListener("blur",O),window.removeEventListener("focus",$),u()}},[u,O,$]),{startAttempt:b,finishAttempt:P,invalidateAttempt:D,isAttemptInvalidated:N,isAttemptCurrent:R,generationRef:n}}import{jsx as oo,jsxs as qi}from"react/jsx-runtime";var Ka=45,xd=1e3,Bd=11e3,Fd={width:"100%",minHeight:Ka,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"},Dd={script_rejected:{errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",operationOutcome:"rejected"},namespace_unusable:{errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",operationOutcome:"returned_error"},pre_ready_callback:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"returned_error"},render_rejected:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"rejected"},watchdog_expired:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"watchdog_expired"}};function Nd(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:Dd[e.kind]??null}}function Ol(e,t){return e==="watchdog_expired"?"paypal_render_timeout":yl(t)?"paypal_init_timeout":"paypal_init_failure"}function Od(e){let t=e,n=t?.payer??t?.payment_source?.paypal;return{email:n?.email_address?.trim()||void 0,firstName:n?.name?.given_name?.trim()||void 0,lastName:n?.name?.surname?.trim()||void 0}}function Ld(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function Ll({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:i,clientId:s,environment:l,currency:y,isSubscription:u,providerObjectType:b,approvalPresentation:P,onTokenizedBody:D,onComplete:N,onErrorChange:R,onDecline:O,onTechnicalFailure:$,isProcessing:g=!1,onLoadStateChange:v,onInitializationStateChange:X,allowAutomaticRetry:H=!0,onButtonClick:pe,runBeforeButtonClick:V,session:De,existingOrderId:Ye,telemetry:be,telemetryContext:et,onInstrument:Ct,debug:fe=!1}){let qe=Vr(),St=Eo(Ct,e),Me=pa(()=>{if(qe)return null;let S=$a({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Td,enabled:be!==!1});return S.setCheckoutContext(et??{}),S.beginCheckout(et??{}),S},[n,qe,be,et?.checkoutMode,et?.layout]),je=pa(()=>cn(qe),[qe]);Ot(()=>()=>{Me&&Me.flush().catch(()=>{}).finally(()=>Me.destroy())},[Me]);let he=pa(()=>({error:S=>{je?je.error(S):Me?.error(S),St({class:"technical_error",errorCode:S.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":S.errorCode,requestCategory:S.requestCategory,provider:S.provider})},log:S=>{je?je.log(S):Me?.log(S),St({class:"lifecycle",name:S.name,provider:S.provider})},performance:S=>{je?je.performance(S):Me?.performance(S)},terminal:S=>{je?je.terminal(S):Me?.terminal(S)},startTiming:()=>je?.now()??Me?.now()??0,elapsed:S=>je?.elapsed(S)??Math.max(0,(Me?.now()??S)-S)}),[St,je,Me]),me=nt(null),$e=nt(0),Je=nt(null),dt=nt(null),L=nt(null),st=Md(ca),Pe=nt(null);Pe.current||(Pe.current=ja());let z=st??Pe.current,Ne=nt(null),Ce=nt(!1),[Xe,G]=Gr(!1),[tt,ot]=Gr(!1),[ke,Ke]=Gr(0),He=nt(0),[at,Ie]=Gr(!1),Lt=nt(!1),Kt=nt(!1),[ut,Rt]=Gr(!1),[T,ae]=Gr(!1),{request:Oe,collect:U,finish:Re}=Ro(),pt=nt({sessionId:e,required:!ua(r?.trim()||De?.customer?.email?.trim())});pt.current.sessionId!==e&&(pt.current={sessionId:e,required:!ua(r?.trim()||De?.customer?.email?.trim())});let Le=pt.current.required,wt=pa(()=>n.replace(/\/+$/,""),[n]),m=De?.gateways?.paypal?.providerObjectType??b,f=m??(u?"subscription":"order"),[F]=Gr(oa),A=De?.gateways?.paypal?.approvalPresentation??P,ne=Oa(F,A==="app_switch"?"app_switch":void 0,f),xt=m==="order"||m==="setup_token",_e=pa(()=>JSON.stringify([wt,s,y,l??"",f,xt,ne,e,Ye??""]),[wt,s,y,l,Ye,f,xt,ne,e]),xe=nt(_e),oe=xe.current!==_e,mt=nt(fe),Ht=nt(null),[Ae,En]=Gr([]),se=kr(S=>{mt.current&&En(Ve=>[...Ve,`${new Date().toISOString().slice(11,23)} ${S}`])},[]);Ot(()=>{mt.current=fe,fe&&se("debug:enabled"),Ht.current?.setEnabled(fe)},[se,fe]);let Nn=nt(D),On=nt(N),_t=nt(R),Sn=nt(O),Tn=nt($),jn=nt(pe),dn=nt(v),Bt=nt(X),Ze=nt(i),Fe=nt(V),wn=nt(De),Et=nt(r),kn=nt(o),un=nt(t),Vt=nt(null),rn=nt(new Map),$n=nt(new Map),Kn=nt(!1);Ot(()=>(Kn.current=!0,()=>{Kn.current=!1}),[]),Ot(()=>{Nn.current=D},[D]),Ot(()=>{Ze.current=i},[i]),Ot(()=>{On.current=N},[N]),Ot(()=>{_t.current=R},[R]),Ot(()=>{Sn.current=O},[O]),Ot(()=>{Tn.current=$},[$]),Ot(()=>{jn.current=pe},[pe]),Ot(()=>{dn.current=v},[v]),Ot(()=>{Bt.current=X},[X]),Ot(()=>{Fe.current=V},[V]),Ot(()=>{wn.current=De},[De]),Ot(()=>{Et.current=r},[r]),Ot(()=>{kn.current=o},[o]),Ot(()=>{un.current=t},[t]),Ot(()=>{He.current=ke},[ke]),Ot(()=>{at&&Ne.current?.focus()},[at,ke]);let kt=kr(()=>{window.setTimeout(()=>{Ne.current?.focus()},0)},[]),yt=kr(()=>{G(!1),Ke(S=>S+1)},[]),gn=kr(()=>{Ie(!1),(me.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??me.current)?.focus?.()},[]);Ot(()=>{!Xe||!Ce.current||(Ce.current=!1,gn())},[gn,Xe,ke]);let en=kr((S,Ve)=>{let W=Ve?.popupBlocked??qr(S);W&&z.markBlocked();let Pn=Da("PayPal",W,F.inAppBrowser),pn=Tn.current;if(pn){let Wt=W&&F.inAppBrowser?new zi(Pn,"api_error",{code:Ve?.code??"paypal_popup_blocked"}):S;pn("paypal",Wt,Ve);return}_t.current?.(Pn)},[z,F.inAppBrowser]),Ft=kr(S=>{let Ve=Je.current,W=dt.current;Ve===null||!W||(he.log({...W,popupCapability:z.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:S}),he.performance({...W,popupCapability:z.current(),stage:"overlay_return",durationMs:he.elapsed(Ve),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:S}),Je.current=null)},[z,he]),on=kr((S,Ve,W)=>{let Pn=dt.current;Ft("overlay_timeout"),Pn&&he.error({...Pn,popupCapability:z.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),en(Ve,{...W,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:ne,terminalReason:"overlay_timeout"}),Ie(!0),yt(),kt()},[Ft,kt,en,z,ne,yt,he]),Xt=kr(()=>{z.markAvailable();let S=dt.current;S&&(L.current=S.attempt,he.log({...S,popupCapability:z.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[z,he]),{finishAttempt:Dt,generationRef:Y,invalidateAttempt:an,isAttemptCurrent:Ln,isAttemptInvalidated:Er,startAttempt:Qn}=da(on,{onHandoffObserved:Xt}),zt=kr(()=>(Ie(!1),Qn("paypal")),[Qn]),er=kr(S=>{an(S?.generation),S?.showRetry&&Ie(!0),S?.remount&&yt(),S?.focus!==!1&&kt()},[kt,an,yt]),hn=S=>{let Ve=Vt.current;return Ve&&$n.current.set(S,Ve),S};Ot(()=>{xe.current!==_e&&(xe.current=_e,Lt.current=!1,Kt.current=!1,G(!1),ot(!1),Rt(!1),Bt.current?.("loading"))},[_e]),Ot(()=>{At(()=>dn.current?.(Xe&&!ut))},[Xe,ut]);let le=Ed(l);Ot(()=>{let S={attempt:Y.current+1,inAppBrowser:F.inAppBrowser,appFamily:F.appFamily,popupCapability:z.current(),presentationMode:ne},Ve=()=>({...dt.current??S,popupCapability:z.current()}),W={error:c=>he.error({...c,...Ve()}),log:c=>he.log({...c,...Ve()}),performance:c=>he.performance({...c,...Ve()}),terminal:c=>he.terminal({...c,...Ve()}),startTiming:he.startTiming,elapsed:he.elapsed},Pn=s?`${s.slice(0,6)}\u2026(len ${s.length})`:"(empty)",pn=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(se(`mount clientId=${Pn} env=${l??"(unset)"}\u2192${le??"live"} ccy=${y} sub=${u}`),se(`ua=${pn.slice(0,80)}${pn.length>80?"\u2026":""}`),!s){se("FAIL: clientId empty \u2014 gateway misconfigured"),Rt(!0),W.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!me.current){se("FAIL: containerRef not attached");return}$e.current=W.startTiming(),W.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Wt=!1,Hn=!1,Qe=()=>Wt||Hn,Lr,Gt=!1,mn=()=>{Lr=_d(),Lr||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Gt=!0},Tr=null,Ar=!1,An=null,Zt=!1,yr=()=>{!An||Zt||(Zt=!0,An.close().catch(()=>{}))},Mn=!1,Mr=!1,xn=me.current,fr=null,gr=null,tr=[],Vn=null,Wn=!1,Tt=!1,nr=null,In=c=>{if(!c||typeof c.getBoundingClientRect!="function")return"(no rect)";let p=c.getBoundingClientRect();return`${Math.round(p.width)}\xD7${Math.round(p.height)}`},Gn=c=>{if(!c)return"(empty)";try{let p=new URL(c,typeof window>"u"?"https://localhost":window.location.href),_=p.pathname.toLowerCase();return _.includes("checkcaptcha")||_.includes("captcha")?`CAPTCHA(${p.host}${_})`:_.includes("risk")||_.includes("challenge")?`RISK(${p.host}${_})`:_.includes("smart/buttons")?`smart-buttons(${p.host})`:`${p.host}${_}`.slice(0,100)}catch{return c.slice(0,80)}},hr=c=>{let p=c.getAttribute("src"),_=c.getAttribute("srcdoc"),M=c.getAttribute("name"),te=c.getAttribute("sandbox"),K=[];return p&&K.push(`src=${Gn(p)}`),_&&K.push(`srcdoc[${_.length}ch]`),!p&&!_&&K.push("src=(empty) srcdoc=(empty)"),M&&K.push(`name=${M.slice(0,40)}`),te!==null&&K.push(`sandbox="${te.slice(0,40)}"`),K.join(" ")},it=c=>{if(!(c instanceof HTMLIFrameElement))return"";try{let p=c.contentDocument;if(!p)return"cd=null";let _=p.body?.children.length??0,M=p.body?.innerHTML.length??0,te=p.head?.innerHTML.length??0;return`cd=same-origin readyState=${p.readyState} body[${_}children,${M}ch] head[${te}ch]`}catch(p){return`cd=cross-origin(${p.message.slice(0,30)})`}},tn=[],Qt=c=>{if(Qe())return;let p=c.message??String(c.error??"(no message)");p&&(p.toLowerCase().includes("paypal")||p.toLowerCase().includes("zoid")||p.toLowerCase().includes("postrobot")||p.toLowerCase().includes("storage"))&&(se(`window:error ${p.slice(0,140)}`),tn.push(p))},xr=c=>{if(Qe())return;let p=c.reason instanceof Error?c.reason.message:String(c.reason??"(no reason)");p&&(p.toLowerCase().includes("paypal")||p.toLowerCase().includes("zoid")||p.toLowerCase().includes("postrobot")||p.toLowerCase().includes("storage"))&&(se(`window:rejection ${p.slice(0,140)}`),tn.push(p))},zn={value:0},zr=()=>{fr?.disconnect(),fr=null,gr?.disconnect(),gr=null;for(let c of tr.splice(0))clearTimeout(c);Tt=!1,Wn&&typeof window<"u"&&(window.removeEventListener("error",Qt),window.removeEventListener("unhandledrejection",xr)),Wn=!1},rr=()=>{if(!(Wn||Qe()||Mn)){if(Wn=!0,tn.length=0,zn.value=0,typeof window<"u"&&(window.addEventListener("error",Qt),window.addEventListener("unhandledrejection",xr)),typeof PerformanceObserver<"u")try{gr=new PerformanceObserver(c=>{if(!Qe())for(let p of c.getEntries()){if(!p.name.toLowerCase().includes("paypal"))continue;zn.value+=1;let _=Math.round(p.duration);se(`net ${_}ms ${p.name.slice(0,90)}`)}}),gr.observe({type:"resource",buffered:!0})}catch{}nr?.()}},or=()=>{Vn&&(clearTimeout(Vn),Vn=null)},yn=()=>{zr(),or()},ar={setEnabled:c=>{c?rr():zr()}};Ht.current=ar,mt.current&&rr();let Br=c=>{if(!c)return!1;let p=c.toLowerCase();return p.includes("zoid destroyed")||p.includes("destroyed all components")||p.includes("window closed")||p.includes("detected container element removed")},Rn=c=>{if(Qe()||Br(c))return;let p=Kr(c)??c;At(()=>_t.current?.(p))},I=(c,p)=>{if(Wt||Ar)return;Ar=!0,Hn=!0,yn(),yr();let _=Nd({kind:c,generationActive:!0,automaticRetryAllowed:H,automaticRetryUsed:Lt.current});if(_.action==="retry"){Lt.current=!0,G(!1),ae(!1),ot(!0),Bt.current?.("retrying"),Tr=setTimeout(()=>{Wt||Ke(M=>M+1)},xd);return}if(G(!1),ae(!1),ot(!1),Rt(!0),_.action!=="ignore"){if(Bt.current?.("exhausted"),_.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",p);return}if(_.report){let M=Ai({code:Ol(c,p),message:p},{inAppBrowser:F.inAppBrowser,handoffObserved:!1});M.popupBlocked&&z.markBlocked(),W.error({errorCode:M.popupBlocked?M.errorCode:_.report.errorCode,stage:_.report.stage,operationOutcome:_.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:M.terminalReason})}Kt.current||(Kt.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",Ol(c,p)))}};Rt(!1);let E=async(c,p=Vt.current)=>{if(Qe())return;let _=p?.sessionId??e;if(Nn.current){await Nn.current(c,{sessionId:_,accountPatch:p?.accountPatch,nonce:p?.nonce});return}let M=W.startTiming();W.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let te=()=>{W.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),W.performance({stage:"processing",durationMs:W.elapsed(M),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let K=wn.current,ze=p?.accountPatch?.email??Et.current,Pt=p?.accountPatch?.userId??K?.customer?.id??K?.accountData?.userId??"",w=p?.accountPatch?.firstName??K?.customer?.firstName??K?.accountData?.firstName,ye=p?.accountPatch?.lastName??K?.customer?.lastName??K?.accountData?.lastName,ce=await new Li(wt,{telemetry:!1}).processPayment(Pt,{sessionId:_,nonce:p?.nonce??un.current,paymentMethodCategory:"paypal",tokenizedData:c,accountData:{userId:Pt,email:ze??K?.customer?.email??"",...w?{firstName:w}:{},...ye?{lastName:ye}:{},country:p?.accountPatch?.country??K?.customer?.country??K?.accountData?.country??void 0,zip:p?.accountPatch?.zip??K?.customer?.zip??K?.accountData?.zip??void 0}});if(ce.ok){if(Hn||Wt&&Kn.current)return;te(),W.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),At(()=>On.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Qe())return;let x=await ce.json().catch(()=>null),Q=x?.message??"PayPal payment failed.",C=Kr(Q)??Q;te(),ce.status===400&&(typeof x?.declineCode=="string"||!Array.isArray(x?.fields))?W.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):ce.status===400||ce.status===422?W.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):W.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:Ld(ce.status),failureCategory:ce.status>=500?"server_error":void 0}),Rn(C),At(()=>Sn.current?.(ln("paypal",C,{code:x?.code,declineCode:x?.declineCode})));return}catch(K){if(Qe())return;te(),W.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let ze=K instanceof Error?K.message:"PayPal payment failed.",Pt=Kr(ze)??ze;Rn(Pt),At(()=>Sn.current?.(ln("paypal",Pt)));return}},k=()=>new zi("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),ee=c=>Qe()?Promise.reject(k()):Promise.resolve(c),Ee=async c=>{if(Qe())throw k();Gt||mn();let p=Vt.current,_=p?.sessionId??e,M=p?.nonce??un.current;W.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let te;try{te=await new Li(wt,{telemetry:!1}).createSessionIntent(_,M??"",xt?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:Ui,paymentMethodId:null,intentKind:f==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:Lr})}catch(K){throw W.error({...Rd(K,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),K}if(Qe())throw k();if(te.provider!=="paypal"||te.providerObjectType!==f)throw new Error(c);return W.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),te.providerObjectId},lt=(c,p)=>{let _=p?.nonce??un.current;if(!_)return;let M=p?.sessionId??e,te=ra(c)??Ur(c)??"provider_declined";new Li(wt,{telemetry:!1}).reportSessionIntentDecline(M,_,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:te}).catch(()=>{})},re=ke;se("loadScript:scheduled (deferred 1 tick)");let Te=null,q=setTimeout(()=>{if(Wt){se("loadScript:skipped (cancelled before defer ran)");return}se("loadScript:start");let c=le==="live"?"production":le,p={};f==="subscription"?p={intent:"subscription",vault:!0}:f==="order"&&(p={intent:"capture"}),Te=Ad({clientId:s,currency:y,...p,...c?{environment:c}:{},...c==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let _=!1;Te.then(M=>{if(_=!0,se(`loadScript:resolved inactive=${Qe()} ns=${!!M} buttons=${!!M?.Buttons}`),Qe())return;if(!M?.Buttons){se("FAIL: namespace missing Buttons factory"),I("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}W.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),W.performance({stage:"provider_ready",durationMs:W.elapsed($e.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),W.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let te=async(ce,x)=>{if(Qe()||He.current!==re)return;let Q=ce.vaultSetupToken??ce.subscriptionID??ce.orderID??"",C=Q?$n.current.get(Q):rn.current.get(re);if(!(!C||!Ln(C.generation))&&Dt(C.generation)){$n.current.delete(Q),rn.current.delete(C.surfaceKey),Ft("approved");try{if(ae(!0),At(()=>_t.current?.(null)),!Q)throw new zi("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let Be=wn.current,vt=no(kn.current??[Be?.customer?.firstName,Be?.customer?.lastName].filter(Boolean).join(" ")),Se=Dn({email:C.accountPatch?.email?.trim()||Et.current?.trim()||Be?.customer?.email?.trim(),firstName:C.accountPatch?.firstName?.trim()||vt.firstName,lastName:C.accountPatch?.lastName?.trim()||vt.lastName});if(!ua(Se.email)||!(Se.firstName||Se.lastName))try{let Pr=Od(await x?.order?.get?.());Se=Dn({email:Pr.email||Se.email,firstName:Pr.firstName||Se.firstName,lastName:Pr.lastName||Se.lastName})}catch{}if((Ze.current||Le)&&!ua(Se.email)){let Pr=await U("PayPal",Se);if(!Pr)return;Se=Pr}ua(Se.email)&&(C.accountPatch=Dn({...C.accountPatch,...Se}),await Ze.current?.(Se));let vn;f==="setup_token"?vn={id:Q,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:Ui}:xt?vn={id:Q,isPaypal:!0,gateway:"paypal",paymentMethodType:Ui}:vn={id:Q,isPaypal:!0},await E(vn,C)}catch(Be){Rn(Be instanceof Error?Be.message:"PayPal capture failed.")}finally{Qe()||ae(!1)}}},K=ce=>{let x=Ye?()=>ee(Ye):()=>Ee(ce);return async()=>hn(await x())},ze=M.Buttons({style:{layout:"horizontal",height:Ka,tagline:!1},...ne==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(ce,x)=>{if(Qe()){await x.reject();return}mn();let Q=Fe.current,C={};if(Q)try{let Se=await Q("paypal");if(Qe()){await x.reject();return}if(!Se.proceed){Vt.current=null,rn.current.delete(re),await x.reject();return}C={sessionId:Se.sessionId,accountPatch:Se.accountPatch,nonce:Se.nonce}}catch(Se){se(`onClick:runBeforeButtonClick rejected msg=${(Se instanceof Error?Se.message:String(Se)).slice(0,120)}`),Vt.current=null,rn.current.delete(re),await x.reject();return}At(()=>jn.current?.("paypal"));let Be=zt(),vt={generation:Be,surfaceKey:re,...C};Vt.current=vt,rn.current.set(re,vt),dt.current={...S,attempt:Be},await x.resolve(),W.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),W.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),Je.current=W.startTiming()},createOrder:f==="order"?K("Failed to create PayPal order."):void 0,createSubscription:f==="subscription"?K("Failed to create PayPal subscription."):void 0,createVaultSetupToken:f==="setup_token"?async()=>hn(await Ee("Failed to create PayPal setup token.")):void 0,onApprove:te,onCancel:()=>{if(Qe())return;let ce=rn.current.get(re)??Vt.current;ce&&rn.current.delete(ce.surfaceKey),Vt.current=null,Ft("cancelled"),W.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Ce.current=!0,er({generation:ce?.generation,remount:!0,focus:!1})},onError:ce=>{if(Qe()||He.current!==re)return;let x=ce instanceof Error?ce.message:"PayPal failed to render.";if(se(`onError rendered=${Mn} msg=${x.slice(0,120)}`),Mn){let Q=rn.current.get(re)??Vt.current;if(Q&&!Ln(Q.generation)||!Q&&Er())return;if(Br(x)){Dt(Q?.generation);return}let{errorCode:C,popupBlocked:Be,providerDeclined:vt,terminalReason:Se}=Ai(ce,{inAppBrowser:F.inAppBrowser,handoffObserved:Q!=null&&L.current===Q.generation});if(Be&&z.markBlocked(),Ft(Se),vt){W.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:Se}),lt(ce,Q),At(()=>Sn.current?.(ln("paypal",x))),Q&&rn.current.delete(Q.surfaceKey),Vt.current=null,Dt(Q?.generation);return}W.error({errorCode:C,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:Se}),Q&&rn.current.delete(Q.surfaceKey),Vt.current=null,er({generation:Q?.generation,remount:!0,showRetry:!0,focus:!0}),en(ce,{code:"paypal_runtime_failed",popupBlocked:Be,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:ne,terminalReason:Se});return}I(Br(x)?"teardown":"pre_ready_callback",x)}}),Pt=ze.isEligible();if(se(`isEligible=${Pt}`),W.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!Pt){G(!1),I("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Mr=!0,An=ze,nr=()=>{if(!Wn||Tt||Qe()||Mn)return;Tt=!0,se(`container:dims ${In(xn)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(fr=new MutationObserver(x=>{if(!Qe()){for(let Q of x)if(Q.type==="childList")Q.addedNodes.forEach(C=>{if(!(C instanceof Element))return;let Be=C.tagName.toLowerCase(),vt=(C.getAttribute("title")??"").slice(0,40),Se=Be==="iframe"?` ${hr(C)}`:"";se(`child+ ${Be}${vt?` title="${vt}"`:""}${Se} dims=${In(C)}`)});else if(Q.type==="attributes"&&Q.target instanceof Element){let C=Q.target;if(C.tagName.toLowerCase()!=="iframe")continue;let Be=Q.attributeName;(Be==="src"||Be==="srcdoc")&&se(`attr~ iframe ${Be}=${Be==="srcdoc"?`[${(C.getAttribute("srcdoc")??"").length}ch]`:Gn(C.getAttribute("src"))} dims=${In(C)}`)}}}),fr.observe(xn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let ce=x=>{if(Qe()||Mn)return;let Q=xn.querySelectorAll("iframe"),C=typeof document<"u"&&"hasStorageAccess"in document;se(`watchdog:${x} container=${In(xn)} children=${xn.childElementCount} iframes=${Q.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${C} paypalNetRequests=${zn.value}`),Q.forEach((Be,vt)=>{let Se=(Be.getAttribute("title")??"").slice(0,40);se(` iframe[${vt}] ${In(Be)}${Se?` title="${Se}"`:""} ${hr(Be)}`);let vn=it(Be);vn&&se(` ${vn}`)}),tn.length===0&&se(" (no PayPal/zoid window errors captured)")};tr.push(setTimeout(()=>ce("3s"),3e3)),tr.push(setTimeout(()=>ce("8s"),8e3)),tr.push(setTimeout(()=>ce("15s"),15e3))},nr(),se("render:start");let ye=W.startTiming();Vn=setTimeout(()=>{Qe()||Mn||(se("watchdog:11s retryable render timeout"),I("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},Bd);let It=ze.render(xn);(async()=>{try{if(await It,se(`render:resolved inactive=${Qe()}`),yn(),Qe()){yr();return}Mn=!0,G(!0),ot(!1),Bt.current?.("ready"),W.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),W.performance({stage:"checkout_render",durationMs:W.elapsed(ye),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(ce){let x=ce instanceof Error?ce.message:"PayPal failed to render.";se(`render:rejected msg=${x.slice(0,120)}`),yn(),I(Br(x)?"teardown":"render_rejected",x)}})()}).catch(M=>{let te=M instanceof Error?M.message:"PayPal operation failed.";se(`provider:failed msg=${te.slice(0,120)}`);let K="script_rejected";_&&Br(te)?K="teardown":_&&Mr&&(K="render_rejected"),I(K,te)})},0);return()=>{Wt=!0,clearTimeout(q),Tr&&clearTimeout(Tr),yn(),Ht.current===ar&&(Ht.current=null),yr(),Je.current=null,dt.current=null}},[H,wt,s,y,l,f,ne,xt,e,Ye,ke,he,U,Le,se,Ft]);let Z=fe?qi("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:ut?"#fef2f2":"#f3f4f6",border:`1px solid ${ut?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${Xe} failed=${ut})`,Ae.length===0?`
1
+ import{a as Pl}from"./chunk-JUUKXJQQ.mjs";import{c as At,d as wr,e as ta,f as Ti,g as na,h as ul,i as pl,j as Qc,l as ed}from"./chunk-I4TPZWBS.mjs";import{a as gl}from"./chunk-YSFYLEHB.mjs";import{a as hl}from"./chunk-OYOJA6FI.mjs";import{a as Da,b as ml,c as Ur,d as ra,e as Na,f as yl,g as Ai,h as qr,i as oa,j as fl,k as Oa}from"./chunk-M7R46EDF.mjs";import{dropThirdPartyOnlyError as $y}from"@flopay/shared";import{PaymentAPI as Es}from"@flopay/js";import{FloPayError as wa,resolveBillingApiUrl as cp,resolveButtonsLayoutTheme as dp,resolveTheme as up}from"@flopay/shared";import{useCallback as Or,useEffect as zo,useMemo as Sa,useRef as Uo,useState as qo}from"react";import{Fragment as wo,jsx as Jn,jsxs as vl}from"react/jsx-runtime";function td(){return vl(wo,{children:[vl("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[Jn("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),Jn("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",Jn("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"#9ca3af",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem"},"aria-hidden":"true",children:Jn("path",{d:"M9 18l6-6-6-6"})})]})}function nd(){return Jn(wo,{children:"Go back"})}function rd(){return Jn(wo,{children:"Secure card checkout"})}function bo(e){return e!==void 0&&(e===""||e===null||e===!1)}function Co({content:e}){return Jn(wo,{children:e===void 0?Jn(td,{}):e})}function So({content:e}){return Jn(wo,{children:e===void 0?Jn(nd,{}):e})}function aa({content:e}){return Jn(wo,{children:e===void 0?Jn(rd,{}):e})}import{CHECKOUT_PROCESSING_TIMEOUT_MESSAGE as od,classifyTelemetryFailure as ad,FloPayError as _n,isCardHolderNamePlaceholder as bl,isMoneySettledOutcome as id,isSetupIntentClientSecret as sd,isValidEmail as ld}from"@flopay/shared";var cd="Checkout is temporarily unavailable. Please try again later.";function Mi(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof _n&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function dd(e){return e.type==="validation_error"||e.code==="checkout_session_not_found"||e.code==="checkout_session_expired"||e.code==="checkout_session_completed"||e.code==="session_auto_completed"}function Cl(){return new _n(cd,"api_error",{code:"CheckoutInitializationFailed"})}function xi(e){return!!e?.gateways?.worldpayCorporateGateway}function jr(e){return e?.status==="open"&&xi(e)}function Sl(e,t,n){let r=e?.data.session,o=r?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(n&&(r?.vault?.html||r?.gateways?.pcivault||o?.includes("card")||jr(r))||t&&e?.data.paypal?.publishableKey)}function wl(e,t){if(t&&(!(e instanceof _n)||e.type==="authentication_error"))return Mi(e);if(!(e instanceof _n&&dd(e))){if(!t&&!(e instanceof _n)&&(e instanceof TypeError||e instanceof SyntaxError))return{...ad(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof _n)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof _n))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function ko(e,t,n,r={}){let o;return(i={})=>{if(o)return o;let s={...r,...i,email:i.email?.trim()||r.email?.trim()},l=bl(s.firstName,s.lastName);if(!ld(s.email))return Promise.reject(new _n("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let y={};for(let[u,b]of Object.entries(s)){if(l&&u.endsWith("Name")||typeof b!="string")continue;let P=b.trim();P&&(y[u]=P)}return o=e.claimCheckoutSession(t,n,{accountData:y}),o.catch(()=>{}),o}}function kl(e,t){if(!t)return e;if(!e)return t;let n;return"checkoutMetadata"in t?n=t:"checkoutMetadata"in e&&(n=e),{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,...n?{checkoutMetadata:n.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}}function Bi(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,..."checkoutMetadata"in t?{checkoutMetadata:t.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function Il(e,t){let n=e.products??[...(e.subscriptions??[]).map(i=>({type:"subscription",code:i.code??i.providerPlanId,name:i.subscriptionName??i.providerPlanName??i.code??i.providerPlanId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata})),...(e.items??[]).map(i=>({type:"item",code:i.code??i.providerItemId,name:i.itemName??i.providerItemName??i.code??i.providerItemId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata}))],r=n.reduce((i,s)=>i+(s.overrideAmount??s.totalAmount??0),0),o=e.currency??n.find(i=>i.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(i=>i.type==="subscription")?"subscription":"payment",amount:Math.round(r*100),currency:o,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((i,s)=>({uuid:`synthetic-${i.type??"item"}-${s}`,checkoutSessionId:"",type:i.type??"item",code:i.code,name:i.name??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount??null,currency:i.currency??o,metadata:i.metadata??null}))}}function no(e){if(bl(e))return{};let[t,...n]=e?.trim().split(/\s+/)??[];return t?{firstName:t,lastName:n.join(" ")||void 0}:{}}function Fi(e,t){return t?{...e,...t}:e}function ln(e,t,n){let r=typeof t=="string"?t:t.message,o=typeof t=="string"?n?.code:n?.code??t.code,i=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode,s=typeof t=="string"?void 0:t.sessionId;return{method:e,message:r,...o?{code:o}:{},...i?{declineCode:i}:{},...s?{sessionId:s}:{}}}function $r(e,t){return t&&e.sessionId===void 0&&Object.defineProperty(e,"sessionId",{value:t,enumerable:!0}),e}var ud=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function Kr(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of ud)if(n.test(t))return r;return e}function Fr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function Dr(e){return e?.status==="authorized"||e?.status==="complete"}function Hr(e,t){if(e.data.session)return e.data.session;let n=e.raw,r=n?.latestTransactionAttempt?.result,o=n?.status==="authorized"||r==="AUTHORIZED";return o||n?.status==="completed"||r==="SUCCESS"?{...t,status:o?"authorized":"complete"}:n?.status==="expired"?{...t,status:"expired"}:void 0}function Rl(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function La(e){let t=Rl(e);return new _n(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function za(e){return e instanceof _n||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function Io(e){return Rl(e)?new _n("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new _n("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new _n(od,"api_error",{code:"checkout_processing_timeout"})}function ia(e,t){return e==="processing"||id(e,t)}function _l(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function El(e,t){let n=e;if(sd(t)){if(!n?.retrieveSetupIntent)return null;let{setupIntent:i,error:s}=await n.retrieveSetupIntent(t);if(s)throw new _n(s.message??"Failed to retrieve setup intent.","api_error",{...s.code?{code:s.code}:{}});return i??null}if(!n?.retrievePaymentIntent)return null;let{paymentIntent:r,error:o}=await n.retrievePaymentIntent(t);if(o)throw new _n(o.message??"Failed to retrieve payment intent.","api_error",{...o.code?{code:o.code}:{}});return r??null}function Tl(e,t="automatic"){return{...typeof e=="number"&&Number.isFinite(e)&&e>0?{mode:"payment",amount:e,captureMethod:t==="manual"?"manual":"automatic_async"}:{mode:"setup"},paymentMethodTypes:["card"],setupFutureUsage:"off_session"}}function Di(e){let t=e&&typeof e=="object"?e:null;return t?.name==="IntegrationError"||t?.code==="elements_intent_mismatch"||t?.type==="invalid_request_error"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function sa(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}import{FloPay as Wu,PaymentAPI as li,SESSION_CREATE_TELEMETRY as Gu}from"@flopay/js";import{buildCheckoutDisplayData as Yu,classifyTelemetryFailure as Mc,FloPayError as Cn,isDetachedSessionEligible as Ju,resolveBillingApiUrl as Xu,resolveButtonsLayoutTheme as Zu,resolveIdempotencyKey as kc,resolveTheme as xc,SDK_VERSION as Bc,telemetryStatusClass as Qu}from"@flopay/shared";import vs,{useCallback as bn,useEffect as mr,useMemo as Zn,useRef as Mt,useState as $t}from"react";import{createContext as Al}from"react";var Xn=Al({flopay:null,paypalFlopay:null,billingApiUrl:""}),dr=Al({session:null,loading:!1,error:null});import{PaymentAPI as Li}from"@flopay/js";import{classifyTelemetryFailure as Rd,FloPayError as zi,generateIdempotencyKey as _d,isValidEmail as ua,normalizeGatewayEnvironment as Ed,PAYPAL_VAULTED_PAYMENT_METHOD_TYPE as Ui,SDK_VERSION as Td}from"@flopay/shared";import{loadScript as Ad}from"@paypal/paypal-js";import{useCallback as kr,useContext as Md,useEffect as Ot,useMemo as pa,useRef as nt,useState as Gr}from"react";import{isValidEmail as pd}from"@flopay/shared";import{useCallback as Ml,useEffect as md,useRef as xl,useState as Fl}from"react";import{jsx as Bl,jsxs as la}from"react/jsx-runtime";function Dn(e,t=!1){let{firstName:n,lastName:r,...o}=e,i=n?.trim(),s=r?.trim();return{...o,...i||t?{firstName:i??""}:{},...s||t?{lastName:s??""}:{}}}function Ro(){let[e,t]=Fl(null),n=xl(null),r=xl(0),o=Ml((s,l)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:s,identity:l}),new Promise(y=>{n.current=y})),[]),i=Ml(s=>{let l=n.current;n.current=null,t(null),l?.(s)},[]);return md(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:i}}function _o({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:i="flopay-buyer-identity-pane"}){let[s,l]=Fl(e.email?.trim()??""),y=pd(s.trim());return la("div",{"data-testid":i,style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"0.875rem",border:"1px solid #d1d5db",borderRadius:8,background:"#fff",color:"#262833"},children:[la("div",{style:{fontWeight:700},children:["Continue with ",t]}),la("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",Bl("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:s,onChange:u=>l(u.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),la("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&Bl("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),la("button",{type:"button",disabled:!y||o,onClick:()=>{n(Dn({...e,email:s.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}import{resolveBillingApiUrl as yd}from"@flopay/shared";import{useContext as Ua}from"react";function Vr(){return Ua(Xn).flopay}function Ni(){return Ua(Xn).paypalFlopay??null}function fd(){return Ua(dr)}function Dl(){return Ua(Xn).billingApiUrl||yd()}import{FLO_INSTRUMENT_SCHEMA_VERSION as gd}from"@flopay/shared";import{useCallback as hd,useRef as qa}from"react";var Pd={"checkout.mount":"checkout_mount","sdk.initialize.ready":"sdk_loaded","provider.ready":"sdk_loaded","checkout.rendered":"form_rendered","vault.widget.ready":"form_rendered","vault.submission.started":"tokenize","payment.tokenization.started":"tokenize","payment.processing.started":"process_attempt","payment.intent.started":"process_attempt","vault.action.required":"3ds_challenge","payment.three_ds.handoff":"3ds_challenge"};function vd(e){return e==="stripe"||e==="paypal"?e:void 0}function bd(e){let t=vd(e.provider),n={schemaVersion:gd,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=Pd[e.name];return r?{...n,name:r}:null}return e.class==="card_surface"?{...n,name:"card_expanded"}:e.errorCode==="CHECKOUT_SESSION_CREATE_FAILED"?{...n,name:"checkout_error",phase:"session_create"}:e.errorCode==="SDK_INITIALIZATION_FAILED"||e.errorCode==="PROVIDER_LOAD_FAILED"?{...n,name:"checkout_error",phase:"sdk_load"}:e.errorCode==="PAYMENT_PROCESSING_FAILED"?{...n,name:"checkout_error",phase:e.requestCategory==="intent_create"?"wallets":"process"}:null}var Oi=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function Eo(e,t){let n=qa(e);n.current=e;let r=qa(new Set),o=qa(t),i=qa(t);return ta(()=>{i.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),hd(s=>{if(i.current!==t)return;let l=bd(s);if(l){if(Oi.has(l.name)){if(r.current.has(l.name))return;r.current.add(l.name)}At(()=>n.current?.(l))}},[t])}import{createContext as Cd}from"react";var ca=Cd(null);function ja(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var Sd=Symbol.for("@flopay/js.telemetry.bridge.v1"),wd=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function kd(){return{error:()=>{},log:()=>{},performance:()=>{},terminal:()=>{},now:()=>globalThis.performance?.now()??0,elapsed:e=>Math.max(0,(globalThis.performance?.now()??e)-e),setCheckoutContext:()=>{},beginCheckout:()=>globalThis.performance?.now()??0,disable:()=>{},subscribe:()=>()=>{},flush:async()=>{},destroy:()=>{}}}function Id(e){let t=kd(),n=(o,i)=>o?o.bind(e):i,r=n(e.now,t.now);return{error:n(e.error,t.error),log:n(e.log,t.log),performance:n(e.performance,t.performance),terminal:n(e.terminal,t.terminal),now:r,elapsed:e.elapsed?e.elapsed.bind(e):o=>Math.max(0,r()-o),setCheckoutContext:n(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:n(e.beginCheckout,t.beginCheckout),disable:n(e.disable,t.disable),subscribe:n(e.subscribe,t.subscribe),flush:n(e.flush,t.flush),destroy:n(e.destroy,t.destroy)}}function $a(e){let t=globalThis[wd];return Id(t?.(e)??{})}function cn(e){if(e)return e[Sd]}import{useCallback as Wr,useEffect as Nl,useRef as ro}from"react";function da(e,t){let n=ro(0),r=ro(null),o=ro(null),i=ro(e),s=ro(t?.onHandoffObserved),l=ro(t?.defersMissingTerminal),y=ro(t?.onMissingTerminalDeferred);Nl(()=>{i.current=e,s.current=t?.onHandoffObserved,l.current=t?.defersMissingTerminal,y.current=t?.onMissingTerminalDeferred},[e,t?.onHandoffObserved,t?.defersMissingTerminal,t?.onMissingTerminalDeferred]);let u=Wr((g=o.current)=>{g?.timer&&(clearTimeout(g.timer),g.timer=null)},[]),b=Wr(g=>{u();let v=n.current+1;return n.current=v,r.current=null,o.current={generation:v,method:g,timer:null,yieldedControl:!1},v},[u]),P=Wr(g=>{let v=o.current;return g!==void 0&&v?.generation!==g?!1:(u(v),o.current=null,(g===void 0||r.current===g)&&(r.current=null),!0)},[u]),D=Wr(g=>{let v=o.current,X=g??v?.generation??n.current;(g===void 0||v?.generation===g)&&(u(v),o.current=null),r.current=X},[u]),N=Wr(g=>r.current===(g??n.current),[]),R=Wr(g=>o.current?.generation===g&&r.current!==g,[]),O=Wr(()=>{let g=o.current;g&&(u(g),!g.yieldedControl&&(g.yieldedControl=!0,s.current?.(g.method)))},[u]),$=Wr(()=>{let g=o.current;!g?.yieldedControl||document.visibilityState!=="visible"||(u(g),g.timer=setTimeout(()=>{if(g.timer=null,o.current?.generation===g.generation){if(l.current?.(g.method)){y.current?.(g.method,g.generation);return}o.current=null,r.current=g.generation,i.current(g.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"})}},600))},[u]);return Nl(()=>{let g=()=>{document.visibilityState==="visible"?$():O()};return document.addEventListener("visibilitychange",g),window.addEventListener("blur",O),window.addEventListener("focus",$),()=>{document.removeEventListener("visibilitychange",g),window.removeEventListener("blur",O),window.removeEventListener("focus",$),u()}},[u,O,$]),{startAttempt:b,finishAttempt:P,invalidateAttempt:D,isAttemptInvalidated:N,isAttemptCurrent:R,generationRef:n}}import{jsx as oo,jsxs as qi}from"react/jsx-runtime";var Ka=45,xd=1e3,Bd=11e3,Fd={width:"100%",minHeight:Ka,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"},Dd={script_rejected:{errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",operationOutcome:"rejected"},namespace_unusable:{errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",operationOutcome:"returned_error"},pre_ready_callback:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"returned_error"},render_rejected:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"rejected"},watchdog_expired:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"watchdog_expired"}};function Nd(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:Dd[e.kind]??null}}function Ol(e,t){return e==="watchdog_expired"?"paypal_render_timeout":yl(t)?"paypal_init_timeout":"paypal_init_failure"}function Od(e){let t=e,n=t?.payer??t?.payment_source?.paypal;return{email:n?.email_address?.trim()||void 0,firstName:n?.name?.given_name?.trim()||void 0,lastName:n?.name?.surname?.trim()||void 0}}function Ld(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function Ll({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:i,clientId:s,environment:l,currency:y,isSubscription:u,providerObjectType:b,approvalPresentation:P,onTokenizedBody:D,onComplete:N,onErrorChange:R,onDecline:O,onTechnicalFailure:$,isProcessing:g=!1,onLoadStateChange:v,onInitializationStateChange:X,allowAutomaticRetry:H=!0,onButtonClick:pe,runBeforeButtonClick:V,session:De,existingOrderId:Ye,telemetry:be,telemetryContext:et,onInstrument:Ct,debug:fe=!1}){let qe=Vr(),St=Eo(Ct,e),Me=pa(()=>{if(qe)return null;let S=$a({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Td,enabled:be!==!1});return S.setCheckoutContext(et??{}),S.beginCheckout(et??{}),S},[n,qe,be,et?.checkoutMode,et?.layout]),je=pa(()=>cn(qe),[qe]);Ot(()=>()=>{Me&&Me.flush().catch(()=>{}).finally(()=>Me.destroy())},[Me]);let he=pa(()=>({error:S=>{je?je.error(S):Me?.error(S),St({class:"technical_error",errorCode:S.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":S.errorCode,requestCategory:S.requestCategory,provider:S.provider})},log:S=>{je?je.log(S):Me?.log(S),St({class:"lifecycle",name:S.name,provider:S.provider})},performance:S=>{je?je.performance(S):Me?.performance(S)},terminal:S=>{je?je.terminal(S):Me?.terminal(S)},startTiming:()=>je?.now()??Me?.now()??0,elapsed:S=>je?.elapsed(S)??Math.max(0,(Me?.now()??S)-S)}),[St,je,Me]),me=nt(null),$e=nt(0),Je=nt(null),dt=nt(null),L=nt(null),st=Md(ca),Pe=nt(null);Pe.current||(Pe.current=ja());let z=st??Pe.current,Ne=nt(null),Ce=nt(!1),[Xe,G]=Gr(!1),[tt,ot]=Gr(!1),[ke,Ke]=Gr(0),He=nt(0),[at,Ie]=Gr(!1),Lt=nt(!1),Kt=nt(!1),[ut,Rt]=Gr(!1),[T,ae]=Gr(!1),{request:Oe,collect:U,finish:Re}=Ro(),pt=nt({sessionId:e,required:!ua(r?.trim()||De?.customer?.email?.trim())});pt.current.sessionId!==e&&(pt.current={sessionId:e,required:!ua(r?.trim()||De?.customer?.email?.trim())});let Le=pt.current.required,wt=pa(()=>n.replace(/\/+$/,""),[n]),m=De?.gateways?.paypal?.providerObjectType??b,f=m??(u?"subscription":"order"),[F]=Gr(oa),A=De?.gateways?.paypal?.approvalPresentation??P,ne=Oa(F,A==="app_switch"?"app_switch":void 0,f),xt=m==="order"||m==="setup_token",_e=pa(()=>JSON.stringify([wt,s,y,l??"",f,xt,ne,e,Ye??""]),[wt,s,y,l,Ye,f,xt,ne,e]),xe=nt(_e),oe=xe.current!==_e,mt=nt(fe),Ht=nt(null),[Ae,En]=Gr([]),se=kr(S=>{mt.current&&En(Ve=>[...Ve,`${new Date().toISOString().slice(11,23)} ${S}`])},[]);Ot(()=>{mt.current=fe,fe&&se("debug:enabled"),Ht.current?.setEnabled(fe)},[se,fe]);let Nn=nt(D),On=nt(N),_t=nt(R),Sn=nt(O),Tn=nt($),jn=nt(pe),dn=nt(v),Bt=nt(X),Ze=nt(i),Fe=nt(V),wn=nt(De),Et=nt(r),kn=nt(o),un=nt(t),Vt=nt(null),rn=nt(new Map),$n=nt(new Map),Kn=nt(!1);Ot(()=>(Kn.current=!0,()=>{Kn.current=!1}),[]),Ot(()=>{Nn.current=D},[D]),Ot(()=>{Ze.current=i},[i]),Ot(()=>{On.current=N},[N]),Ot(()=>{_t.current=R},[R]),Ot(()=>{Sn.current=O},[O]),Ot(()=>{Tn.current=$},[$]),Ot(()=>{jn.current=pe},[pe]),Ot(()=>{dn.current=v},[v]),Ot(()=>{Bt.current=X},[X]),Ot(()=>{Fe.current=V},[V]),Ot(()=>{wn.current=De},[De]),Ot(()=>{Et.current=r},[r]),Ot(()=>{kn.current=o},[o]),Ot(()=>{un.current=t},[t]),Ot(()=>{He.current=ke},[ke]),Ot(()=>{at&&Ne.current?.focus()},[at,ke]);let kt=kr(()=>{window.setTimeout(()=>{Ne.current?.focus()},0)},[]),yt=kr(()=>{G(!1),Ke(S=>S+1)},[]),gn=kr(()=>{Ie(!1),(me.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??me.current)?.focus?.()},[]);Ot(()=>{!Xe||!Ce.current||(Ce.current=!1,gn())},[gn,Xe,ke]);let en=kr((S,Ve)=>{let W=Ve?.popupBlocked??qr(S);W&&z.markBlocked();let Pn=Da("PayPal",W,F.inAppBrowser),pn=Tn.current;if(pn){let Wt=W&&F.inAppBrowser?new zi(Pn,"api_error",{code:Ve?.code??"paypal_popup_blocked"}):S;pn("paypal",Wt,Ve);return}_t.current?.(Pn)},[z,F.inAppBrowser]),Ft=kr(S=>{let Ve=Je.current,W=dt.current;Ve===null||!W||(he.log({...W,popupCapability:z.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:S}),he.performance({...W,popupCapability:z.current(),stage:"overlay_return",durationMs:he.elapsed(Ve),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:S}),Je.current=null)},[z,he]),on=kr((S,Ve,W)=>{let Pn=dt.current;Ft("overlay_timeout"),Pn&&he.error({...Pn,popupCapability:z.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),en(Ve,{...W,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:ne,terminalReason:"overlay_timeout"}),Ie(!0),yt(),kt()},[Ft,kt,en,z,ne,yt,he]),Xt=kr(()=>{z.markAvailable();let S=dt.current;S&&(L.current=S.attempt,he.log({...S,popupCapability:z.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[z,he]),{finishAttempt:Dt,generationRef:Y,invalidateAttempt:an,isAttemptCurrent:Ln,isAttemptInvalidated:Er,startAttempt:Qn}=da(on,{onHandoffObserved:Xt}),zt=kr(()=>(Ie(!1),Qn("paypal")),[Qn]),er=kr(S=>{an(S?.generation),S?.showRetry&&Ie(!0),S?.remount&&yt(),S?.focus!==!1&&kt()},[kt,an,yt]),hn=S=>{let Ve=Vt.current;return Ve&&$n.current.set(S,Ve),S};Ot(()=>{xe.current!==_e&&(xe.current=_e,Lt.current=!1,Kt.current=!1,G(!1),ot(!1),Rt(!1),Bt.current?.("loading"))},[_e]),Ot(()=>{At(()=>dn.current?.(Xe&&!ut))},[Xe,ut]);let le=Ed(l);Ot(()=>{let S={attempt:Y.current+1,inAppBrowser:F.inAppBrowser,appFamily:F.appFamily,popupCapability:z.current(),presentationMode:ne},Ve=()=>({...dt.current??S,popupCapability:z.current()}),W={error:c=>he.error({...c,...Ve()}),log:c=>he.log({...c,...Ve()}),performance:c=>he.performance({...c,...Ve()}),terminal:c=>he.terminal({...c,...Ve()}),startTiming:he.startTiming,elapsed:he.elapsed},Pn=s?`${s.slice(0,6)}\u2026(len ${s.length})`:"(empty)",pn=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(se(`mount clientId=${Pn} env=${l??"(unset)"}\u2192${le??"live"} ccy=${y} sub=${u}`),se(`ua=${pn.slice(0,80)}${pn.length>80?"\u2026":""}`),!s){se("FAIL: clientId empty \u2014 gateway misconfigured"),Rt(!0),W.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!me.current){se("FAIL: containerRef not attached");return}$e.current=W.startTiming(),W.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Wt=!1,Hn=!1,Qe=()=>Wt||Hn,Lr,Gt=!1,mn=()=>{Lr=_d(),Lr||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Gt=!0},Tr=null,Ar=!1,An=null,Zt=!1,yr=()=>{!An||Zt||(Zt=!0,An.close().catch(()=>{}))},Mn=!1,Mr=!1,xn=me.current,fr=null,gr=null,tr=[],Vn=null,Wn=!1,Tt=!1,nr=null,In=c=>{if(!c||typeof c.getBoundingClientRect!="function")return"(no rect)";let p=c.getBoundingClientRect();return`${Math.round(p.width)}\xD7${Math.round(p.height)}`},Gn=c=>{if(!c)return"(empty)";try{let p=new URL(c,typeof window>"u"?"https://localhost":window.location.href),_=p.pathname.toLowerCase();return _.includes("checkcaptcha")||_.includes("captcha")?`CAPTCHA(${p.host}${_})`:_.includes("risk")||_.includes("challenge")?`RISK(${p.host}${_})`:_.includes("smart/buttons")?`smart-buttons(${p.host})`:`${p.host}${_}`.slice(0,100)}catch{return c.slice(0,80)}},hr=c=>{let p=c.getAttribute("src"),_=c.getAttribute("srcdoc"),M=c.getAttribute("name"),te=c.getAttribute("sandbox"),K=[];return p&&K.push(`src=${Gn(p)}`),_&&K.push(`srcdoc[${_.length}ch]`),!p&&!_&&K.push("src=(empty) srcdoc=(empty)"),M&&K.push(`name=${M.slice(0,40)}`),te!==null&&K.push(`sandbox="${te.slice(0,40)}"`),K.join(" ")},it=c=>{if(!(c instanceof HTMLIFrameElement))return"";try{let p=c.contentDocument;if(!p)return"cd=null";let _=p.body?.children.length??0,M=p.body?.innerHTML.length??0,te=p.head?.innerHTML.length??0;return`cd=same-origin readyState=${p.readyState} body[${_}children,${M}ch] head[${te}ch]`}catch(p){return`cd=cross-origin(${p.message.slice(0,30)})`}},tn=[],Qt=c=>{if(Qe())return;let p=c.message??String(c.error??"(no message)");p&&(p.toLowerCase().includes("paypal")||p.toLowerCase().includes("zoid")||p.toLowerCase().includes("postrobot")||p.toLowerCase().includes("storage"))&&(se(`window:error ${p.slice(0,140)}`),tn.push(p))},xr=c=>{if(Qe())return;let p=c.reason instanceof Error?c.reason.message:String(c.reason??"(no reason)");p&&(p.toLowerCase().includes("paypal")||p.toLowerCase().includes("zoid")||p.toLowerCase().includes("postrobot")||p.toLowerCase().includes("storage"))&&(se(`window:rejection ${p.slice(0,140)}`),tn.push(p))},zn={value:0},zr=()=>{fr?.disconnect(),fr=null,gr?.disconnect(),gr=null;for(let c of tr.splice(0))clearTimeout(c);Tt=!1,Wn&&typeof window<"u"&&(window.removeEventListener("error",Qt),window.removeEventListener("unhandledrejection",xr)),Wn=!1},rr=()=>{if(!(Wn||Qe()||Mn)){if(Wn=!0,tn.length=0,zn.value=0,typeof window<"u"&&(window.addEventListener("error",Qt),window.addEventListener("unhandledrejection",xr)),typeof PerformanceObserver<"u")try{gr=new PerformanceObserver(c=>{if(!Qe())for(let p of c.getEntries()){if(!p.name.toLowerCase().includes("paypal"))continue;zn.value+=1;let _=Math.round(p.duration);se(`net ${_}ms ${p.name.slice(0,90)}`)}}),gr.observe({type:"resource",buffered:!0})}catch{}nr?.()}},or=()=>{Vn&&(clearTimeout(Vn),Vn=null)},yn=()=>{zr(),or()},ar={setEnabled:c=>{c?rr():zr()}};Ht.current=ar,mt.current&&rr();let Br=c=>{if(!c)return!1;let p=c.toLowerCase();return p.includes("zoid destroyed")||p.includes("destroyed all components")||p.includes("window closed")||p.includes("detected container element removed")},Rn=c=>{if(Qe()||Br(c))return;let p=Kr(c)??c;At(()=>_t.current?.(p))},I=(c,p)=>{if(Wt||Ar)return;Ar=!0,Hn=!0,yn(),yr();let _=Nd({kind:c,generationActive:!0,automaticRetryAllowed:H,automaticRetryUsed:Lt.current});if(_.action==="retry"){Lt.current=!0,G(!1),ae(!1),ot(!0),Bt.current?.("retrying"),Tr=setTimeout(()=>{Wt||Ke(M=>M+1)},xd);return}if(G(!1),ae(!1),ot(!1),Rt(!0),_.action!=="ignore"){if(Bt.current?.("exhausted"),_.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",p);return}if(_.report){let M=Ai({code:Ol(c,p),message:p},{inAppBrowser:F.inAppBrowser,handoffObserved:!1});M.popupBlocked&&z.markBlocked(),W.error({errorCode:M.popupBlocked?M.errorCode:_.report.errorCode,stage:_.report.stage,operationOutcome:_.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:M.terminalReason})}Kt.current||(Kt.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",Ol(c,p)))}};Rt(!1);let E=async(c,p=Vt.current)=>{if(Qe())return;let _=p?.sessionId??e;if(Nn.current){await Nn.current(c,{sessionId:_,accountPatch:p?.accountPatch,nonce:p?.nonce});return}let M=W.startTiming();W.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let te=()=>{W.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),W.performance({stage:"processing",durationMs:W.elapsed(M),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let K=wn.current,ze=p?.accountPatch?.email??Et.current,Pt=p?.accountPatch?.userId??K?.customer?.id??K?.accountData?.userId??"",w=p?.accountPatch?.firstName??K?.customer?.firstName??K?.accountData?.firstName,ye=p?.accountPatch?.lastName??K?.customer?.lastName??K?.accountData?.lastName,ce=await new Li(wt,{telemetry:!1}).processPayment(Pt,{sessionId:_,nonce:p?.nonce??un.current,paymentMethodCategory:"paypal",tokenizedData:c,accountData:{userId:Pt,email:ze??K?.customer?.email??"",...w?{firstName:w}:{},...ye?{lastName:ye}:{},country:p?.accountPatch?.country??K?.customer?.country??K?.accountData?.country??void 0,zip:p?.accountPatch?.zip??K?.customer?.zip??K?.accountData?.zip??void 0}});if(ce.ok){if(Hn||Wt&&Kn.current)return;te(),W.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),At(()=>On.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Qe())return;let x=await ce.json().catch(()=>null),Q=x?.message??"PayPal payment failed.",C=Kr(Q)??Q;te(),ce.status===400&&(typeof x?.declineCode=="string"||!Array.isArray(x?.fields))?W.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):ce.status===400||ce.status===422?W.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):W.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:Ld(ce.status),failureCategory:ce.status>=500?"server_error":void 0}),Rn(C),At(()=>Sn.current?.(ln("paypal",C,{code:x?.code,declineCode:x?.declineCode})));return}catch(K){if(Qe())return;te(),W.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let ze=K instanceof Error?K.message:"PayPal payment failed.",Pt=Kr(ze)??ze;Rn(Pt),At(()=>Sn.current?.(ln("paypal",Pt)));return}},k=()=>new zi("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),ee=c=>Qe()?Promise.reject(k()):Promise.resolve(c),Ee=async c=>{if(Qe())throw k();Gt||mn();let p=Vt.current,_=p?.sessionId??e,M=p?.nonce??un.current;W.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let te;try{te=await new Li(wt,{telemetry:!1}).createSessionIntent(_,M??"",xt?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:Ui,paymentMethodId:null,intentKind:f==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:Lr})}catch(K){throw W.error({...Rd(K,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),K}if(Qe())throw k();if(te.provider!=="paypal"||te.providerObjectType!==f)throw new Error(c);return W.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),te.providerObjectId},lt=(c,p)=>{let _=p?.nonce??un.current;if(!_)return;let M=p?.sessionId??e,te=ra(c)??Ur(c)??"provider_declined";new Li(wt,{telemetry:!1}).reportSessionIntentDecline(M,_,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:te}).catch(()=>{})},re=ke;se("loadScript:scheduled (deferred 1 tick)");let Te=null,q=setTimeout(()=>{if(Wt){se("loadScript:skipped (cancelled before defer ran)");return}se("loadScript:start");let c=le==="live"?"production":le,p={};f==="subscription"?p={intent:"subscription",vault:!0}:f==="order"&&(p={intent:"capture"}),Te=Ad({clientId:s,currency:y,...p,...c?{environment:c}:{},...c==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let _=!1;Te.then(M=>{if(_=!0,se(`loadScript:resolved inactive=${Qe()} ns=${!!M} buttons=${!!M?.Buttons}`),Qe())return;if(!M?.Buttons){se("FAIL: namespace missing Buttons factory"),I("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}W.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),W.performance({stage:"provider_ready",durationMs:W.elapsed($e.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),W.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let te=async(ce,x)=>{if(Qe()||He.current!==re)return;let Q=ce.vaultSetupToken??ce.subscriptionID??ce.orderID??"",C=Q?$n.current.get(Q):rn.current.get(re);if(!(!C||!Ln(C.generation))&&Dt(C.generation)){$n.current.delete(Q),rn.current.delete(C.surfaceKey),Ft("approved");try{if(ae(!0),At(()=>_t.current?.(null)),!Q)throw new zi("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let Be=wn.current,vt=no(kn.current??[Be?.customer?.firstName,Be?.customer?.lastName].filter(Boolean).join(" ")),Se=Dn({email:C.accountPatch?.email?.trim()||Et.current?.trim()||Be?.customer?.email?.trim(),firstName:C.accountPatch?.firstName?.trim()||vt.firstName,lastName:C.accountPatch?.lastName?.trim()||vt.lastName});if(!ua(Se.email)||!(Se.firstName||Se.lastName))try{let Pr=Od(await x?.order?.get?.());Se=Dn({email:Pr.email||Se.email,firstName:Pr.firstName||Se.firstName,lastName:Pr.lastName||Se.lastName})}catch{}if((Ze.current||Le)&&!ua(Se.email)){let Pr=await U("PayPal",Se);if(!Pr)return;Se=Pr}ua(Se.email)&&(C.accountPatch=Dn({...C.accountPatch,...Se}),await Ze.current?.(Se));let vn;f==="setup_token"?vn={id:Q,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:Ui}:xt?vn={id:Q,isPaypal:!0,gateway:"paypal",paymentMethodType:Ui}:vn={id:Q,isPaypal:!0},await E(vn,C)}catch(Be){Rn(Be instanceof Error?Be.message:"PayPal capture failed.")}finally{Qe()||ae(!1)}}},K=ce=>{let x=Ye?()=>ee(Ye):()=>Ee(ce);return async()=>hn(await x())},ze=M.Buttons({style:{layout:"horizontal",height:Ka,tagline:!1},...ne==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(ce,x)=>{if(Qe()){await x.reject();return}mn();let Q=Fe.current,C={};if(Q)try{let Se=await Q("paypal");if(Qe()){await x.reject();return}if(!Se.proceed){Vt.current=null,rn.current.delete(re),await x.reject();return}C={sessionId:Se.sessionId,accountPatch:Se.accountPatch,nonce:Se.nonce}}catch(Se){se(`onClick:runBeforeButtonClick rejected msg=${(Se instanceof Error?Se.message:String(Se)).slice(0,120)}`),Vt.current=null,rn.current.delete(re),await x.reject();return}At(()=>jn.current?.("paypal"));let Be=zt(),vt={generation:Be,surfaceKey:re,...C};Vt.current=vt,rn.current.set(re,vt),dt.current={...S,attempt:Be},await x.resolve(),W.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),W.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),Je.current=W.startTiming()},createOrder:f==="order"?K("Failed to create PayPal order."):void 0,createSubscription:f==="subscription"?K("Failed to create PayPal subscription."):void 0,createVaultSetupToken:f==="setup_token"?async()=>hn(await Ee("Failed to create PayPal setup token.")):void 0,onApprove:te,onCancel:()=>{if(Qe())return;let ce=rn.current.get(re)??Vt.current;ce&&rn.current.delete(ce.surfaceKey),Vt.current=null,Ft("cancelled"),W.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Ce.current=!0,er({generation:ce?.generation,remount:!0,focus:!1})},onError:ce=>{if(Qe()||He.current!==re)return;let x=ce instanceof Error?ce.message:"PayPal failed to render.";if(se(`onError rendered=${Mn} msg=${x.slice(0,120)}`),Mn){let Q=rn.current.get(re)??Vt.current;if(Q&&!Ln(Q.generation)||!Q&&Er())return;if(Br(x)){Dt(Q?.generation);return}let{errorCode:C,popupBlocked:Be,providerDeclined:vt,terminalReason:Se}=Ai(ce,{inAppBrowser:F.inAppBrowser,handoffObserved:Q!=null&&L.current===Q.generation});if(Be&&z.markBlocked(),Ft(Se),vt){W.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:Se}),lt(ce,Q),At(()=>Sn.current?.(ln("paypal",x))),Q&&rn.current.delete(Q.surfaceKey),Vt.current=null,Dt(Q?.generation);return}W.error({errorCode:C,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:Se}),Q&&rn.current.delete(Q.surfaceKey),Vt.current=null,er({generation:Q?.generation,remount:!0,showRetry:!0,focus:!0}),en(ce,{code:"paypal_runtime_failed",popupBlocked:Be,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:ne,terminalReason:Se});return}I(Br(x)?"teardown":"pre_ready_callback",x)}}),Pt=ze.isEligible();if(se(`isEligible=${Pt}`),W.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!Pt){G(!1),I("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Mr=!0,An=ze,nr=()=>{if(!Wn||Tt||Qe()||Mn)return;Tt=!0,se(`container:dims ${In(xn)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(fr=new MutationObserver(x=>{if(!Qe()){for(let Q of x)if(Q.type==="childList")Q.addedNodes.forEach(C=>{if(!(C instanceof Element))return;let Be=C.tagName.toLowerCase(),vt=(C.getAttribute("title")??"").slice(0,40),Se=Be==="iframe"?` ${hr(C)}`:"";se(`child+ ${Be}${vt?` title="${vt}"`:""}${Se} dims=${In(C)}`)});else if(Q.type==="attributes"&&Q.target instanceof Element){let C=Q.target;if(C.tagName.toLowerCase()!=="iframe")continue;let Be=Q.attributeName;(Be==="src"||Be==="srcdoc")&&se(`attr~ iframe ${Be}=${Be==="srcdoc"?`[${(C.getAttribute("srcdoc")??"").length}ch]`:Gn(C.getAttribute("src"))} dims=${In(C)}`)}}}),fr.observe(xn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let ce=x=>{if(Qe()||Mn)return;let Q=xn.querySelectorAll("iframe"),C=typeof document<"u"&&"hasStorageAccess"in document;se(`watchdog:${x} container=${In(xn)} children=${xn.childElementCount} iframes=${Q.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${C} paypalNetRequests=${zn.value}`),Q.forEach((Be,vt)=>{let Se=(Be.getAttribute("title")??"").slice(0,40);se(` iframe[${vt}] ${In(Be)}${Se?` title="${Se}"`:""} ${hr(Be)}`);let vn=it(Be);vn&&se(` ${vn}`)}),tn.length===0&&se(" (no PayPal/zoid window errors captured)")};tr.push(setTimeout(()=>ce("3s"),3e3)),tr.push(setTimeout(()=>ce("8s"),8e3)),tr.push(setTimeout(()=>ce("15s"),15e3))},nr(),se("render:start");let ye=W.startTiming();Vn=setTimeout(()=>{Qe()||Mn||(se("watchdog:11s retryable render timeout"),I("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},Bd);let It=ze.render(xn);(async()=>{try{if(await It,se(`render:resolved inactive=${Qe()}`),yn(),Qe()){yr();return}Mn=!0,G(!0),ot(!1),Bt.current?.("ready"),W.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),W.performance({stage:"checkout_render",durationMs:W.elapsed(ye),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(ce){let x=ce instanceof Error?ce.message:"PayPal failed to render.";se(`render:rejected msg=${x.slice(0,120)}`),yn(),I(Br(x)?"teardown":"render_rejected",x)}})()}).catch(M=>{let te=M instanceof Error?M.message:"PayPal operation failed.";se(`provider:failed msg=${te.slice(0,120)}`);let K="script_rejected";_&&Br(te)?K="teardown":_&&Mr&&(K="render_rejected"),I(K,te)})},0);return()=>{Wt=!0,clearTimeout(q),Tr&&clearTimeout(Tr),yn(),Ht.current===ar&&(Ht.current=null),yr(),Je.current=null,dt.current=null}},[H,wt,s,y,l,f,ne,xt,e,Ye,ke,he,U,Le,se,Ft]);let Z=fe?qi("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:ut?"#fef2f2":"#f3f4f6",border:`1px solid ${ut?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${Xe} failed=${ut})`,Ae.length===0?`
2
2
  (waiting for first lifecycle event\u2026)`:`
3
3
  ${Ae.join(`
4
4
  `)}`]}):null;return ut&&!oe?fe?oo("div",{children:Z}):null:qi("div",{children:[Z,Oe&&oo(_o,{identity:Oe.identity,methodLabel:Oe.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:Re,onCancel:()=>Re(null)}),qi("div",{"aria-hidden":tt||Oe?!0:void 0,style:tt||Oe?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Ka},children:[!Xe&&!tt&&oo("div",{"data-testid":"flopay-direct-paypal-placeholder",style:{position:"absolute",inset:0,borderRadius:8,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite",pointerEvents:"none"}}),oo("div",{ref:me,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:Ka,display:"flex",opacity:Xe?1:0},"aria-busy":T||g},ke)]},ke),at&&oo("button",{ref:Ne,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:gn,style:Fd,children:"Try PayPal again"})]})}function Ha(e){return oo(Ll,{...e})}function zl(e){return oo(Ll,{...e})}import{jsx as Ul,jsxs as zd}from"react/jsx-runtime";function To({children:e,margin:t,icon:n=!0,styleOverride:r}){return zd("div",{role:"alert","data-testid":"flopay-error",style:{margin:t,padding:"0.625rem 0.875rem",background:"#FEF2F2",border:"1px solid #FECACA",borderRadius:"8px",color:"#991B1B",fontSize:"0.85rem",fontWeight:600,...n?{display:"flex",alignItems:"center",gap:"0.5rem"}:{},...r??{}},children:[n&&Ul("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:Ul("path",{d:"M12 9v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z",stroke:"#DC2626",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),e]})}import{foldIntoProducts as Ud,resolveSessionCurrency as qd}from"@flopay/shared";function Ao(){return typeof window<"u"&&typeof window.sessionStorage<"u"}var $i=":idempotency-key";function Ki(e,t){if(!Ao())return null;let n=window.sessionStorage.getItem(e);if(!n)return null;try{let r=JSON.parse(n);return!r||typeof r.sid!="string"||!r.sid||"canonicalIdentity"in r&&r.canonicalIdentity!==t?null:{..."canonicalIdentity"in r?{canonicalIdentity:t}:{},sid:r.sid,nonce:typeof r.nonce=="string"?r.nonce:void 0}}catch{return{sid:n}}}function Hi(e,t){if(!Ao())return null;try{let n=window.sessionStorage.getItem(e+$i);if(!n)return null;try{let r=JSON.parse(n);return typeof r=="string"?r?{idempotencyKey:r}:null:!r||typeof r.idempotencyKey!="string"||!r.idempotencyKey||"canonicalIdentity"in r&&r.canonicalIdentity!==t?null:{..."canonicalIdentity"in r?{canonicalIdentity:t}:{},idempotencyKey:r.idempotencyKey}}catch{return{idempotencyKey:n}}}catch{return null}}function Va(e,t){if(Ao())try{Ki(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function Wa(e,t){if(Va(e,t),!!Ao())try{Hi(e,t)&&window.sessionStorage.removeItem(e+$i)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function Ga(e,t,n,r){if(Ao())try{window.sessionStorage.setItem(e,JSON.stringify(r?{canonicalIdentity:t,sid:n,nonce:r}:{canonicalIdentity:t,sid:n}))}catch(o){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",o)}}function Ya(e,t,n){if(Ao())try{window.sessionStorage.setItem(e+$i,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function ji(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function jd(e){if(e==null)return e;let t=JSON.stringify(Object.entries(e).sort(([s],[l])=>s<l?-1:s>l?1:0)),n=1779033703,r=3144134277,o=1013904242,i=2773480762;for(let s=0;s<t.length;s++){let l=t.charCodeAt(s);n=r^Math.imul(n^l,597399067),r=o^Math.imul(r^l,2869860233),o=i^Math.imul(o^l,951274213),i=n^Math.imul(i^l,2716044179)}return n=Math.imul(o^n>>>18,597399067),r=Math.imul(i^r>>>22,2869860233),o=Math.imul(n^o>>>17,951274213),i=Math.imul(r^i>>>19,2716044179),n^=r^o^i,r^=n,o^=n,i^=n,[n,r,o,i].map(s=>(s>>>0).toString(16).padStart(8,"0")).join("")}function Mo(e,t=!1){let n=e?.account?.email?.trim().toLowerCase()??"",r={c:e?.clientId,cur:e?.currency??"",captureMethod:e?.captureMethod??"",a:{e:n,u:n?"":e?.account?.userId??"",country:e?.account?.country??""},successUrl:e?.successUrl,cancelUrl:e?.cancelUrl,p:e?.products?.map(o=>ji(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>ji(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>ji(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,checkoutMetadata:jd(e?.checkoutMetadata),...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function ql(e,t=!1){let n=Mo(e,t),r=0;for(let o=0;o<n.length;o++)r=(r<<5)-r+n.charCodeAt(o)|0;return`flopay_session_${Math.abs(r).toString(36)}`}function jl(e,t){if(!e?.customer||!e.products||t.checkoutMetadata!==void 0)return!1;let n=t.account.email?.trim().toLowerCase()??"",r=e.customer.email?.trim().toLowerCase()??"";if((n?r!==n:e.customer.id!==t.account.userId)||(t.account.country??"").trim().toUpperCase()!==(e.customer.country??"").trim().toUpperCase()||e.successUrl!==t.successUrl||e.cancelUrl!==t.cancelUrl||(e.captureMethod??"automatic")!==(t.captureMethod??"automatic"))return!1;let o=qd(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let i=(t.products??Ud(t.items,t.subscriptions)).map(u=>({type:u.type,code:u.code??u.providerItemId??u.providerPlanId??"",quantity:u.quantity??1,totalAmount:u.totalAmount,overrideAmount:u.overrideAmount??null,currency:(u.currency??o).toUpperCase()})).sort((u,b)=>`${u.code}:${u.type??""}`.localeCompare(`${b.code}:${b.type??""}`)),s=e.products.map(u=>({type:u.type,code:u.code??"",quantity:u.quantity??1,totalAmount:u.totalAmount,overrideAmount:u.overrideAmount??null,currency:(u.currency??e.currency).toUpperCase()})).sort((u,b)=>`${u.code}:${u.type??""}`.localeCompare(`${b.code}:${b.type??""}`));if(i.length!==s.length)return!1;for(let[u,b]of i.entries()){let P=s[u];if(P===void 0||b.code!==P.code||b.type!==void 0&&b.type!==P.type||b.quantity!==P.quantity||b.totalAmount!==P.totalAmount||b.overrideAmount!==P.overrideAmount||b.currency!==P.currency)return!1}let l=[...t.couponCodes??[]].sort(),y=[...e.coupons??[]].sort();return l.length===y.length&&l.every((u,b)=>u===y[b])}import{resolveBillingApiUrl as $d}from"@flopay/shared";import{useEffect as Yr,useMemo as Kd,useRef as $l,useState as Kl}from"react";import{jsx as Hd}from"react/jsx-runtime";function Ja({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[i,s]=Kl(e instanceof Promise?null:e),[l,y]=Kl(t instanceof Promise||!t?null:t),u=$l(null),b=$l(null),P=Eo(r);Yr(()=>{P({class:"lifecycle",name:"checkout.mount"})},[P]),Yr(()=>{i&&P({class:"lifecycle",name:"sdk.initialize.ready"})},[P,i]),Yr(()=>{if(i)return cn(i)?.subscribe?.(P)},[P,i]),Yr(()=>{if(!(!l||l===i))return cn(l)?.subscribe?.(P)},[P,i,l]),Yr(()=>{if(!i)return;let R=cn(i);return u.current=R?.beginCheckout()??R?.now()??0,R?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{R?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),Yr(()=>{let R=!1;return e instanceof Promise?e.then(O=>{R||s(O)},()=>{R||P({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):s(e),()=>{R=!0}},[P,e]),Yr(()=>{let R=!1;if(!t){y(null);return}return t instanceof Promise?t.then(O=>{R||y(O)},()=>{R||P({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):y(t),()=>{R=!0}},[P,t]),Yr(()=>{if(!i||b.current===i)return;b.current=i;let R=cn(i);R?.log({name:"checkout.rendered",stage:"checkout_render"}),P({class:"lifecycle",name:"checkout.rendered"}),R?.performance({stage:"checkout_render",durationMs:R.elapsed(u.current??0),durationMode:"machine"})},[P,i]);let D=$d(n?.billingApiUrl),N=Kd(()=>({flopay:i,paypalFlopay:l,billingApiUrl:D,emitInstrument:P}),[i,l,D,P]);return Hd(Xn.Provider,{value:N,children:o})}var Xa="flopay_recent_completion_";function xo(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(Xa+e,JSON.stringify(t))}catch{}}function Vi(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(Xa+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(Xa+e),!1):!0}catch{return!1}}async function Za(e,t){e.current?.abort();let n=new AbortController;e.current=n;try{return await t(n.signal)}finally{e.current===n&&(e.current=null)}}import{loadFloPay as Hl,PaymentAPI as ei}from"@flopay/js";import{classifyPaymentRejection as Vd,FloPayError as bt,isAuthorizationOnlySession as Wd,isSetupIntentClientSecret as Gd,normalizeCheckoutFailureOutcome as Vl,THREE_DS_CHALLENGE_WINDOW_MS as Gl}from"@flopay/shared";var ya="card",Yd=1e3;async function Jd(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:i,error:s}=await e.retrieveSetupIntent(t);return{error:s,intent:i??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:r,error:o}=await e.retrievePaymentIntent(t);return{error:o,intent:r??null}}async function Xd(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:s,error:l}=await e.confirmCardSetup(t,n);return{error:l,intent:s??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:o,error:i}=await e.confirmCardPayment(t,n);return{error:i,intent:o??null}}function Jr(e){return new bt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function Wi(){return new bt("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function Yi(e,t){return Object.assign(e,{checkoutMethod:t})}function Nr(e,t){let n=e instanceof bt?e:new bt(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(n,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function ma(e,t){try{return await e()}catch(n){throw Nr(n,t)}}function Yl(e){return!e?.type||!e.threeDSecureToken||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function Zd(e){return e.status==="succeeded"||e.status==="authorized"||e.status==="declined"}async function Ji(e){if(typeof document>"u"||typeof window>"u")throw new bt("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw Jr();let t=1e3,n=15e3,r=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,o=async()=>{let P=new AbortController,D=()=>P.abort();e.signal?.aborted?P.abort():e.signal?.addEventListener("abort",D);let N=window.setTimeout(()=>P.abort(),n);try{let R=await fetch(r,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:P.signal});if(!R.ok)return{status:"unknown"};let O=await R.json().catch(()=>null);return Qd(O)}catch{return{status:"unknown"}}finally{window.clearTimeout(N),e.signal?.removeEventListener("abort",D)}},i,s=()=>e.pollCompletionEndpoint!==!1?o():(i??(i=o()),i),l=document.activeElement instanceof HTMLElement?document.activeElement:null,y=document.createElement("div");y.setAttribute("data-flopay-auto-3ds-overlay","1"),y.setAttribute("role","dialog"),y.setAttribute("aria-modal","true"),y.setAttribute("aria-label","Card authentication"),y.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 u=document.createElement("iframe");u.setAttribute("title","Card authentication"),u.setAttribute("allow","payment"),u.tabIndex=0,u.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";");let b=null;try{b=new URL(e.billingApiUrl,window.location.href).origin}catch{b=null}try{let P=await new Promise((D,N)=>{let R=!1,O=0,$=0,g=0,v=!1,X=()=>{window.clearTimeout(O),window.clearInterval($),window.clearTimeout(g),window.removeEventListener("message",De),u.removeEventListener("load",pe),e.signal?.removeEventListener("abort",V)},H=async()=>{if(!(R||v)){v=!0;try{let Ye=await s();if(R||!Zd(Ye))return;R=!0,X(),D(Ye)}finally{v=!1}}},pe=()=>{e.pollCompletionEndpoint!==!1&&(window.clearTimeout(g),g=window.setTimeout(()=>{H()},250))},V=()=>{R||(R=!0,X(),N(Jr()))},De=Ye=>{if(Ye.source!==u.contentWindow||b&&Ye.origin!==b)return;let be=Ye.data;!be||typeof be!="object"||be.source!=="flopay-vault-3ds-return"||R||(R=!0,X(),D(null))};O=window.setTimeout(()=>{R||(R=!0,X(),N(Wi()))},Gl),e.pollCompletionEndpoint!==!1&&($=window.setInterval(()=>{H()},t)),u.addEventListener("load",pe),window.addEventListener("message",De),e.signal?.addEventListener("abort",V),u.src=e.nextActionRedirectUrl,y.appendChild(u),document.body.appendChild(y),u.focus(),e.signal?.aborted&&V()});return P||await s()}finally{y.parentNode?.removeChild(y),l?.isConnected&&l.focus()}}async function Bo(e,t){let{billingApiUrl:n,sessionId:r,signal:o}=t,i=t.nonce??t.session.clientSecret,s=new ei(n,{telemetry:!1}),l=`${n.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(r)}/status`,y=new AbortController,u=new AbortController,b=()=>{y.abort(o.reason),u.abort(o.reason)};o.aborted?b():o.addEventListener("abort",b,{once:!0});let P=Ji({billingApiUrl:n,sessionId:r,nonce:i,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:y.signal,pollCompletionEndpoint:!1}),D=s.waitForCheckoutSessionCompletion(r,{initialDelayMs:Yd,nonce:i,statusUrl:l,continueAfterActionRequired:!0,timeoutMs:Gl+15e3,signal:u.signal}),N;try{let O=await Promise.race([P,D]);if("data"in O)N=O;else{if(O.status==="declined")throw Ir({type:O.declineReason??"authorization_declined",gatewayErrorCode:O.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"});if(O.status==="timeout")throw Wi();N=await D}}catch(O){if(o.aborted||O instanceof Error&&O.name==="AbortError")throw Jr(O);if(!(O instanceof bt)||O.code!=="three_ds_timeout"&&O.code!=="checkout_processing_timeout")throw O;try{N=await s.waitForCheckoutSessionCompletion(r,{initialDelayMs:0,nonce:i,statusUrl:l,timeoutMs:5e3,signal:o})}catch(g){if(o.aborted)throw Jr(g);if(!(g instanceof bt)||g.code!=="checkout_processing_timeout")throw g}let $=N&&Hr(N,t.session);if(!Dr($)&&$?.status!=="expired"){if(t.telemetry){let g=new ei(n);try{g.reportThreeDsAbandoned(r)}finally{g.destroy()}}throw Wi()}}finally{o.removeEventListener("abort",b),y.abort(),u.abort()}let R=N&&Hr(N,t.session);if(!Dr(R))throw Io(R);return{...Fr(R,r),checkoutMethod:"card"}}function Qd(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",n=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":case"authorized":case"pending":case"timeout":return{status:t,providerIntentId:n};case"declined":return{status:"declined",providerIntentId:n,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:n,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function Ir(e,t="Payment failed. Please try again.",n){let r=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),o=e?.message??t,i=Kr(o)??o,s=Yi(new bt(i,"api_error",{code:e?.code??Vl(e?.outcome)??Vl(e?.type)??e?.gatewayErrorCode}),r);return e?.orderId&&(s.orderId=e.orderId),s}function Gi(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Qa(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function Jl(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||Qa(o)))return o;let r=e?.data;if(r&&typeof r=="object"){let o=r,i=[o.threeDSecureToken,o.clientSecret,o.stripeClientSecret,o.id];for(let l of i)if(typeof l=="string"&&l.length>0&&(!t?.requirePaymentIntentClientSecret||Qa(l)))return l;let s=o.gateways;if(s&&typeof s=="object"){let l=s.stripe;if(l&&typeof l=="object"){let y=l,u=[y.stripeClientSecret,y.clientSecret];for(let b of u)if(typeof b=="string"&&b.length>0&&(!t?.requirePaymentIntentClientSecret||Qa(b)))return b}}}}async function eu({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=Jl(r,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let l=(await new ei(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Qa(l))return{type:"3ds_required",threeDSecureToken:l}}catch{}return null}async function Fo({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:i,telemetry:s}){let l=e.replace(/\/+$/,""),y=t??n.id,u=r??n.clientSecret,b=n.customer?.id??n.accountData?.userId??"",P=n.customer?.email??n.accountData?.email??"",D=n.customer?.firstName??n.accountData?.firstName??"",N=n.customer?.lastName??n.accountData?.lastName??"",R=n.customer?.country??n.accountData?.country??void 0,O=n.customer?.zip??n.accountData?.zip??void 0,g=await new ei(l,s===!1?{telemetry:!1}:void 0).processPayment(b,{sessionId:y,nonce:u,paymentMethodCategory:"saved",tokenizedData:o,accountData:{userId:b,email:P,firstName:D,lastName:N,country:R,zip:O},returnUrl:i??Gi(n)});if(g.ok){let H=typeof g.json=="function"?await g.json().catch(()=>null):null;if(Wd(n)||H?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof H?.paymentId=="string"?H.paymentId:n.paymentId,sessionId:typeof H?.sessionId=="string"?H.sessionId:y,authorizationExpiresAt:typeof H?.authorizationExpiresAt=="string"?H.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:sa(o),checkoutMethod:Wl(o,n)}};let pe=o?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...pe?{paymentIntentId:pe}:{},paymentMethodId:sa(o),checkoutMethod:Wl(o,n)}}}let v;try{v=await g.json()}catch(H){throw new bt("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:g.status,cause:H})}if(v?.type==="3ds_required"&&typeof v.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:v.nextActionRedirectUrl};if(v?.type==="paypal_redirect_required"||v?.type==="3ds_required"){let H=Jl(v);if(!H)throw new bt("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:g.status});return{type:v.type,threeDSecureToken:H,paymentMethodId:v.paymentMethodId}}if(v?.gatewayErrorCode==="authentication_required"){let H=await eu({billingApiUrl:l,sessionId:y,nonce:u,responseJson:v});if(H)return H;throw Yi(new bt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let X=new bt(v?.message??"Payment failed. Please try again.","api_error",{code:v?.code??v?.gatewayErrorCode,declineCode:v?.declineCode??v?.gatewayDeclineReason,statusCode:g.status});throw Object.assign(X,{telemetryOutcome:Vd(g.status,v)})}async function ti(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:i,session:s,returnUrl:l,telemetry:y,signal:u}){let b=t?.getRawProvider();if(!b)throw Nr(new bt("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw Yi(new bt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let P=Gd(e.threeDSecureToken),D=null,N=e.paymentMethodId,R=await ma(()=>Jd(b,e.threeDSecureToken,P),"card");if(R){if(R.error)throw Nr(new bt(R.error.message??`Failed to retrieve 3DS ${P?"setup":"payment"} status.`,"api_error",{code:R.error.code}),"card");let $=R.intent;!N&&$?.payment_method&&(typeof $.payment_method=="string"?N=$.payment_method:"id"in $.payment_method&&(N=$.payment_method.id??void 0))}let O=N?await ma(()=>Xd(b,e.threeDSecureToken,{payment_method:N,return_url:l??Gi(s)??window.location.href},P),"card"):null;if(O){if(O.error)throw Nr(new bt(O.error.message??"3DS authentication failed.","api_error",{code:O.error.code}),"card");D=O.intent}else{let $=await ma(()=>b.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if($.error)throw Nr(new bt($.error.message??"3DS authentication failed.","api_error",{code:$.error.code}),"card");D=(P?$.setupIntent:$.paymentIntent)??null}if(D&&(D.status==="requires_capture"||D.status==="succeeded"||D.status==="processing")){let $=await Fo({billingApiUrl:o,sessionId:i,session:s,telemetry:y,tokenizedData:{id:D.id,type:"card",threeDSecureActionResultTokenId:D.id},returnUrl:l});return $.type==="success"?{...$.result,paymentIntentId:$.result.paymentIntentId??D.id,paymentMethodId:$.result.paymentMethodId??N}:$.type==="next_action_required"?Bo($,{billingApiUrl:o,sessionId:i??s.id,session:s,signal:u}):ti($,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:i,session:s,returnUrl:l,telemetry:y,signal:u})}throw Nr(new bt("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let P=(n??t)?.getRawProvider();if(!P)throw Nr(new bt("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:N}=await ma(()=>P.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(N)throw Nr(new bt(N.message??"PayPal authorization failed.","api_error",{code:N.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:D}=await ma(()=>P.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:l??Gi(s)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(D)throw Nr(new bt(D.message??"PayPal authorization failed.","api_error",{code:D.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new bt("Unsupported payment redirect state.","api_error")}function fa(e){if(e instanceof bt){let r=Kr(e.message);return r&&r!==e.message?Object.assign(new bt(r,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode,sessionId:e.sessionId}),{checkoutMethod:e.checkoutMethod,orderId:e.orderId,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=Kr(t)??t;return new bt(n,"api_error")}function Xi(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey,r=!!e.data.session?.vault?.html||jr(e.data.session);if(!t&&!n&&!r)throw new bt("Session advertises no supported gateways or hosted vault (expected `gateways.stripe`, `gateways.paypal`, or vault markup).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}function Wl(e,t){return e?e.isPaypal?"paypal":"card":t&&jr(t)?"card":void 0}async function Zi({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:r,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let i=t&&t!==e?t:void 0,[s,l]=await Promise.all([Hl(e,{billingApiUrl:n,locale:r,telemetry:o}),i?Hl(i,{billingApiUrl:n,locale:r,telemetry:o}).catch(u=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",u),null)):Promise.resolve(null)]);if(!s)throw new bt("The payment provider did not initialize.","authentication_error");let y=null;return i?y=l:t&&(y=s),{flopay:s,paypalFlopay:y}}import{PaymentAPI as No,PciVaultCardCapture as tu,toStripeAppearance as nu}from"@flopay/js";import{COUNTRY_OPTIONS as ru,classifyPaymentRejection as ou,FloPayError as pr,filterStripeMethodsByCountry as au,getPostalCodeExample as iu,getPostalCodeLabel as ss,getStateFromPostalCode as Zl,getStateLabel as Qi,getStateOptions as su,getStripeMethodDisplayName as so,hasVendoredStripeMethodLogo as lu,isAuthorizationOnlySession as es,isAVSFieldVisible as rt,isPostalCodeSupported as cu,isSetupIntentClientSecret as ts,isValidEmail as fn,isValidPostalCode as du,needsStripeMethodExplicitConfirm as Ql,normalizeCheckoutFailureOutcome as uu,partitionStripeMethods as pu,randomUuidV4 as mu,resolveAVSConfig as yu,resolveButtonsLayoutTheme as fu,resolveStripeMethodBrandVariant as gu,resolveTheme as hu,stripeExpressMethodToOptionKey as ec}from"@flopay/shared";import{ExpressCheckoutElement as yc,PaymentElement as Pu,Elements as ao,useElements as us,useStripe as ps}from"@stripe/react-stripe-js";import vu,{useCallback as Ge,useContext as Oo,useEffect as ht,useMemo as gt,useRef as ie,useState as de}from"react";function Do(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function ni(e,t){if(e)return{error:n=>e.error(Do(t,n)),log:n=>e.log(Do(t,n)),performance:n=>e.performance(Do(t,n)),terminal:n=>e.terminal(Do(t,n)),now:()=>e.now(),elapsed:n=>e.elapsed(n),setCheckoutContext:n=>e.setCheckoutContext(n),beginCheckout:n=>e.beginCheckout(n),disable:()=>e.disable(),subscribe:n=>e.subscribe(n),flush:()=>e.flush(),destroy:()=>e.destroy()}}var Xl={alipay:"https://cdn.flopay.com/sdk-logos/v1/alipay.svg",bancontact:"https://cdn.flopay.com/sdk-logos/v1/bancontact.svg",blik:"https://cdn.flopay.com/sdk-logos/v1/blik.svg",eps:"https://cdn.flopay.com/sdk-logos/v1/eps.svg",giropay:"https://cdn.flopay.com/sdk-logos/v1/giropay.svg",ideal:"https://cdn.flopay.com/sdk-logos/v1/ideal.svg",klarna:"https://cdn.flopay.com/sdk-logos/v1/klarna.svg",p24:"https://cdn.flopay.com/sdk-logos/v1/p24.svg",sepa_debit:"https://cdn.flopay.com/sdk-logos/v1/sepa_debit.svg",wechat_pay:"https://cdn.flopay.com/sdk-logos/v1/wechat_pay.svg"};import{Fragment as io,jsx as d,jsxs as Ue}from"react/jsx-runtime";var Rr="flopay_stripe_resume",tc="flopay_wallet_resume",fc="fw1",bu="fw2",gc=300*1e3,Cu=900,Su=25e3,wu=25e3,ku=1e4,hc=["payment_intent","payment_intent_client_secret","redirect_status"],ur={provider:"paypal",paymentMethodCategory:"paypal"},ri={},ns={};function jt(e,t){if(typeof window>"u")return!1;try{return t===void 0?window.localStorage.removeItem(e):window.localStorage.setItem(e,JSON.stringify(t)),!0}catch{return!1}}function ms(e){return`${bu}:${e}`}function oi(e){return jt(ms(e))}function ai(e,t){if(typeof window>"u")return null;let n=ms(e);try{let r=localStorage.getItem(n);if(!r)return null;let o=JSON.parse(r);return typeof o.createdAt!="number"||Date.now()-o.createdAt<0||Date.now()-o.createdAt>gc||o.sessionId!==e||o.nonce!==t||typeof o.clientSecret!="string"||typeof o.providerObjectId!="string"||typeof o.paymentMethodType!="string"?(oi(e),null):o}catch{return oi(e),null}}function Iu(e){return jt(ms(e.sessionId),e)}function nc(e,t,n){let r=ai(e,t);return!r||r.clientSecret!==n?!1:oi(e)}function rs(e,t,n){if(typeof window>"u")return;ai(e,t)?.clientSecret===n&&oi(e)}function Ru(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function os(e,t,n){if(!e||typeof e.id!="string"||t&&e.id!==t)return{kind:"ambiguous"};if(e.status==="canceled"||e.status==="requires_payment_method")return{kind:"terminal"};let r=n?e.status==="succeeded":ia(e.status),o=Ru(e);return!r||!o?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:o}}async function rc(e,t,n){let r=null;try{return await Promise.race([El(e,t),new Promise(o=>{r=window.setTimeout(()=>{r!==null&&n?.delete(r),o(null)},ku),n?.add(r)})])}finally{r!==null&&(window.clearTimeout(r),n?.delete(r))}}function _u(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function Pc(e){return e instanceof pr&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function ii(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new No(e,{telemetry:!1}).createSessionIntent(...n)}catch(o){throw Pc(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var ha="flopay_paypal_resume",ga=new Map;function vc(e){if(!e||typeof window>"u")return null;try{let t=window.localStorage.getItem(ha);if(!t)return null;let n=JSON.parse(t);return n?.clientSecret===e?n:null}catch{return null}}function Eu(){if(typeof window>"u")return!1;let[e,t]=ys();return e?vc(t)!==null:!1}function ys(){let e=new URLSearchParams(window.location.search);return hc.map(t=>e.get(t))}function fs(){let e=new URL(window.location.href);for(let t of hc)e.searchParams.delete(t);return e.toString()}function Tu(){jt(ha),window.history.replaceState({},"",fs())}var Au=250,oc="Just a moment \u2014 we are finalizing your order. Please press pay again.",Mu="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function gs(e,t,n,r){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk",...r?{terminalReason:r}:{}})}async function si({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new No(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function xu(e){return e instanceof pr&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function as(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function bc({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=t?.trim(),i=no(n),s=i.firstName?i:no(r?.name);return Dn({email:fn(o)?o:r?.email?.trim(),firstName:s.firstName,lastName:s.lastName})}async function Bu({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:i}){let s=bc({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||r});return fn(s.email)?s:i(o,s)}var Fu=`
@@ -1,6 +1,6 @@
1
- "use strict";var Mt=Object.create;var de=Object.defineProperty;var xt=Object.getOwnPropertyDescriptor;var At=Object.getOwnPropertyNames;var Tt=Object.getPrototypeOf,Bt=Object.prototype.hasOwnProperty;var pe=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ee=(e,t)=>{for(var r in t)de(e,r,{get:t[r],enumerable:!0})},Ne=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of At(t))!Bt.call(e,o)&&o!==r&&de(e,o,{get:()=>t[o],enumerable:!(n=xt(t,o))||n.enumerable});return e};var Lt=(e,t,r)=>(r=e!=null?Mt(Tt(e)):{},Ne(t||!e||!e.__esModule?de(r,"default",{value:e,enumerable:!0}):r,e)),Ot=e=>Ne(de({},"__esModule",{value:!0}),e);function he(e,t,r){let n=`We couldn't open ${e}. Try again or choose another payment method.`;return t?r?`${n} Open this page in your system browser, then try again.`:`${n} Allow pop-ups for this site, then try again.`:n}function dt(e){if(e instanceof Error)return e.message;if(typeof e=="object"&&e!==null){let t=e.message;return typeof t=="string"?t:void 0}return typeof e=="string"?e:void 0}function se(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function pt(e){if(typeof e!="object"||e===null)return;let t=e;return se(t.code)??se(t.type)??se(t.name)}function fr(e){if(!(typeof e!="object"||e===null))return se(e.decline_code)}function Fe(e){return typeof e!="object"||e===null?!1:se(e.type)?.toLowerCase()==="card_error"||fr(e)!==void 0}function mr(e){let t=dt(e)?.toLowerCase()??"",r=pt(e)?.toLowerCase()??"";return dr.has(r)?!0:/(?:popup|pop-up).{0,40}(?:block|denied|prevent)/i.test(t)||/(?:block|denied|prevent).{0,40}(?:popup|pop-up)/i.test(t)}function yr(e){if(pt(e)?.toLowerCase()==="paypal_init_timeout")return!0;let r=dt(e)??"";return r.includes("No ack for postMessage init()")&&pr.some(n=>r.includes(n))&&r.includes("10000ms")}function Se(e,t){if(Fe(e))return{errorCode:"PROVIDER_RUNTIME_FAILED",popupBlocked:!1,providerDeclined:!0,terminalReason:"provider_declined"};let n=mr(e)||t.inAppBrowser&&!t.handoffObserved&&yr(e);return{errorCode:n?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",popupBlocked:n,providerDeclined:!1,terminalReason:n?"popup_blocked":"provider_error"}}var dr,pr,Me=pe(()=>{"use strict";dr=new Set(["err_blocked_by_client","notallowederror","popup_blocked","popupblocked"]),pr=["https://www.paypal.com","https://www.sandbox.paypal.com"]});function be(e){let t=e??(typeof navigator>"u"?"":navigator.userAgent),r=n=>({inAppBrowser:n!=="none",appFamily:n,popupCapability:"unknown"});return t?/FBAN|FBAV|FB_IAB|FBIOS/i.test(t)?r("facebook"):/Instagram/i.test(t)?r("instagram"):/musical_ly|BytedanceWebview|TikTok/i.test(t)?r("tiktok"):/Twitter|Snapchat|Pinterest|LinkedInApp|Line\/|MicroMessenger|GSA\//i.test(t)?r("other_in_app"):/Android.*;\s?wv\)/.test(t)||/(iPhone|iPad|iPod).*AppleWebKit(?!.*Safari)/.test(t)?r("generic_webview"):r("none"):r("none")}function ft(e,t,r=e.popupCapability){return e.inAppBrowser||r==="blocked"||t==="prefer_redirect"?"redirect":"popup"}var xe=pe(()=>{"use strict"});var ht={};Ee(ht,{StripeSetupMethod:()=>vr});function gr(e){let t=Ae.get(e);if(t)return t;let r=(0,yt.loadStripe)(e).catch(n=>{throw Ae.delete(e),n});return Ae.set(e,r),r}function Sr(e){return e?{theme:hr[e.theme??"default"]??"stripe",...e.variables?{variables:e.variables}:{},...e.rules?{rules:e.rules}:{}}:void 0}function br(e){return Fe(e)||e.code==="setup_intent_authentication_failure"||e.code==="payment_method_provider_decline"}function Pr(e){return e==="paypal"?"PayPal":(0,Pe.getStripeMethodDisplayName)(e)}function Cr(){return typeof window>"u"?"":window.location.href}function vr(e){let{publishableKey:t,method:r,currency:n,appearance:o}=e,[a]=(0,V.useState)(()=>gr(t)),i=(0,V.useMemo)(()=>{let l=Sr(o);return{mode:"setup",currency:n.toLowerCase(),paymentMethodTypes:gt[r]?.types??[r],...l?{appearance:l}:{}}},[o,n,r]);return(0,z.jsx)(U.Elements,{stripe:a,options:i,children:(0,z.jsx)(wr,{...e})})}function wr({method:e,category:t,sessionId:r,nonce:n,billingApiUrl:o,telemetry:a,onSubmitting:i,onConfirmed:l,onDeclined:c,onFailed:p,onValidation:d}){let y=(0,U.useStripe)(),h=(0,U.useElements)(),[A,w]=(0,V.useState)(!1),F=(0,V.useRef)(!1),[m]=(0,V.useState)(()=>be()),[T,D]=(0,V.useState)(!1),R=(0,V.useCallback)((f,v)=>{if(Se(f,{inAppBrowser:m.inAppBrowser,handoffObserved:!1}).popupBlocked){D(!0),p(new Error(he(Pr(e),!0,m.inAppBrowser)),{code:"popup_blocked",retryable:!0});return}p(v.message===void 0?f:new Error(v.message),{code:v.code,retryable:!0})},[m.inAppBrowser,e,p]),S=(0,V.useCallback)(async()=>{if(!(!y||!h||F.current)){F.current=!0,w(!0);try{let f=await h.submit();if(f.error){d(f.error.message??null);return}i();let v=await new mt.PaymentAPI(o,{telemetry:a}).createSessionIntent(r,n,{provider:"stripe",paymentMethodCategory:t,paymentMethodType:e,paymentMethodId:null,intentKind:"setup"});if(v.provider!=="stripe"||v.intentKind!=="setup")throw new Pe.FloPayError("The billing API returned a non-setup intent.","api_error",{code:"InvalidSessionIntentResponse"});let P=await y.confirmSetup({elements:h,clientSecret:v.clientSecret,confirmParams:{return_url:Cr()},redirect:"if_required"});if(P.error){br(P.error)?c({...P.error.decline_code||P.error.code?{reason:P.error.decline_code??P.error.code}:{},...P.error.message?{message:P.error.message}:{}}):R(P.error,{code:"payment_method_setup_provider_failed",message:P.error.message??"The payment method could not be saved."});return}l()}catch(f){R(f,{code:"payment_method_setup_failed"})}finally{F.current=!1,w(!1)}}},[o,t,h,e,n,l,c,i,d,R,r,y,a]),L=gt[e]?.wallet,O=L==="paypal"&&ft(m,"auto",T?"blocked":m.popupCapability)==="redirect";if(t==="wallet"&&L&&!O){let f={applePay:"never",googlePay:"never",link:"never",paypal:"never",amazonPay:"never"};return f[L]="auto",(0,z.jsx)(U.ExpressCheckoutElement,{options:{paymentMethods:f},onConfirm:()=>{S()}})}return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(U.PaymentElement,{onChange:f=>{f.complete&&d(null)}}),(0,z.jsx)("button",{type:"button","data-flopay-payment-method-save":e,disabled:!y||!h||A,onClick:()=>{S()},children:"Save payment method"})]})}var mt,Pe,U,yt,V,z,gt,Ae,hr,St=pe(()=>{"use strict";mt=require("@flopay/js/card-setup"),Pe=require("@flopay/shared"),U=require("@stripe/react-stripe-js"),yt=require("@stripe/stripe-js"),V=require("react");Me();xe();z=require("react/jsx-runtime"),gt={apple_pay:{types:["card"],wallet:"applePay"},google_pay:{types:["card"],wallet:"googlePay"},link:{types:["link"],wallet:"link"},paypal:{types:["paypal"],wallet:"paypal"},amazon_pay:{types:["amazon_pay"],wallet:"amazonPay"}},Ae=new Map;hr={night:"night",flat:"flat"}});var Ct={};Ee(Ct,{PayPalSetupMethod:()=>Er});function Er({clientId:e,environment:t,currency:r,sessionId:n,nonce:o,billingApiUrl:a,telemetry:i,customer:{userId:l,email:c},onSubmitting:p,onConfirmed:d,onFailed:y,onAbandoned:h}){let A=(0,K.useRef)(null),w=(0,K.useRef)({onSubmitting:p,onConfirmed:d,onFailed:y,onAbandoned:h});w.current={onSubmitting:p,onConfirmed:d,onFailed:y,onAbandoned:h};let[F]=(0,K.useState)(()=>be().inAppBrowser);return(0,K.useEffect)(()=>{let m=!0,T,D=new bt.PaymentAPI(a,{telemetry:i}),R={userId:l,email:c};return(async()=>{try{let S=await(0,Pt.loadScript)({clientId:e,currency:r.toUpperCase(),components:"buttons",...t==="sandbox"||t==="production"?{environment:t}:{}}),L=A.current;if(!m||!L)return;if(!S?.Buttons)throw new H.FloPayError("PayPal could not be loaded.","api_error",{code:"paypal_unavailable"});let O=S.Buttons({createVaultSetupToken:async()=>{w.current.onSubmitting();let f=await D.createSessionIntent(n,o,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:H.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:"setup"});if(f.provider!=="paypal"||f.providerObjectType!=="setup_token")throw new H.FloPayError("The billing API did not return a PayPal setup token.","api_error",{code:"InvalidSessionIntentResponse"});return f.providerObjectId},onApprove:async f=>{let v=f.vaultSetupToken;if(!v)throw new H.FloPayError("PayPal approved without a setup token.","api_error",{code:"paypal_setup_token_missing"});let P=await D.processPayment(R.userId,{sessionId:n,nonce:o,paymentMethodCategory:"paypal",tokenizedData:{id:v,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:H.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE},accountData:R});if(!P.ok)throw new H.FloPayError("PayPal could not be saved.","api_error",{code:"paypal_setup_failed",statusCode:P.status});m&&w.current.onConfirmed()},onCancel:()=>{m&&w.current.onAbandoned()},onError:f=>{if(!m)return;let{popupBlocked:v}=Se(f,{inAppBrowser:F,handoffObserved:!1});w.current.onFailed(v?new Error(he("PayPal",!0,F)):f,{code:v?"popup_blocked":"paypal_setup_failed",retryable:!0})}});T=()=>O.close(),await O.render(L)}catch(S){if(!m)return;w.current.onFailed(S,{code:"paypal_unavailable",retryable:!0})}})(),()=>{m=!1,T?.().catch(()=>{}),D.destroy()}},[a,e,r,c,t,F,o,n,i,l]),(0,vt.jsx)("div",{ref:A,"data-flopay-paypal-setup":""})}var bt,H,Pt,K,vt,wt=pe(()=>{"use strict";bt=require("@flopay/js/card-setup"),H=require("@flopay/shared"),Pt=require("@paypal/paypal-js"),K=require("react");Me();xe();vt=require("react/jsx-runtime")});var Rr={};Ee(Rr,{FloPayCardSetupError:()=>oe,FloPayPaymentMethodSetup:()=>Et});module.exports=Ot(Rr);var rt=require("@flopay/js/card-setup"),Q=require("@flopay/shared"),ye=require("react");function We(e,t){if(!e)return t;let r=t??{},n=Object.keys(r),o=n.some(i=>i.startsWith("background")),a={};for(let[i,l]of Object.entries(e))i in r||o&&i.startsWith("background")||(a[i]=l);for(let i of n)a[i]=r[i];return a}var It=new Set(["animationIterationCount","aspectRatio","borderImageOutset","borderImageSlice","borderImageWidth","boxFlex","boxFlexGroup","boxOrdinalGroup","columnCount","columns","flex","flexGrow","flexPositive","flexShrink","flexNegative","flexOrder","gridArea","gridRow","gridRowEnd","gridRowSpan","gridRowStart","gridColumn","gridColumnEnd","gridColumnSpan","gridColumnStart","fontWeight","lineClamp","lineHeight","opacity","order","orphans","scale","tabSize","widows","zIndex","zoom","fillOpacity","floodOpacity","stopOpacity","strokeDasharray","strokeDashoffset","strokeMiterlimit","strokeOpacity","strokeWidth"]);function Vt(e){let t=e.replace(/^(Webkit|Moz|ms)(?=[A-Z])/,"");return It.has(t.charAt(0).toLowerCase()+t.slice(1))}function Dt(e,t){return typeof t=="number"&&t!==0&&!Vt(e)?`${t}px`:String(t).trim()}function ze(e,t){if(e.style.cssText="",!!t){for(let[r,n]of Object.entries(t))if(!(n==null||n==="")){if(r.startsWith("--")){e.style.setProperty(r,String(n));continue}e.style[r]=Dt(r,n)}}}var Ue={light:{success:"#166534",error:"#991B1B"},dark:{success:"#4ADE80",error:"#FCA5A5"}};function Ge(e){let t=e.appearance.variables??{},r=e.buttonsLayout.cardFormContainer??{},n=e.appearance.theme==="night",o=n?Ue.dark:Ue.light,a=t.colorText??(n?"#F1F5F9":"#262833"),i=e.appearance.rules?.[".Label"];return{panel:{...r.background===void 0?{}:{background:r.background},...r.backgroundColor===void 0?{}:{backgroundColor:r.backgroundColor},...r.border===void 0?{}:{border:r.border},...r.borderRadius===void 0?{}:{borderRadius:r.borderRadius},...r.boxShadow===void 0?{}:{boxShadow:r.boxShadow},color:a,...t.fontFamily?{fontFamily:t.fontFamily}:{}},spinnerTrackColor:e.buttonsLayout.cardInputBorder??(n?"#374151":"#e5e7eb"),spinnerAccentColor:t.colorPrimary??"#4A49FF",labelColors:{processing:a,success:o.success,error:o.error},noteColor:i?.color??a}}function G(e){if(!e)return;let t=r=>{console.error("[FloPay] Merchant callback failed; checkout continued.",r)};try{Promise.resolve(e()).catch(t)}catch(r){t(r)}}var b=require("react/jsx-runtime");var Nt={panel:{background:"white"},spinnerTrackColor:"#e5e7eb",spinnerAccentColor:"#4A49FF",labelColors:{processing:"#374151",success:"#16a34a",error:"#dc2626"},noteColor:"#6b7280"};function He({status:e,errorMessage:t,authorized:r=!1,processingLabel:n="PROCESSING...",successLabel:o,errorLabel:a="PAYMENT FAILED",successNote:i="You will be automatically redirected, do not close or navigate away from this window.",theme:l=Nt}){let c={fontSize:13,color:l.noteColor,fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0};return(0,b.jsx)("div",{"data-testid":"flopay-processing-overlay","data-status":e,role:"dialog","aria-modal":"true",style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(2px)"},children:(0,b.jsxs)("div",{"data-testid":"flopay-processing-overlay-panel",style:{borderRadius:12,boxShadow:"0 8px 32px rgba(0,0,0,0.18)",...l.panel,padding:"2rem 2.5rem",textAlign:"center",minWidth:240,display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[(0,b.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,b.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{animation:"flopay-spin 0.8s linear infinite"},children:[(0,b.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:l.spinnerTrackColor,strokeWidth:"3"}),(0,b.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:l.spinnerAccentColor})]}),e==="success"&&(0,b.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,b.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,b.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,b.jsx)("path",{d:"M7 12.5l3 3 7-7",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:20,strokeDashoffset:20,animation:"flopay-draw 0.4s 0.15s ease forwards"}})]})}),e==="error"&&(0,b.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,b.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,b.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,b.jsx)("path",{d:"M8 8l8 8M16 8l-8 8",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",style:{strokeDasharray:12,strokeDashoffset:12,animation:"flopay-draw 0.3s 0.1s ease forwards"}})]})})]}),(0,b.jsxs)("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:l.labelColors[e]},children:[e==="processing"&&n,e==="success"&&(o??(r?"PAYMENT AUTHORISED":"PAYMENT SUCCESSFUL")),e==="error"&&a]}),e==="success"&&i!==null&&(0,b.jsx)("p",{style:c,children:i}),e==="error"&&t&&(0,b.jsx)("p",{style:c,children:t}),(0,b.jsx)("style",{children:`
1
+ "use strict";var zt=Object.create;var ge=Object.defineProperty;var Ut=Object.getOwnPropertyDescriptor;var Yt=Object.getOwnPropertyNames;var Ht=Object.getPrototypeOf,Gt=Object.prototype.hasOwnProperty;var he=(e,t)=>()=>(e&&(t=e(e=0)),t);var Fe=(e,t)=>{for(var r in t)ge(e,r,{get:t[r],enumerable:!0})},Xe=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Yt(t))!Gt.call(e,o)&&o!==r&&ge(e,o,{get:()=>t[o],enumerable:!(n=Ut(t,o))||n.enumerable});return e};var $t=(e,t,r)=>(r=e!=null?zt(Ht(e)):{},Xe(t||!e||!e.__esModule?ge(r,"default",{value:e,enumerable:!0}):r,e)),jt=e=>Xe(ge({},"__esModule",{value:!0}),e);function ve(e,t,r){let n=`We couldn't open ${e}. Try again or choose another payment method.`;return t?r?`${n} Open this page in your system browser, then try again.`:`${n} Allow pop-ups for this site, then try again.`:n}function vt(e){if(e instanceof Error)return e.message;if(typeof e=="object"&&e!==null){let t=e.message;return typeof t=="string"?t:void 0}return typeof e=="string"?e:void 0}function ce(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function wt(e){if(typeof e!="object"||e===null)return;let t=e;return ce(t.code)??ce(t.type)??ce(t.name)}function Mr(e){if(!(typeof e!="object"||e===null))return ce(e.decline_code)}function Le(e){return typeof e!="object"||e===null?!1:ce(e.type)?.toLowerCase()==="card_error"||Mr(e)!==void 0}function Fr(e){let t=vt(e)?.toLowerCase()??"",r=wt(e)?.toLowerCase()??"";return Rr.has(r)?!0:/(?:popup|pop-up).{0,40}(?:block|denied|prevent)/i.test(t)||/(?:block|denied|prevent).{0,40}(?:popup|pop-up)/i.test(t)}function Ar(e){if(wt(e)?.toLowerCase()==="paypal_init_timeout")return!0;let r=vt(e)??"";return r.includes("No ack for postMessage init()")&&_r.some(n=>r.includes(n))&&r.includes("10000ms")}function we(e,t){if(Le(e))return{errorCode:"PROVIDER_RUNTIME_FAILED",popupBlocked:!1,providerDeclined:!0,terminalReason:"provider_declined"};let n=Fr(e)||t.inAppBrowser&&!t.handoffObserved&&Ar(e);return{errorCode:n?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",popupBlocked:n,providerDeclined:!1,terminalReason:n?"popup_blocked":"provider_error"}}var Rr,_r,Oe=he(()=>{"use strict";Rr=new Set(["err_blocked_by_client","notallowederror","popup_blocked","popupblocked"]),_r=["https://www.paypal.com","https://www.sandbox.paypal.com"]});function Ee(e){let t=e??(typeof navigator>"u"?"":navigator.userAgent),r=n=>({inAppBrowser:n!=="none",appFamily:n,popupCapability:"unknown"});return t?/FBAN|FBAV|FB_IAB|FBIOS/i.test(t)?r("facebook"):/Instagram/i.test(t)?r("instagram"):/musical_ly|BytedanceWebview|TikTok/i.test(t)?r("tiktok"):/Twitter|Snapchat|Pinterest|LinkedInApp|Line\/|MicroMessenger|GSA\//i.test(t)?r("other_in_app"):/Android.*;\s?wv\)/.test(t)||/(iPhone|iPad|iPod).*AppleWebKit(?!.*Safari)/.test(t)?r("generic_webview"):r("none"):r("none")}function Et(e,t,r=e.popupCapability){return e.inAppBrowser||r==="blocked"||t==="prefer_redirect"?"redirect":"popup"}var Ie=he(()=>{"use strict"});var Mt={};Fe(Mt,{StripeSetupMethod:()=>Vr});function Tr(e){let t=Ve.get(e);if(t)return t;let r=(0,Rt.loadStripe)(e).catch(n=>{throw Ve.delete(e),n});return Ve.set(e,r),r}function Br(e){return e?{theme:xr[e.theme??"default"]??"stripe",...e.variables?{variables:e.variables}:{},...e.rules?{rules:e.rules}:{}}:void 0}function Lr(e){return Le(e)||e.code==="setup_intent_authentication_failure"||e.code==="payment_method_provider_decline"}function Or(e){return e==="paypal"?"PayPal":(0,ke.getStripeMethodDisplayName)(e)}function Ir(){return typeof window>"u"?"":window.location.href}function Vr(e){let{publishableKey:t,method:r,currency:n,appearance:o}=e,[a]=(0,V.useState)(()=>Tr(t)),s=(0,V.useMemo)(()=>{let i=Br(o);return{mode:"setup",currency:n.toLowerCase(),paymentMethodTypes:_t[r]?.types??[r],...i?{appearance:i}:{}}},[o,n,r]);return(0,z.jsx)(U.Elements,{stripe:a,options:s,children:(0,z.jsx)(Dr,{...e})})}function Dr({method:e,category:t,sessionId:r,nonce:n,billingApiUrl:o,telemetry:a,onSubmitting:s,onConfirmed:i,onDeclined:c,onFailed:d,onValidation:p}){let h=(0,U.useStripe)(),S=(0,U.useElements)(),[x,E]=(0,V.useState)(!1),F=(0,V.useRef)(!1),[y]=(0,V.useState)(()=>Ee()),[B,D]=(0,V.useState)(!1),M=(0,V.useCallback)((m,w)=>{if(we(m,{inAppBrowser:y.inAppBrowser,handoffObserved:!1}).popupBlocked){D(!0),d(new Error(ve(Or(e),!0,y.inAppBrowser)),{code:"popup_blocked",retryable:!0});return}d(w.message===void 0?m:new Error(w.message),{code:w.code,retryable:!0})},[y.inAppBrowser,e,d]),b=(0,V.useCallback)(async()=>{if(!(!h||!S||F.current)){F.current=!0,E(!0);try{let m=await S.submit();if(m.error){p(m.error.message??null);return}s();let w=await new kt.PaymentAPI(o,{telemetry:a}).createSessionIntent(r,n,{provider:"stripe",paymentMethodCategory:t,paymentMethodType:e,paymentMethodId:null,intentKind:"setup"});if(w.provider!=="stripe"||w.intentKind!=="setup")throw new ke.FloPayError("The billing API returned a non-setup intent.","api_error",{code:"InvalidSessionIntentResponse"});let C=await h.confirmSetup({elements:S,clientSecret:w.clientSecret,confirmParams:{return_url:Ir()},redirect:"if_required"});if(C.error){Lr(C.error)?c({...C.error.decline_code||C.error.code?{reason:C.error.decline_code??C.error.code}:{},...C.error.message?{message:C.error.message}:{}}):M(C.error,{code:"payment_method_setup_provider_failed",message:C.error.message??"The payment method could not be saved."});return}i()}catch(m){M(m,{code:"payment_method_setup_failed"})}finally{F.current=!1,E(!1)}}},[o,t,S,e,n,i,c,s,p,M,r,h,a]),O=_t[e]?.wallet,I=O==="paypal"&&Et(y,"auto",B?"blocked":y.popupCapability)==="redirect";if(t==="wallet"&&O&&!I){let m={applePay:"never",googlePay:"never",link:"never",paypal:"never",amazonPay:"never"};return m[O]="auto",(0,z.jsx)(U.ExpressCheckoutElement,{options:{paymentMethods:m},onConfirm:()=>{b()}})}return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(U.PaymentElement,{onChange:m=>{m.complete&&p(null)}}),(0,z.jsx)("button",{type:"button","data-flopay-payment-method-save":e,disabled:!h||!S||x,onClick:()=>{b()},children:"Save payment method"})]})}var kt,ke,U,Rt,V,z,_t,Ve,xr,Ft=he(()=>{"use strict";kt=require("@flopay/js/card-setup"),ke=require("@flopay/shared"),U=require("@stripe/react-stripe-js"),Rt=require("@stripe/stripe-js"),V=require("react");Oe();Ie();z=require("react/jsx-runtime"),_t={apple_pay:{types:["card"],wallet:"applePay"},google_pay:{types:["card"],wallet:"googlePay"},link:{types:["link"],wallet:"link"},paypal:{types:["paypal"],wallet:"paypal"},amazon_pay:{types:["amazon_pay"],wallet:"amazonPay"}},Ve=new Map;xr={night:"night",flat:"flat"}});var xt={};Fe(xt,{PayPalSetupMethod:()=>Nr});function Nr({clientId:e,environment:t,currency:r,sessionId:n,nonce:o,billingApiUrl:a,telemetry:s,customer:{userId:i,email:c},onSubmitting:d,onConfirmed:p,onFailed:h,onAbandoned:S}){let x=(0,q.useRef)(null),E=(0,q.useRef)({onSubmitting:d,onConfirmed:p,onFailed:h,onAbandoned:S});E.current={onSubmitting:d,onConfirmed:p,onFailed:h,onAbandoned:S};let[F]=(0,q.useState)(()=>Ee().inAppBrowser);return(0,q.useEffect)(()=>{let y=!0,B,D=new At.PaymentAPI(a,{telemetry:s}),M={userId:i,email:c};return(async()=>{try{let b=await(0,Tt.loadScript)({clientId:e,...r?{currency:r.toUpperCase()}:{},components:"buttons",...t==="sandbox"||t==="production"?{environment:t}:{}}),O=x.current;if(!y||!O)return;if(!b?.Buttons)throw new $.FloPayError("PayPal could not be loaded.","api_error",{code:"paypal_unavailable"});let I=b.Buttons({createVaultSetupToken:async()=>{E.current.onSubmitting();let m=await D.createSessionIntent(n,o,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:$.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:"setup"});if(m.provider!=="paypal"||m.providerObjectType!=="setup_token")throw new $.FloPayError("The billing API did not return a PayPal setup token.","api_error",{code:"InvalidSessionIntentResponse"});return m.providerObjectId},onApprove:async m=>{let w=m.vaultSetupToken;if(!w)throw new $.FloPayError("PayPal approved without a setup token.","api_error",{code:"paypal_setup_token_missing"});let C=await D.processPayment(M.userId,{sessionId:n,nonce:o,paymentMethodCategory:"paypal",tokenizedData:{id:w,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:$.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE},accountData:M});if(!C.ok)throw new $.FloPayError("PayPal could not be saved.","api_error",{code:"paypal_setup_failed",statusCode:C.status});y&&E.current.onConfirmed()},onCancel:()=>{y&&E.current.onAbandoned()},onError:m=>{if(!y)return;let{popupBlocked:w}=we(m,{inAppBrowser:F,handoffObserved:!1});E.current.onFailed(w?new Error(ve("PayPal",!0,F)):m,{code:w?"popup_blocked":"paypal_setup_failed",retryable:!0})}});B=()=>I.close(),await I.render(O)}catch(b){if(!y)return;E.current.onFailed(b,{code:"paypal_unavailable",retryable:!0})}})(),()=>{y=!1,B?.().catch(()=>{}),D.destroy()}},[a,e,r,c,t,F,o,n,s,i]),(0,Bt.jsx)("div",{ref:x,"data-flopay-paypal-setup":""})}var At,$,Tt,q,Bt,Lt=he(()=>{"use strict";At=require("@flopay/js/card-setup"),$=require("@flopay/shared"),Tt=require("@paypal/paypal-js"),q=require("react");Oe();Ie();Bt=require("react/jsx-runtime")});var zr={};Fe(zr,{FloPayCardSetupError:()=>le,FloPayPaymentMethodSetup:()=>Ot});module.exports=jt(zr);var pt=require("@flopay/js/card-setup"),te=require("@flopay/shared"),Pe=require("react");function qe(e,t){if(!e)return t;let r=t??{},n=Object.keys(r),o=n.some(s=>s.startsWith("background")),a={};for(let[s,i]of Object.entries(e))s in r||o&&s.startsWith("background")||(a[s]=i);for(let s of n)a[s]=r[s];return a}var Kt=new Set(["animationIterationCount","aspectRatio","borderImageOutset","borderImageSlice","borderImageWidth","boxFlex","boxFlexGroup","boxOrdinalGroup","columnCount","columns","flex","flexGrow","flexPositive","flexShrink","flexNegative","flexOrder","gridArea","gridRow","gridRowEnd","gridRowSpan","gridRowStart","gridColumn","gridColumnEnd","gridColumnSpan","gridColumnStart","fontWeight","lineClamp","lineHeight","opacity","order","orphans","scale","tabSize","widows","zIndex","zoom","fillOpacity","floodOpacity","stopOpacity","strokeDasharray","strokeDashoffset","strokeMiterlimit","strokeOpacity","strokeWidth"]);function Xt(e){let t=e.replace(/^(Webkit|Moz|ms)(?=[A-Z])/,"");return Kt.has(t.charAt(0).toLowerCase()+t.slice(1))}function qt(e,t){return typeof t=="number"&&t!==0&&!Xt(e)?`${t}px`:String(t).trim()}function Ze(e,t){if(e.style.cssText="",!!t){for(let[r,n]of Object.entries(t))if(!(n==null||n==="")){if(r.startsWith("--")){e.style.setProperty(r,String(n));continue}e.style[r]=qt(r,n)}}}var Je={light:{success:"#166534",error:"#991B1B"},dark:{success:"#4ADE80",error:"#FCA5A5"}};function Qe(e){let t=e.appearance.variables??{},r=e.buttonsLayout.cardFormContainer??{},n=e.appearance.theme==="night",o=n?Je.dark:Je.light,a=t.colorText??(n?"#F1F5F9":"#262833"),s=e.appearance.rules?.[".Label"];return{panel:{...r.background===void 0?{}:{background:r.background},...r.backgroundColor===void 0?{}:{backgroundColor:r.backgroundColor},...r.border===void 0?{}:{border:r.border},...r.borderRadius===void 0?{}:{borderRadius:r.borderRadius},...r.boxShadow===void 0?{}:{boxShadow:r.boxShadow},color:a,...t.fontFamily?{fontFamily:t.fontFamily}:{}},spinnerTrackColor:e.buttonsLayout.cardInputBorder??(n?"#374151":"#e5e7eb"),spinnerAccentColor:t.colorPrimary??"#4A49FF",labelColors:{processing:a,success:o.success,error:o.error},noteColor:s?.color??a}}function H(e){if(!e)return;let t=r=>{console.error("[FloPay] Merchant callback failed; checkout continued.",r)};try{Promise.resolve(e()).catch(t)}catch(r){t(r)}}var P=require("react/jsx-runtime");var Zt={panel:{background:"white"},spinnerTrackColor:"#e5e7eb",spinnerAccentColor:"#4A49FF",labelColors:{processing:"#374151",success:"#16a34a",error:"#dc2626"},noteColor:"#6b7280"};function et({status:e,errorMessage:t,authorized:r=!1,processingLabel:n="PROCESSING...",successLabel:o,errorLabel:a="PAYMENT FAILED",successNote:s="You will be automatically redirected, do not close or navigate away from this window.",theme:i=Zt}){let c={fontSize:13,color:i.noteColor,fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0};return(0,P.jsx)("div",{"data-testid":"flopay-processing-overlay","data-status":e,role:"dialog","aria-modal":"true",style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(2px)"},children:(0,P.jsxs)("div",{"data-testid":"flopay-processing-overlay-panel",style:{borderRadius:12,boxShadow:"0 8px 32px rgba(0,0,0,0.18)",...i.panel,padding:"2rem 2.5rem",textAlign:"center",minWidth:240,display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[(0,P.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,P.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{animation:"flopay-spin 0.8s linear infinite"},children:[(0,P.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:i.spinnerTrackColor,strokeWidth:"3"}),(0,P.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:i.spinnerAccentColor})]}),e==="success"&&(0,P.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,P.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,P.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,P.jsx)("path",{d:"M7 12.5l3 3 7-7",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:20,strokeDashoffset:20,animation:"flopay-draw 0.4s 0.15s ease forwards"}})]})}),e==="error"&&(0,P.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,P.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,P.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,P.jsx)("path",{d:"M8 8l8 8M16 8l-8 8",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",style:{strokeDasharray:12,strokeDashoffset:12,animation:"flopay-draw 0.3s 0.1s ease forwards"}})]})})]}),(0,P.jsxs)("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:i.labelColors[e]},children:[e==="processing"&&n,e==="success"&&(o??(r?"PAYMENT AUTHORISED":"PAYMENT SUCCESSFUL")),e==="error"&&a]}),e==="success"&&s!==null&&(0,P.jsx)("p",{style:c,children:s}),e==="error"&&t&&(0,P.jsx)("p",{style:c,children:t}),(0,P.jsx)("style",{children:`
2
2
  @keyframes flopay-spin { to { transform: rotate(360deg); } }
3
3
  @keyframes flopay-pop { 0% { transform: scale(0); } 100% { transform: scale(1); } }
4
4
  @keyframes flopay-draw { to { stroke-dashoffset: 0; } }
5
5
  @keyframes flopay-shake { 0%,100% { transform: translateX(0); } 20%,60% { transform: translateX(-4px); } 40%,80% { transform: translateX(4px); } }
6
- `})]})})}var B=require("react");var fe=require("react"),Ye=typeof window>"u"?fe.useEffect:fe.useLayoutEffect;var je=require("react/jsx-runtime"),ke=new WeakSet;function $e({capture:e,html:t,messageToken:r,expectedOrigin:n,theme:o,submitLabel:a,containerStyle:i,onReady:l,onError:c,onValidation:p}){let d=(0,B.useRef)(null),y=(0,B.useRef)(l),h=(0,B.useRef)(c),A=(0,B.useRef)(p);y.current=l,h.current=c,A.current=p;let w=(0,B.useRef)(o);w.current=o;let F=(0,B.useRef)(null),m=a??void 0,T=(0,B.useRef)(m);T.current=m;let D=(0,B.useRef)(void 0);return(0,B.useEffect)(()=>{let R=d.current;if(!R)return;let S=!0,L=!1,O=()=>{!S||L||(L=!0,y.current?.())},f=e.on("ready",()=>{O()}),v=e.on("error",_=>{h.current?.(_.message??"There was a problem loading the secure card form.")}),P=e.on("validation",_=>{A.current?.(_.message??null)}),Y=T.current??(ke.has(e)?null:void 0),x={html:t,...r?{messageToken:r}:{},...n?{expectedOrigin:n}:{},...w.current?{theme:w.current}:{},...Y===void 0?{}:{submitLabel:Y}};return F.current=w.current??null,D.current=T.current,T.current!==void 0&&ke.add(e),e.mount(R,x).then(()=>{O()}).catch(_=>{S&&h.current?.(_ instanceof Error?_.message:"Failed to load the secure card form.")}),()=>{S=!1,f(),v(),P(),e.unmount()}},[e,t,r,n]),Ye(()=>{let R=d.current;R&&ze(R,i)},[i]),(0,B.useEffect)(()=>{o!==void 0&&(o===null&&F.current===null||(F.current=o,e.applyTheme?.(o)))},[e,o]),(0,B.useEffect)(()=>{m!==D.current&&(D.current=m,m!==void 0&&ke.add(e),e.setSubmitLabel?.(m??null))},[e,m]),(0,je.jsx)("div",{ref:d,"data-testid":"flopay-vault-card-fields"})}var Xe=/^#([0-9a-f]{6})$/i,Wt=/^#([0-9a-f]{3})$/i,qe=/^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i,Ze=/^rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(0|1|0?\.\d+|1\.0+)\s*\)$/i,zt=/^linear-gradient\(\s*(-?\d+(?:\.\d+)?)deg\s*,\s*(.+)\)$/i,Ut=/^(-?\d+(?:\.\d+)?)(?:px)?$/,Gt=/^(-?\d+(?:\.\d+)?)em$/,Ht=/^blur\(\s*(\d+(?:\.\d+)?)(?:px)?\s*\)$/i,Yt=/^[a-z][a-z0-9 -]{0,31}$/i,$t=new Set(["none","uppercase","lowercase","capitalize"]);function Je(e){if(typeof e!="string")return null;let t=e.trim(),r=Xe.exec(t);if(r){let d=Number.parseInt(r[1],16);return{r:d>>16&255,g:d>>8&255,b:d&255,a:null}}let n=Wt.exec(t);if(n){let[d,y,h]=n[1].split("").map(A=>Number.parseInt(A+A,16));return{r:d,g:y,b:h,a:null}}let o=qe.exec(t),a=o?null:Ze.exec(t),i=o??a;if(!i)return null;let l=Number(i[1]),c=Number(i[2]),p=Number(i[3]);return l>255||c>255||p>255?null:{r:l,g:c,b:p,a:a?Number(a[4]):null}}function Qe({r:e,g:t,b:r,a:n}){return n===null?`#${(1<<24|e<<16|t<<8|r).toString(16).slice(1)}`:`rgba(${e},${t},${r},${n})`}function re(e){if(typeof e!="string")return;let t=e.trim();if(Xe.test(t)||qe.test(t))return t;let r=Ze.exec(t);if(r&&/^\d/.test(r[4]))return t;let n=Je(t);return n?Qe(n):void 0}function me(e,t=.12){let r=Je(e);if(!r)return e;let n=Math.max(0,Math.min(1,1-t));return Qe({r:Math.round(r.r*n),g:Math.round(r.g*n),b:Math.round(r.b*n),a:r.a})}function ne(e,t){let r=[],n=0,o="";for(let a of e){if(a==="("&&(n+=1),a===")"&&(n-=1),a===t&&n===0){o.trim()&&r.push(o.trim()),o="";continue}o+=a}return o.trim()&&r.push(o.trim()),r}function j(e,t,r){if(typeof e!="number"&&typeof e!="string")return;let n=Ut.exec(String(e).trim());if(!n)return;let o=Number(n[1]);return Number.isFinite(o)&&o>=t&&o<=r?o:void 0}function jt(e,t,r){if(typeof e!="string")return;let n=Gt.exec(e.trim());if(!n)return;let o=Number(n[1]);return Number.isFinite(o)&&o>=t&&o<=r?o:void 0}function Kt(e){let t=ne(e,",");if(t.length<2||t.length>5)return;let r=[];for(let[n,o]of t.entries()){let a=ne(o," "),i=re(a[0]);if(!i)return;let l=n/(t.length-1)*100,c=a[1]===void 0?l:Number(/^(\d+(?:\.\d+)?)%$/.exec(a[1])?.[1]),p=r[r.length-1]?.position??-1;if(!Number.isFinite(c)||c<0||c>100||c<p)return;r.push({color:i,position:c})}return{type:"linearGradient",angle:0,stops:r}}function Xt(e){if(typeof e!="string")return;let t=e.trim(),r=re(t);if(r)return{type:"solid",color:r};let n=zt.exec(t);if(!n)return;let o=Number(n[1]);if(!Number.isFinite(o)||o<0||o>360)return;let a=Kt(n[2]);return a&&a.type==="linearGradient"?{...a,angle:o}:void 0}function qt(e){return e.type==="solid"?{type:"solid",color:me(e.color)}:{...e,stops:e.stops.map(t=>({...t,color:me(t.color)}))}}function Zt(e){let t=!1,r,n=[];for(let c of ne(e," ")){if(c.toLowerCase()==="inset"){t=!0;continue}let p=re(c);if(p){r=p;continue}let d=j(c,-128,128);if(d===void 0)return;n.push(d)}if(!r||n.length<2||n.length>4)return;let[o,a,i=0,l=0]=n;if(!(Math.abs(o)>64||Math.abs(a)>64||i>128||Math.abs(l)>32))return{color:r,inset:t,offsetX:o,offsetY:a,blur:i,spread:l}}function Jt(e){if(typeof e!="string")return;let t=e.trim();if(t.toLowerCase()==="none")return[];let r=ne(t,",").map(Zt);if(!(r.length===0||r.length>4))return r.every(n=>n!==void 0)?r:void 0}function Ke(e){if(typeof e!="string")return;let t=ne(e,",").map(r=>r.replace(/^['"]|['"]$/g,"").trim()).filter(r=>Yt.test(r)).slice(0,4);return t.length>0?t:void 0}function Qt(e){let t=typeof e=="string"?e.trim().split(/\s+/):[e],r=j(t[0],0,64),n=j(t[1]??t[0],0,64);if(!(r===void 0||n===void 0))return{paddingBlock:r,paddingInline:n}}function er(e){if(e==="bold")return 700;if(e==="normal")return 400;let t=Number(e);return Number.isInteger(t)&&t>=100&&t<=900?t:void 0}function et({appearance:e,buttonsStyles:t,fontFamily:r}){let n=t.submitButton;if(!n)return;let o=e?.variables,a=Xt(n.background??n.backgroundColor),i=re(o?.colorPrimaryHover),l=i?{type:"solid",color:i}:a&&qt(a),c={fontFamilies:Ke(n.fontFamily)??Ke(r),fontSize:j(n.fontSize??t.submitButtonFontSize,10,32)??16,fontWeight:er(n.fontWeight)??600,letterSpacing:jt(n.letterSpacing,-.1,.5)??.01,lineHeight:j(n.lineHeight,.8,2)??1,textTransform:$t.has(String(n.textTransform))?n.textTransform:"uppercase"},p=Qt(n.padding),d=Jt(n.boxShadow),y=j(n.borderRadius,0,9999),h=typeof n.backdropFilter=="string"?j(Ht.exec(n.backdropFilter.trim())?.[1],0,40):void 0;return{foregroundColor:re(n.color)??"#FFFFFF",...a?{background:a,disabledBackground:a}:{},...l?{hoverBackground:l}:{},typography:c,...p?{spacing:p}:{},...d?{shadow:d}:{},...y===void 0?{}:{borderRadius:y},disabledOpacity:e?.theme==="night"?.8:.6,...h===void 0?{}:{backdropBlur:h}}}function tr(e,t=.12){let r=e.trim(),n=/^[0-9a-fA-F]{6}$/.test(r)?`#${r}`:r;return/^#[0-9a-fA-F]{6}$/.test(n)?me(n,t):e}function rr(e){if(typeof e=="number"||typeof e=="string")return e}function tt({appearance:e,buttonsStyles:t,layout:r="default"}){let n=e?.variables,o=y=>typeof y=="string"&&y?y:void 0,a=t.submitButton,i=o(n?.colorPrimary)??o(a?.backgroundColor)??"#4A49FF",l=r==="buttons",c=t.nameInput,p=o(c?.fontFamily)??o(n?.fontFamily)??"Poppins, sans-serif",d=et({appearance:e,buttonsStyles:t,fontFamily:p});return{primaryColor:i,primaryHoverColor:o(n?.colorPrimaryHover)??tr(i,.12),inputBackgroundColor:o(t.cardInputBackground)??o(n?.colorBackground)??"#ffffff",textColor:o(t.cardInputColor)??o(c?.color)??o(n?.colorText)??"#262833",borderColor:o(t.cardInputBorder)??(l?"#e5e7eb":"#A4A4FF"),placeholderColor:o(t.cardInputPlaceholderColor)??"#9ca3af",errorColor:o(n?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:p,fontSize:o(t.cardInputFontSize)??o(n?.fontSizeBase)??"16px",fontWeight:String(rr(c?.fontWeight)??400),borderRadius:o(n?.borderRadius)??"8px",...d?{submitButton:d}:{}}}var Re=require("react/jsx-runtime"),oe=class extends Q.FloPayError{constructor(t,r,n){super(t,r,n),this.name="FloPayCardSetupError",this.retryable=n.retryable}};function ae(e,t={}){let r=e instanceof Q.FloPayError?e:void 0,n=r?.statusCode,o=t.retryable??(r?.type==="network_error"||r?.type==="rate_limit_error"||typeof n=="number"&&n>=500||r?.code==="vault_capture_timeout"||!r);return new oe(r?.message??(e instanceof Error?e.message:"Failed to load the secure card form."),r?.type??"api_error",{code:t.code??r?.code??"card_setup_load_failed",retryable:o,...r?.param?{param:r.param}:{},...n===void 0?{}:{statusCode:n}})}var Te=require("react");var ie=require("@flopay/js/card-setup"),k=require("@flopay/shared"),s=Lt(require("react"),1);var nr=new Set(["apple_pay","google_pay","link","paypal","amazon_pay"]);function nt(e){let t=e.data.stripe,r=Array.from(new Set(t?.enabledPaymentMethods??[])),n=e.data.paypal,o=n?.publishableKey?{clientId:n.publishableKey,...n.environment?{environment:String(n.environment)}:{}}:null,a=r.filter(i=>i!=="card"&&!(o&&i==="paypal"));return{card:r.includes("card"),stripe:t?.publishableKey&&a.length>0?{publishableKey:t.publishableKey,methods:a}:null,paypal:o}}function ot(e){return e.card||e.stripe!==null||e.paypal!==null}function at(e){return nr.has(e)?"wallet":"apm"}var or=["setup_intent","setup_intent_client_secret","redirect_status"];function it(){if(typeof window>"u")return null;let e=new URLSearchParams(window.location.search);return!e.has("setup_intent")||!e.has("redirect_status")?null:{failed:e.get("redirect_status")==="failed"}}function st(){if(typeof window>"u")return;let e=new URL(window.location.href),t=!1;for(let r of or)e.searchParams.has(r)&&(e.searchParams.delete(r),t=!0);t&&window.history.replaceState(window.history.state,"",e.toString())}function lt(e){return e==="card"?{processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED"}:{processingLabel:"SAVING PAYMENT METHOD...",successLabel:"PAYMENT METHOD SAVED",errorLabel:"PAYMENT METHOD NOT SAVED"}}var C=require("react/jsx-runtime"),ir=15,sr=2e3;function lr(e){return{userId:e.customer?.id??"",email:e.customer?.email??""}}function _e(e){return new Promise(t=>setTimeout(t,e))}async function ur(e,t,r){if(!t.trim())throw new k.FloPayError("FloPayPaymentMethodSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!r.trim())throw new k.FloPayError("FloPayPaymentMethodSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let n=await e.getUnifiedCheckoutSession(t,r),o=n.data.session;if(!o||!(0,k.isCardSetupCheckoutSession)(o))throw new k.FloPayError("FloPayPaymentMethodSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidPaymentMethodSetupSession",param:"sessionId"});let a=nt(n);if(!ot(a))throw new k.FloPayError("FloPay: this setup session advertises no payment method.","validation_error",{code:"NoAdvertisedPaymentMethods",param:"sessionId"});return{session:o,advertisement:a}}async function cr(e,t,r,n){let o=t.vault??null;if(o?.html?.trim()||(o=await e.getVaultCapture(r,n)),!o.html?.trim())throw new k.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});return o}var ge=class extends s.default.Component{constructor(){super(...arguments);this.state={failed:!1}}static getDerivedStateFromError(){return{failed:!0}}componentDidCatch(r){this.props.onFailed(r,{code:"payment_method_setup_load_failed",retryable:!1})}render(){return this.state.failed?null:this.props.children}};function ct({branches:{StripeSetupMethod:e,PayPalSetupMethod:t},sessionId:r,nonce:n,billingApiUrl:o,telemetry:a,theme:i="modern-light",containerStyle:l,loading:c=null,onReady:p,onComplete:d,onDecline:y,onCancel:h,onValidation:A,onError:w}){let[F]=(0,s.useState)(it),[m,T]=(0,s.useState)(null),[D,R]=(0,s.useState)(!1),[S,L]=(0,s.useState)(null),[O,f]=(0,s.useState)(null),[v,P]=(0,s.useState)(null),[Y,x]=(0,s.useState)(null),_=(0,s.useRef)(!1),Ce=(0,s.useRef)(!1),ee=(0,s.useRef)(!1),ve=(0,s.useRef)(!1),we=(0,s.useRef)(0),le=(0,s.useRef)(0),X=(0,s.useRef)(!1),N=(0,s.useMemo)(()=>typeof i=="object"?void 0:(0,k.resolveTheme)(i),[i]),Rt=(0,s.useMemo)(()=>typeof i=="object"?i:N?tt({appearance:N.appearance,buttonsStyles:N.buttonsLayout,layout:"default"}):null,[N,i]),_t=(0,s.useMemo)(()=>We(N?.buttonsLayout.cardFormContainer,l),[N,l]),Be=(0,s.useMemo)(()=>N?Ge(N):void 0,[N]),M=(0,s.useRef)({sessionId:r,nonce:n,billingApiUrl:o,telemetry:a,onReady:p,onComplete:d,onDecline:y,onCancel:h,onValidation:A,onError:w});M.current={sessionId:r,nonce:n,billingApiUrl:o,telemetry:a,onReady:p,onComplete:d,onDecline:y,onCancel:h,onValidation:A,onError:w},(0,s.useEffect)(()=>{X.current=!0;let u=we.current+1;return we.current=u,()=>{X.current=!1,le.current+=1,queueMicrotask(()=>{we.current===u&&(ee.current||ve.current||(ve.current=!0,G(()=>{M.current.onCancel?.({status:"cancelled",sessionId:r})})))})}},[r]);let q=(0,s.useCallback)((u,g)=>{ee.current=!0,_.current=!1,x({status:"success",wording:u,message:null}),(async()=>(await _e(600),!Ce.current&&(Ce.current=!0,G(()=>{M.current.onComplete?.({status:"succeeded",sessionId:M.current.sessionId,...g?{paymentMethod:g}:{}})}),X.current&&x(null))))()},[]),Z=(0,s.useCallback)((u,g)=>{ee.current=!0,_.current=!1,x({status:"error",wording:u,message:g.message??null}),G(()=>{M.current.onDecline?.({status:"declined",sessionId:M.current.sessionId,...g.reason?{reason:g.reason}:{},...g.message?{message:g.message}:{}})}),(async()=>(await _e(400),X.current&&x(null)))()},[]),te=(0,s.useCallback)((u,g)=>{_.current?(_.current=!1,x({status:"error",wording:u,message:g.message}),setTimeout(()=>{X.current&&x(null)},400)):x(null),G(()=>M.current.onError?.(g))},[]),ue=(0,s.useCallback)(async u=>{let g=le.current+1;le.current=g;let I=()=>!X.current||g!==le.current;_.current=!0,x({status:"processing",wording:"payment_method",message:null});let W=new ie.PaymentAPI((0,k.resolveBillingApiUrl)(M.current.billingApiUrl),{telemetry:M.current.telemetry});try{for(let E=0;E<ir;E+=1){if((E>0||u.waitFirst)&&await _e(sr),I())return;let J=await W.getUnifiedCheckoutSession(M.current.sessionId,M.current.nonce);if(I())return;let De=J.data.session?.status;if(De==="complete"){R(!0),q("payment_method");return}if(De==="expired")throw new k.FloPayError("This setup session expired before the payment method was saved.","validation_error",{code:"payment_method_setup_expired"})}throw new k.FloPayError("The payment method could not be confirmed yet. Please try again.","api_error",{code:"payment_method_setup_unverified"})}catch(E){if(I())return;let J=E instanceof k.FloPayError&&E.code==="payment_method_setup_unverified";te("payment_method",ae(E,J?{retryable:!0}:{}))}finally{W.destroy()}},[te,q]);(0,s.useEffect)(()=>{let u=!0,g=new ie.PaymentAPI((0,k.resolveBillingApiUrl)(o),{telemetry:a});return T(null),R(!1),L(null),f(null),P(null),ee.current=!1,ve.current=!1,Ce.current=!1,(async()=>{try{let{session:I,advertisement:W}=await ur(g,r,n);if(!u)return;let E={advertisement:W,currency:I.currency,customer:lr(I)};if(F){if(st(),I.status==="complete"){R(!0),T(E),q("payment_method");return}F.failed?Z("payment_method",{reason:"redirect_failed"}):ue({waitFirst:!0})}let J=W.card?await cr(g,I,r,n):null;if(!u)return;T(E),J&&(f(J),L(new ie.PciVaultCardCapture({sessionId:r,operation:"card_setup",telemetry:a})))}catch(I){if(!u)return;let W=ae(I);ee.current=!0,P(W),G(()=>M.current.onError?.(W))}})(),()=>{u=!1,g.destroy()}},[o,n,F,Z,q,r,a,ue]),(0,s.useEffect)(()=>{if(!S)return;_.current=!1;let u=S.on("submitting",()=>{_.current=!0,x({status:"processing",wording:"card",message:null})}),g=S.on("complete",E=>{q("card",E.paymentMethod)}),I=S.on("decline",E=>{Z("card",{...E.declineReason?{reason:E.declineReason}:{},...E.message?{message:E.message}:{}})}),W=S.on("challenge_dismissed",()=>{x(null)});return()=>{u(),g(),I(),W()}},[S,Z,q]);let ce=(0,s.useMemo)(()=>({onSubmitting:()=>{_.current=!0,x({status:"processing",wording:"payment_method",message:null})},onConfirmed:()=>{ue({waitFirst:!1})},onDeclined:u=>Z("payment_method",u),onFailed:(u,g)=>{te("payment_method",ae(u,g))},onValidation:u=>{G(()=>M.current.onValidation?.(u))},onAbandoned:()=>{_.current=!1,x(null)}}),[Z,te,ue]),Le=Y?(0,C.jsx)(He,{status:Y.status,errorMessage:Y.message,...lt(Y.wording),successNote:null,...Be?{theme:Be}:{}}):null;if(v)return(0,C.jsx)("div",{role:"alert",children:v.message});if(!m||D)return(0,C.jsxs)(C.Fragment,{children:[Le,m?null:c]});let{advertisement:$,currency:Oe,customer:Ft}=m,Ie=(0,k.resolveBillingApiUrl)(o),Ve=a===void 0?{}:{telemetry:a};return(0,C.jsxs)(C.Fragment,{children:[Le,$.card&&S&&O?.html?(0,C.jsx)("div",{"data-flopay-payment-method":"card",children:(0,C.jsx)($e,{capture:S,html:O.html,messageToken:O.messageToken,expectedOrigin:O.expectedOrigin,theme:Rt,containerStyle:_t,onReady:()=>{G(()=>M.current.onReady?.())},onValidation:u=>{G(()=>M.current.onValidation?.(u))},onError:u=>{u&&te("card",ae(new Error(u),{code:"card_setup_widget_failed",retryable:!0}))}})}):null,$.stripe?.methods.map(u=>(0,C.jsx)("div",{"data-flopay-payment-method":u,children:(0,C.jsx)(ge,{onFailed:ce.onFailed,children:(0,C.jsx)(s.Suspense,{fallback:null,children:(0,C.jsx)(e,{method:u,category:at(u),publishableKey:$.stripe?.publishableKey??"",currency:Oe,sessionId:r,nonce:n,billingApiUrl:Ie,...Ve,...N?{appearance:N.appearance}:{},...ce})})})},u)),$.paypal?(0,C.jsx)("div",{"data-flopay-payment-method":"paypal",children:(0,C.jsx)(ge,{onFailed:ce.onFailed,children:(0,C.jsx)(s.Suspense,{fallback:null,children:(0,C.jsx)(t,{clientId:$.paypal.clientId,...$.paypal.environment?{environment:$.paypal.environment}:{},currency:Oe,sessionId:r,nonce:n,billingApiUrl:Ie,customer:Ft,...Ve,...ce})})})}):null]})}var kt=require("react/jsx-runtime"),kr={StripeSetupMethod:(0,Te.lazy)(()=>Promise.resolve().then(()=>(St(),ht)).then(e=>({default:e.StripeSetupMethod}))),PayPalSetupMethod:(0,Te.lazy)(()=>Promise.resolve().then(()=>(wt(),Ct)).then(e=>({default:e.PayPalSetupMethod})))};function Et(e){return(0,kt.jsx)(ct,{...e,branches:kr})}0&&(module.exports={FloPayCardSetupError,FloPayPaymentMethodSetup});
6
+ `})]})})}var L=require("react");var Se=require("react"),tt=typeof window>"u"?Se.useEffect:Se.useLayoutEffect;var nt=require("react/jsx-runtime"),Ae=new WeakSet;function rt({capture:e,html:t,messageToken:r,expectedOrigin:n,theme:o,submitLabel:a,containerStyle:s,onReady:i,onError:c,onValidation:d}){let p=(0,L.useRef)(null),h=(0,L.useRef)(i),S=(0,L.useRef)(c),x=(0,L.useRef)(d);h.current=i,S.current=c,x.current=d;let E=(0,L.useRef)(o);E.current=o;let F=(0,L.useRef)(null),y=a??void 0,B=(0,L.useRef)(y);B.current=y;let D=(0,L.useRef)(void 0);return(0,L.useEffect)(()=>{let M=p.current;if(!M)return;let b=!0,O=!1,I=()=>{!b||O||(O=!0,h.current?.())},m=e.on("ready",()=>{I()}),w=e.on("error",W=>{S.current?.(W.message??"There was a problem loading the secure card form.")}),C=e.on("validation",W=>{x.current?.(W.message??null)}),j=B.current??(Ae.has(e)?null:void 0),T={html:t,...r?{messageToken:r}:{},...n?{expectedOrigin:n}:{},...E.current?{theme:E.current}:{},...j===void 0?{}:{submitLabel:j}};return F.current=E.current??null,D.current=B.current,B.current!==void 0&&Ae.add(e),e.mount(M,T).then(()=>{I()}).catch(W=>{b&&S.current?.(W instanceof Error?W.message:"Failed to load the secure card form.")}),()=>{b=!1,m(),w(),C(),e.unmount()}},[e,t,r,n]),tt(()=>{let M=p.current;M&&Ze(M,s)},[s]),(0,L.useEffect)(()=>{o!==void 0&&(o===null&&F.current===null||(F.current=o,e.applyTheme?.(o)))},[e,o]),(0,L.useEffect)(()=>{y!==D.current&&(D.current=y,y!==void 0&&Ae.add(e),e.setSubmitLabel?.(y??null))},[e,y]),(0,nt.jsx)("div",{ref:p,"data-testid":"flopay-vault-card-fields"})}var at=/^#([0-9a-f]{6})$/i,Jt=/^#([0-9a-f]{3})$/i,st=/^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i,it=/^rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(0|1|0?\.\d+|1\.0+)\s*\)$/i,Qt=/^linear-gradient\(\s*(-?\d+(?:\.\d+)?)deg\s*,\s*(.+)\)$/i,er=/^(-?\d+(?:\.\d+)?)(?:px)?$/,tr=/^(-?\d+(?:\.\d+)?)em$/,rr=/^blur\(\s*(\d+(?:\.\d+)?)(?:px)?\s*\)$/i,nr=/^[a-z][a-z0-9 -]{0,31}$/i,or=new Set(["none","uppercase","lowercase","capitalize"]);function lt(e){if(typeof e!="string")return null;let t=e.trim(),r=at.exec(t);if(r){let p=Number.parseInt(r[1],16);return{r:p>>16&255,g:p>>8&255,b:p&255,a:null}}let n=Jt.exec(t);if(n){let[p,h,S]=n[1].split("").map(x=>Number.parseInt(x+x,16));return{r:p,g:h,b:S,a:null}}let o=st.exec(t),a=o?null:it.exec(t),s=o??a;if(!s)return null;let i=Number(s[1]),c=Number(s[2]),d=Number(s[3]);return i>255||c>255||d>255?null:{r:i,g:c,b:d,a:a?Number(a[4]):null}}function ut({r:e,g:t,b:r,a:n}){return n===null?`#${(1<<24|e<<16|t<<8|r).toString(16).slice(1)}`:`rgba(${e},${t},${r},${n})`}function se(e){if(typeof e!="string")return;let t=e.trim();if(at.test(t)||st.test(t))return t;let r=it.exec(t);if(r&&/^\d/.test(r[4]))return t;let n=lt(t);return n?ut(n):void 0}function be(e,t=.12){let r=lt(e);if(!r)return e;let n=Math.max(0,Math.min(1,1-t));return ut({r:Math.round(r.r*n),g:Math.round(r.g*n),b:Math.round(r.b*n),a:r.a})}function ie(e,t){let r=[],n=0,o="";for(let a of e){if(a==="("&&(n+=1),a===")"&&(n-=1),a===t&&n===0){o.trim()&&r.push(o.trim()),o="";continue}o+=a}return o.trim()&&r.push(o.trim()),r}function X(e,t,r){if(typeof e!="number"&&typeof e!="string")return;let n=er.exec(String(e).trim());if(!n)return;let o=Number(n[1]);return Number.isFinite(o)&&o>=t&&o<=r?o:void 0}function ar(e,t,r){if(typeof e!="string")return;let n=tr.exec(e.trim());if(!n)return;let o=Number(n[1]);return Number.isFinite(o)&&o>=t&&o<=r?o:void 0}function sr(e){let t=ie(e,",");if(t.length<2||t.length>5)return;let r=[];for(let[n,o]of t.entries()){let a=ie(o," "),s=se(a[0]);if(!s)return;let i=n/(t.length-1)*100,c=a[1]===void 0?i:Number(/^(\d+(?:\.\d+)?)%$/.exec(a[1])?.[1]),d=r[r.length-1]?.position??-1;if(!Number.isFinite(c)||c<0||c>100||c<d)return;r.push({color:s,position:c})}return{type:"linearGradient",angle:0,stops:r}}function ir(e){if(typeof e!="string")return;let t=e.trim(),r=se(t);if(r)return{type:"solid",color:r};let n=Qt.exec(t);if(!n)return;let o=Number(n[1]);if(!Number.isFinite(o)||o<0||o>360)return;let a=sr(n[2]);return a&&a.type==="linearGradient"?{...a,angle:o}:void 0}function lr(e){return e.type==="solid"?{type:"solid",color:be(e.color)}:{...e,stops:e.stops.map(t=>({...t,color:be(t.color)}))}}function ur(e){let t=!1,r,n=[];for(let c of ie(e," ")){if(c.toLowerCase()==="inset"){t=!0;continue}let d=se(c);if(d){r=d;continue}let p=X(c,-128,128);if(p===void 0)return;n.push(p)}if(!r||n.length<2||n.length>4)return;let[o,a,s=0,i=0]=n;if(!(Math.abs(o)>64||Math.abs(a)>64||s>128||Math.abs(i)>32))return{color:r,inset:t,offsetX:o,offsetY:a,blur:s,spread:i}}function cr(e){if(typeof e!="string")return;let t=e.trim();if(t.toLowerCase()==="none")return[];let r=ie(t,",").map(ur);if(!(r.length===0||r.length>4))return r.every(n=>n!==void 0)?r:void 0}function ot(e){if(typeof e!="string")return;let t=ie(e,",").map(r=>r.replace(/^['"]|['"]$/g,"").trim()).filter(r=>nr.test(r)).slice(0,4);return t.length>0?t:void 0}function dr(e){let t=typeof e=="string"?e.trim().split(/\s+/):[e],r=X(t[0],0,64),n=X(t[1]??t[0],0,64);if(!(r===void 0||n===void 0))return{paddingBlock:r,paddingInline:n}}function pr(e){if(e==="bold")return 700;if(e==="normal")return 400;let t=Number(e);return Number.isInteger(t)&&t>=100&&t<=900?t:void 0}function ct({appearance:e,buttonsStyles:t,fontFamily:r}){let n=t.submitButton;if(!n)return;let o=e?.variables,a=ir(n.background??n.backgroundColor),s=se(o?.colorPrimaryHover),i=s?{type:"solid",color:s}:a&&lr(a),c={fontFamilies:ot(n.fontFamily)??ot(r),fontSize:X(n.fontSize??t.submitButtonFontSize,10,32)??16,fontWeight:pr(n.fontWeight)??600,letterSpacing:ar(n.letterSpacing,-.1,.5)??.01,lineHeight:X(n.lineHeight,.8,2)??1,textTransform:or.has(String(n.textTransform))?n.textTransform:"uppercase"},d=dr(n.padding),p=cr(n.boxShadow),h=X(n.borderRadius,0,9999),S=typeof n.backdropFilter=="string"?X(rr.exec(n.backdropFilter.trim())?.[1],0,40):void 0;return{foregroundColor:se(n.color)??"#FFFFFF",...a?{background:a,disabledBackground:a}:{},...i?{hoverBackground:i}:{},typography:c,...d?{spacing:d}:{},...p?{shadow:p}:{},...h===void 0?{}:{borderRadius:h},disabledOpacity:e?.theme==="night"?.8:.6,...S===void 0?{}:{backdropBlur:S}}}function fr(e,t=.12){let r=e.trim(),n=/^[0-9a-fA-F]{6}$/.test(r)?`#${r}`:r;return/^#[0-9a-fA-F]{6}$/.test(n)?be(n,t):e}function mr(e){if(typeof e=="number"||typeof e=="string")return e}function dt({appearance:e,buttonsStyles:t,layout:r="default"}){let n=e?.variables,o=h=>typeof h=="string"&&h?h:void 0,a=t.submitButton,s=o(n?.colorPrimary)??o(a?.backgroundColor)??"#4A49FF",i=r==="buttons",c=t.nameInput,d=o(c?.fontFamily)??o(n?.fontFamily)??"Poppins, sans-serif",p=ct({appearance:e,buttonsStyles:t,fontFamily:d});return{primaryColor:s,primaryHoverColor:o(n?.colorPrimaryHover)??fr(s,.12),inputBackgroundColor:o(t.cardInputBackground)??o(n?.colorBackground)??"#ffffff",textColor:o(t.cardInputColor)??o(c?.color)??o(n?.colorText)??"#262833",borderColor:o(t.cardInputBorder)??(i?"#e5e7eb":"#A4A4FF"),placeholderColor:o(t.cardInputPlaceholderColor)??"#9ca3af",errorColor:o(n?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:d,fontSize:o(t.cardInputFontSize)??o(n?.fontSizeBase)??"16px",fontWeight:String(mr(c?.fontWeight)??400),borderRadius:o(n?.borderRadius)??"8px",...p?{submitButton:p}:{}}}var Te=require("react/jsx-runtime"),le=class extends te.FloPayError{constructor(t,r,n){super(t,r,n),this.name="FloPayCardSetupError",this.retryable=n.retryable}};function re(e,t={}){let r=e instanceof te.FloPayError?e:void 0,n=r?.statusCode,o=t.retryable??(r?.type==="network_error"||r?.type==="rate_limit_error"||typeof n=="number"&&n>=500||r?.code==="vault_capture_timeout"||!r);return new le(r?.message??(e instanceof Error?e.message:"Failed to load the secure card form."),r?.type??"api_error",{code:t.code??r?.code??"card_setup_load_failed",retryable:o,...r?.param?{param:r.param}:{},...n===void 0?{}:{statusCode:n}})}var De=require("react");var ue=require("@flopay/js/card-setup"),_=require("@flopay/shared"),l=$t(require("react"),1);var ft=require("@flopay/shared"),yr=new Set(["apple_pay","google_pay","link","paypal","amazon_pay"]),gr=new Set(["wallet","apm"]);function ne(e){return typeof e=="string"&&e.trim().length>0}function hr(e){if(typeof e!="object"||e===null)return!1;let t=e;return ne(t.family)&&ne(t.paymentMethodType)}function Sr(e){let r=e.raw?.data?.currency;return ne(r)?r.trim().toUpperCase():null}function mt(e){let t=Sr(e),r=e.data.session?.advertisedPaymentMethods;if(!Array.isArray(r))return{card:!0,stripe:[],paypal:null,currency:t,skippedForMissingCurrency:[]};let n={card:!1,stripe:[],paypal:null,currency:t,skippedForMissingCurrency:[]},o=new Set;for(let a of r){if(!hr(a)||o.has(a.paymentMethodType))continue;let{family:s,paymentMethodType:i,providerType:c,publishableKey:d}=a;if(s==="card"){if(i!=="card")continue;n.card=!0}else if(gr.has(s)){if(c!=="stripe"||i==="card"||!ne(d))continue;if(t===null){n.skippedForMissingCurrency.includes(i)||n.skippedForMissingCurrency.push(i);continue}n.stripe.push({method:i,publishableKey:d,currency:t})}else if(s==="paypal"){if(i!==ft.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE||c!=="paypal"||!ne(d))continue;n.paypal={clientId:d,...ne(a.environment)?{environment:a.environment}:{}}}else continue;o.add(i)}return n.paypal&&(n.stripe=n.stripe.filter(a=>a.method!=="paypal")),n}function xe(e){return[...e.card?["card"]:[],...e.stripe.map(t=>t.method),...e.paypal?["paypal"]:[]]}function yt(e){return xe(e).length>0}function gt(e){return yr.has(e)?"wallet":"apm"}var br=["setup_intent","setup_intent_client_secret","redirect_status"];function ht(){if(typeof window>"u")return null;let e=new URLSearchParams(window.location.search);return!e.has("setup_intent")||!e.has("redirect_status")?null:{failed:e.get("redirect_status")==="failed"}}function St(){if(typeof window>"u")return;let e=new URL(window.location.href),t=!1;for(let r of br)e.searchParams.has(r)&&(e.searchParams.delete(r),t=!0);t&&window.history.replaceState(window.history.state,"",e.toString())}function bt(e){return e==="card"?{processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED"}:{processingLabel:"SAVING PAYMENT METHOD...",successLabel:"PAYMENT METHOD SAVED",errorLabel:"PAYMENT METHOD NOT SAVED"}}var v=require("react/jsx-runtime"),Cr=15,vr=2e3;function wr(e){return{userId:e.customer?.id??"",email:e.customer?.email??""}}function Be(e){return new Promise(t=>setTimeout(t,e))}async function Er(e,t,r){if(!t.trim())throw new _.FloPayError("FloPayPaymentMethodSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!r.trim())throw new _.FloPayError("FloPayPaymentMethodSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let n=await e.getUnifiedCheckoutSession(t,r),o=n.data.session;if(!o||!(0,_.isCardSetupCheckoutSession)(o))throw new _.FloPayError("FloPayPaymentMethodSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidPaymentMethodSetupSession",param:"sessionId"});let a=mt(n);if(!yt(a)){let{skippedForMissingCurrency:s}=a,i=s.length>0?`FloPay: this setup session advertises only Stripe methods (${s.join(", ")}), and they need the session's currency, which the setup-session read did not carry.`:"FloPay: this setup session advertises no payment method.";throw new _.FloPayError(i,"validation_error",{code:"NoAdvertisedPaymentMethods",param:"sessionId"})}return{session:o,advertisement:a}}async function kr(e,t,r,n){let o=t.vault??null;if(o?.html?.trim()||(o=await e.getVaultCapture(r,n)),!o.html?.trim())throw new _.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});return o}var Ce=class extends l.default.Component{constructor(){super(...arguments);this.state={failed:!1}}static getDerivedStateFromError(){return{failed:!0}}componentDidCatch(r){this.props.onFailed(r,{code:"payment_method_setup_load_failed",retryable:!1})}render(){return this.state.failed?null:this.props.children}};function Ct({branches:{StripeSetupMethod:e,PayPalSetupMethod:t},sessionId:r,nonce:n,billingApiUrl:o,telemetry:a,theme:s="modern-light",containerStyle:i,loading:c=null,onReady:d,onComplete:p,onDecline:h,onCancel:S,onValidation:x,onError:E}){let[F]=(0,l.useState)(ht),[y,B]=(0,l.useState)(null),[D,M]=(0,l.useState)(!1),[b,O]=(0,l.useState)(null),[I,m]=(0,l.useState)(null),[w,C]=(0,l.useState)(null),[j,T]=(0,l.useState)(null),[W,Ne]=(0,l.useState)(()=>new Set),de=(0,l.useRef)(W),We=(0,l.useRef)(null);We.current=y;let Y=(0,l.useRef)(!1),Re=(0,l.useRef)(!1),oe=(0,l.useRef)(!1),_e=(0,l.useRef)(!1),Me=(0,l.useRef)(0),pe=(0,l.useRef)(0),Z=(0,l.useRef)(!1),N=(0,l.useMemo)(()=>typeof s=="object"?void 0:(0,_.resolveTheme)(s),[s]),Vt=(0,l.useMemo)(()=>typeof s=="object"?s:N?dt({appearance:N.appearance,buttonsStyles:N.buttonsLayout,layout:"default"}):null,[N,s]),Dt=(0,l.useMemo)(()=>qe(N?.buttonsLayout.cardFormContainer,i),[N,i]),ze=(0,l.useMemo)(()=>N?Qe(N):void 0,[N]),A=(0,l.useRef)({sessionId:r,nonce:n,billingApiUrl:o,telemetry:a,onReady:d,onComplete:p,onDecline:h,onCancel:S,onValidation:x,onError:E});A.current={sessionId:r,nonce:n,billingApiUrl:o,telemetry:a,onReady:d,onComplete:p,onDecline:h,onCancel:S,onValidation:x,onError:E},(0,l.useEffect)(()=>{Z.current=!0;let u=Me.current+1;return Me.current=u,()=>{Z.current=!1,pe.current+=1,queueMicrotask(()=>{Me.current===u&&(oe.current||_e.current||(_e.current=!0,H(()=>{A.current.onCancel?.({status:"cancelled",sessionId:r})})))})}},[r]);let J=(0,l.useCallback)((u,f)=>{oe.current=!0,Y.current=!1,T({status:"success",wording:u,message:null}),(async()=>(await Be(600),!Re.current&&(Re.current=!0,H(()=>{A.current.onComplete?.({status:"succeeded",sessionId:A.current.sessionId,...f?{paymentMethod:f}:{}})}),Z.current&&T(null))))()},[]),Q=(0,l.useCallback)((u,f)=>{oe.current=!0,Y.current=!1,T({status:"error",wording:u,message:f.message??null}),H(()=>{A.current.onDecline?.({status:"declined",sessionId:A.current.sessionId,...f.reason?{reason:f.reason}:{},...f.message?{message:f.message}:{}})}),(async()=>(await Be(400),Z.current&&T(null)))()},[]),ee=(0,l.useCallback)((u,f)=>{Y.current?(Y.current=!1,T({status:"error",wording:u,message:f.message}),setTimeout(()=>{Z.current&&T(null)},400)):T(null),H(()=>A.current.onError?.(f))},[]),fe=(0,l.useCallback)(async u=>{let f=pe.current+1;pe.current=f;let k=()=>!Z.current||f!==pe.current;Y.current=!0,T({status:"processing",wording:"payment_method",message:null});let R=new ue.PaymentAPI((0,_.resolveBillingApiUrl)(A.current.billingApiUrl),{telemetry:A.current.telemetry});try{for(let g=0;g<Cr;g+=1){if((g>0||u.waitFirst)&&await Be(vr),k())return;let G=await R.getUnifiedCheckoutSession(A.current.sessionId,A.current.nonce);if(k())return;let K=G.data.session?.status;if(K==="complete"){M(!0),J("payment_method");return}if(K==="expired")throw new _.FloPayError("This setup session expired before the payment method was saved.","validation_error",{code:"payment_method_setup_expired"})}throw new _.FloPayError("The payment method could not be confirmed yet. Please try again.","api_error",{code:"payment_method_setup_unverified"})}catch(g){if(k())return;let G=g instanceof _.FloPayError&&g.code==="payment_method_setup_unverified";ee("payment_method",re(g,G?{retryable:!0}:{}))}finally{R.destroy()}},[ee,J]);(0,l.useEffect)(()=>{let u=!0,f=new ue.PaymentAPI((0,_.resolveBillingApiUrl)(o),{telemetry:a});B(null),M(!1),O(null),m(null),C(null);let k=new Set;return de.current=k,Ne(k),oe.current=!1,_e.current=!1,Re.current=!1,(async()=>{try{let{session:R,advertisement:g}=await Er(f,r,n);if(!u)return;let G={advertisement:g,customer:wr(R)};if(F){if(St(),R.status==="complete"){M(!0),B(G),J("payment_method");return}F.failed?Q("payment_method",{reason:"redirect_failed"}):fe({waitFirst:!0})}let K=g.card?await kr(f,R,r,n):null;if(!u)return;B(G),K&&(m(K),O(new ue.PciVaultCardCapture({sessionId:r,operation:"card_setup",telemetry:a})))}catch(R){if(!u)return;let g=re(R);oe.current=!0,C(g),H(()=>A.current.onError?.(g))}})(),()=>{u=!1,f.destroy()}},[o,n,F,Q,J,r,a,fe]),(0,l.useEffect)(()=>{if(!b)return;Y.current=!1;let u=b.on("submitting",()=>{Y.current=!0,T({status:"processing",wording:"card",message:null})}),f=b.on("complete",g=>{J("card",g.paymentMethod)}),k=b.on("decline",g=>{Q("card",{...g.declineReason?{reason:g.declineReason}:{},...g.message?{message:g.message}:{}})}),R=b.on("challenge_dismissed",()=>{T(null)});return()=>{u(),f(),k(),R()}},[b,Q,J]);let Ue=(0,l.useCallback)((u,f,k)=>{if(k.retryable){ee("payment_method",re(f,k));return}if(de.current.has(u))return;let R=new Set(de.current);R.add(u),de.current=R,Ne(R);let g=We.current?.advertisement,G=g?xe(g).some(K=>!R.has(K)):!1;ee("payment_method",re(f,{code:k.code,retryable:G}))},[ee]),Ye=(0,l.useMemo)(()=>({onSubmitting:()=>{Y.current=!0,T({status:"processing",wording:"payment_method",message:null})},onConfirmed:()=>{fe({waitFirst:!1})},onDeclined:u=>Q("payment_method",u),onValidation:u=>{H(()=>A.current.onValidation?.(u))},onAbandoned:()=>{Y.current=!1,T(null)}}),[Q,fe]),He=(0,l.useRef)(Ue);He.current=Ue;let Ge=(0,l.useRef)(new Map),me=u=>{let f=Ge.current.get(u);if(f)return f;let k=(R,g)=>He.current(u,R,g);return Ge.current.set(u,k),k},$e=j?(0,v.jsx)(et,{status:j.status,errorMessage:j.message,...bt(j.wording),successNote:null,...ze?{theme:ze}:{}}):null;if(w)return(0,v.jsx)("div",{role:"alert",children:w.message});if(!y||D)return(0,v.jsxs)(v.Fragment,{children:[$e,y?null:c]});let{advertisement:ae,customer:Nt}=y,je=(0,_.resolveBillingApiUrl)(o),Ke=a===void 0?{}:{telemetry:a},Wt=ae.stripe.filter(({method:u})=>!W.has(u)),ye=W.has("paypal")?null:ae.paypal;return(0,v.jsxs)(v.Fragment,{children:[$e,ae.card&&b&&I?.html?(0,v.jsx)("div",{"data-flopay-payment-method":"card",children:(0,v.jsx)(rt,{capture:b,html:I.html,messageToken:I.messageToken,expectedOrigin:I.expectedOrigin,theme:Vt,containerStyle:Dt,onReady:()=>{H(()=>A.current.onReady?.())},onValidation:u=>{H(()=>A.current.onValidation?.(u))},onError:u=>{u&&ee("card",re(new Error(u),{code:"card_setup_widget_failed",retryable:!0}))}})}):null,Wt.map(({method:u,publishableKey:f,currency:k})=>(0,v.jsx)("div",{"data-flopay-payment-method":u,children:(0,v.jsx)(Ce,{onFailed:me(u),children:(0,v.jsx)(l.Suspense,{fallback:null,children:(0,v.jsx)(e,{method:u,category:gt(u),publishableKey:f,currency:k,sessionId:r,nonce:n,billingApiUrl:je,...Ke,...N?{appearance:N.appearance}:{},...Ye,onFailed:me(u)})})})},u)),ye?(0,v.jsx)("div",{"data-flopay-payment-method":"paypal",children:(0,v.jsx)(Ce,{onFailed:me("paypal"),children:(0,v.jsx)(l.Suspense,{fallback:null,children:(0,v.jsx)(t,{clientId:ye.clientId,...ye.environment?{environment:ye.environment}:{},...ae.currency?{currency:ae.currency}:{},sessionId:r,nonce:n,billingApiUrl:je,customer:Nt,...Ke,...Ye,onFailed:me("paypal")})})})}):null]})}var It=require("react/jsx-runtime"),Wr={StripeSetupMethod:(0,De.lazy)(()=>Promise.resolve().then(()=>(Ft(),Mt)).then(e=>({default:e.StripeSetupMethod}))),PayPalSetupMethod:(0,De.lazy)(()=>Promise.resolve().then(()=>(Lt(),xt)).then(e=>({default:e.PayPalSetupMethod})))};function Ot(e){return(0,It.jsx)(Ct,{...e,branches:Wr})}0&&(module.exports={FloPayCardSetupError,FloPayPaymentMethodSetup});
@@ -1 +1 @@
1
- import{a as t}from"./chunk-R73QOXY5.mjs";import{j as a}from"./chunk-I4TPZWBS.mjs";import{lazy as o}from"react";import{jsx as P}from"react/jsx-runtime";var p={StripeSetupMethod:o(()=>import("./payment-method-setup-stripe-NCEEB7GN.mjs").then(e=>({default:e.StripeSetupMethod}))),PayPalSetupMethod:o(()=>import("./payment-method-setup-paypal-MWDJVYVO.mjs").then(e=>({default:e.PayPalSetupMethod})))};function y(e){return P(t,{...e,branches:p})}export{a as FloPayCardSetupError,y as FloPayPaymentMethodSetup};
1
+ import{a as t}from"./chunk-JUUKXJQQ.mjs";import{j as a}from"./chunk-I4TPZWBS.mjs";import{lazy as o}from"react";import{jsx as P}from"react/jsx-runtime";var p={StripeSetupMethod:o(()=>import("./payment-method-setup-stripe-NCEEB7GN.mjs").then(e=>({default:e.StripeSetupMethod}))),PayPalSetupMethod:o(()=>import("./payment-method-setup-paypal-FRRQW56L.mjs").then(e=>({default:e.PayPalSetupMethod})))};function y(e){return P(t,{...e,branches:p})}export{a as FloPayCardSetupError,y as FloPayPaymentMethodSetup};
@@ -0,0 +1 @@
1
+ import{a}from"./chunk-YSFYLEHB.mjs";import"./chunk-M7R46EDF.mjs";export{a as PayPalSetupMethod};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flopay/react",
3
- "version": "1.10.1",
3
+ "version": "1.10.2",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "publishConfig": {
@@ -39,8 +39,8 @@
39
39
  "@paypal/paypal-js": "^10.0.0",
40
40
  "@stripe/react-stripe-js": "^6.6.0",
41
41
  "@stripe/stripe-js": "^9.8.0",
42
- "@flopay/shared": "1.10.1",
43
- "@flopay/js": "1.10.1"
42
+ "@flopay/shared": "1.10.2",
43
+ "@flopay/js": "1.10.2"
44
44
  },
45
45
  "peerDependencies": {
46
46
  "react": ">=18.0.0",
@@ -1 +0,0 @@
1
- import{a as ce,b as pe,c as h,d as me,f as ye,i as fe,k as F}from"./chunk-I4TPZWBS.mjs";import{PaymentAPI as _e,PciVaultCardCapture as Ie}from"@flopay/js/card-setup";import{FloPayError as P,isCardSetupCheckoutSession as Le,resolveBillingApiUrl as H,resolveTheme as xe}from"@flopay/shared";import Ne,{Suspense as we,useCallback as L,useEffect as j,useMemo as T,useRef as g,useState as b}from"react";var Ve=new Set(["apple_pay","google_pay","link","paypal","amazon_pay"]);function Se(t){let i=t.data.stripe,r=Array.from(new Set(i?.enabledPaymentMethods??[])),a=t.data.paypal,o=a?.publishableKey?{clientId:a.publishableKey,...a.environment?{environment:String(a.environment)}:{}}:null,u=r.filter(f=>f!=="card"&&!(o&&f==="paypal"));return{card:r.includes("card"),stripe:i?.publishableKey&&u.length>0?{publishableKey:i.publishableKey,methods:u}:null,paypal:o}}function he(t){return t.card||t.stripe!==null||t.paypal!==null}function ve(t){return Ve.has(t)?"wallet":"apm"}var Oe=["setup_intent","setup_intent_client_secret","redirect_status"];function ge(){if(typeof window>"u")return null;let t=new URLSearchParams(window.location.search);return!t.has("setup_intent")||!t.has("redirect_status")?null:{failed:t.get("redirect_status")==="failed"}}function Pe(){if(typeof window>"u")return;let t=new URL(window.location.href),i=!1;for(let r of Oe)t.searchParams.has(r)&&(t.searchParams.delete(r),i=!0);i&&window.history.replaceState(window.history.state,"",t.toString())}function Ce(t){return t==="card"?{processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED"}:{processingLabel:"SAVING PAYMENT METHOD...",successLabel:"PAYMENT METHOD SAVED",errorLabel:"PAYMENT METHOD NOT SAVED"}}import{Fragment as Ee,jsx as p,jsxs as Re}from"react/jsx-runtime";var Be=15,Ue=2e3;function Ye(t){return{userId:t.customer?.id??"",email:t.customer?.email??""}}function q(t){return new Promise(i=>setTimeout(i,t))}async function Ge(t,i,r){if(!i.trim())throw new P("FloPayPaymentMethodSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!r.trim())throw new P("FloPayPaymentMethodSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let a=await t.getUnifiedCheckoutSession(i,r),o=a.data.session;if(!o||!Le(o))throw new P("FloPayPaymentMethodSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidPaymentMethodSetupSession",param:"sessionId"});let u=Se(a);if(!he(u))throw new P("FloPay: this setup session advertises no payment method.","validation_error",{code:"NoAdvertisedPaymentMethods",param:"sessionId"});return{session:o,advertisement:u}}async function Ke(t,i,r,a){let o=i.vault??null;if(o?.html?.trim()||(o=await t.getVaultCapture(r,a)),!o.html?.trim())throw new P("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});return o}var x=class extends Ne.Component{constructor(){super(...arguments);this.state={failed:!1}}static getDerivedStateFromError(){return{failed:!0}}componentDidCatch(r){this.props.onFailed(r,{code:"payment_method_setup_load_failed",retryable:!1})}render(){return this.state.failed?null:this.props.children}};function rt({branches:{StripeSetupMethod:t,PayPalSetupMethod:i},sessionId:r,nonce:a,billingApiUrl:o,telemetry:u,theme:f="modern-light",containerStyle:z,loading:Me=null,onReady:J,onComplete:Q,onDecline:X,onCancel:Z,onValidation:$,onError:ee}){let[N]=b(ge),[B,U]=b(null),[Ae,Y]=b(!1),[v,te]=b(null),[k,re]=b(null),[ne,ae]=b(null),[V,d]=b(null),S=g(!1),G=g(!1),M=g(!1),K=g(!1),W=g(0),O=g(0),_=g(!1),m=T(()=>typeof f=="object"?void 0:xe(f),[f]),Fe=T(()=>typeof f=="object"?f:m?fe({appearance:m.appearance,buttonsStyles:m.buttonsLayout,layout:"default"}):null,[m,f]),Te=T(()=>ce(m?.buttonsLayout.cardFormContainer,z),[m,z]),oe=T(()=>m?pe(m):void 0,[m]),l=g({sessionId:r,nonce:a,billingApiUrl:o,telemetry:u,onReady:J,onComplete:Q,onDecline:X,onCancel:Z,onValidation:$,onError:ee});l.current={sessionId:r,nonce:a,billingApiUrl:o,telemetry:u,onReady:J,onComplete:Q,onDecline:X,onCancel:Z,onValidation:$,onError:ee},j(()=>{_.current=!0;let e=W.current+1;return W.current=e,()=>{_.current=!1,O.current+=1,queueMicrotask(()=>{W.current===e&&(M.current||K.current||(K.current=!0,h(()=>{l.current.onCancel?.({status:"cancelled",sessionId:r})})))})}},[r]);let w=L((e,n)=>{M.current=!0,S.current=!1,d({status:"success",wording:e,message:null}),(async()=>(await q(600),!G.current&&(G.current=!0,h(()=>{l.current.onComplete?.({status:"succeeded",sessionId:l.current.sessionId,...n?{paymentMethod:n}:{}})}),_.current&&d(null))))()},[]),E=L((e,n)=>{M.current=!0,S.current=!1,d({status:"error",wording:e,message:n.message??null}),h(()=>{l.current.onDecline?.({status:"declined",sessionId:l.current.sessionId,...n.reason?{reason:n.reason}:{},...n.message?{message:n.message}:{}})}),(async()=>(await q(400),_.current&&d(null)))()},[]),A=L((e,n)=>{S.current?(S.current=!1,d({status:"error",wording:e,message:n.message}),setTimeout(()=>{_.current&&d(null)},400)):d(null),h(()=>l.current.onError?.(n))},[]),D=L(async e=>{let n=O.current+1;O.current=n;let c=()=>!_.current||n!==O.current;S.current=!0,d({status:"processing",wording:"payment_method",message:null});let y=new _e(H(l.current.billingApiUrl),{telemetry:l.current.telemetry});try{for(let s=0;s<Be;s+=1){if((s>0||e.waitFirst)&&await q(Ue),c())return;let R=await y.getUnifiedCheckoutSession(l.current.sessionId,l.current.nonce);if(c())return;let de=R.data.session?.status;if(de==="complete"){Y(!0),w("payment_method");return}if(de==="expired")throw new P("This setup session expired before the payment method was saved.","validation_error",{code:"payment_method_setup_expired"})}throw new P("The payment method could not be confirmed yet. Please try again.","api_error",{code:"payment_method_setup_unverified"})}catch(s){if(c())return;let R=s instanceof P&&s.code==="payment_method_setup_unverified";A("payment_method",F(s,R?{retryable:!0}:{}))}finally{y.destroy()}},[A,w]);j(()=>{let e=!0,n=new _e(H(o),{telemetry:u});return U(null),Y(!1),te(null),re(null),ae(null),M.current=!1,K.current=!1,G.current=!1,(async()=>{try{let{session:c,advertisement:y}=await Ge(n,r,a);if(!e)return;let s={advertisement:y,currency:c.currency,customer:Ye(c)};if(N){if(Pe(),c.status==="complete"){Y(!0),U(s),w("payment_method");return}N.failed?E("payment_method",{reason:"redirect_failed"}):D({waitFirst:!0})}let R=y.card?await Ke(n,c,r,a):null;if(!e)return;U(s),R&&(re(R),te(new Ie({sessionId:r,operation:"card_setup",telemetry:u})))}catch(c){if(!e)return;let y=F(c);M.current=!0,ae(y),h(()=>l.current.onError?.(y))}})(),()=>{e=!1,n.destroy()}},[o,a,N,E,w,r,u,D]),j(()=>{if(!v)return;S.current=!1;let e=v.on("submitting",()=>{S.current=!0,d({status:"processing",wording:"card",message:null})}),n=v.on("complete",s=>{w("card",s.paymentMethod)}),c=v.on("decline",s=>{E("card",{...s.declineReason?{reason:s.declineReason}:{},...s.message?{message:s.message}:{}})}),y=v.on("challenge_dismissed",()=>{d(null)});return()=>{e(),n(),c(),y()}},[v,E,w]);let I=T(()=>({onSubmitting:()=>{S.current=!0,d({status:"processing",wording:"payment_method",message:null})},onConfirmed:()=>{D({waitFirst:!1})},onDeclined:e=>E("payment_method",e),onFailed:(e,n)=>{A("payment_method",F(e,n))},onValidation:e=>{h(()=>l.current.onValidation?.(e))},onAbandoned:()=>{S.current=!1,d(null)}}),[E,A,D]),se=V?p(me,{status:V.status,errorMessage:V.message,...Ce(V.wording),successNote:null,...oe?{theme:oe}:{}}):null;if(ne)return p("div",{role:"alert",children:ne.message});if(!B||Ae)return Re(Ee,{children:[se,B?null:Me]});let{advertisement:C,currency:ie,customer:ke}=B,le=H(o),ue=u===void 0?{}:{telemetry:u};return Re(Ee,{children:[se,C.card&&v&&k?.html?p("div",{"data-flopay-payment-method":"card",children:p(ye,{capture:v,html:k.html,messageToken:k.messageToken,expectedOrigin:k.expectedOrigin,theme:Fe,containerStyle:Te,onReady:()=>{h(()=>l.current.onReady?.())},onValidation:e=>{h(()=>l.current.onValidation?.(e))},onError:e=>{e&&A("card",F(new Error(e),{code:"card_setup_widget_failed",retryable:!0}))}})}):null,C.stripe?.methods.map(e=>p("div",{"data-flopay-payment-method":e,children:p(x,{onFailed:I.onFailed,children:p(we,{fallback:null,children:p(t,{method:e,category:ve(e),publishableKey:C.stripe?.publishableKey??"",currency:ie,sessionId:r,nonce:a,billingApiUrl:le,...ue,...m?{appearance:m.appearance}:{},...I})})})},e)),C.paypal?p("div",{"data-flopay-payment-method":"paypal",children:p(x,{onFailed:I.onFailed,children:p(we,{fallback:null,children:p(i,{clientId:C.paypal.clientId,...C.paypal.environment?{environment:C.paypal.environment}:{},currency:ie,sessionId:r,nonce:a,billingApiUrl:le,customer:ke,...ue,...I})})})}):null]})}export{rt as a};
@@ -1 +0,0 @@
1
- import{a as T,g as A,i as R}from"./chunk-M7R46EDF.mjs";import{PaymentAPI as I}from"@flopay/js/card-setup";import{FloPayError as p,PAYPAL_VAULTED_PAYMENT_METHOD_TYPE as B}from"@flopay/shared";import{loadScript as x}from"@paypal/paypal-js";import{useEffect as D,useRef as C,useState as O}from"react";import{jsx as F}from"react/jsx-runtime";function z({clientId:u,environment:o,currency:d,sessionId:s,nonce:i,billingApiUrl:y,telemetry:f,customer:{userId:m,email:P},onSubmitting:h,onConfirmed:_,onFailed:v,onAbandoned:b}){let w=C(null),t=C({onSubmitting:h,onConfirmed:_,onFailed:v,onAbandoned:b});t.current={onSubmitting:h,onConfirmed:_,onFailed:v,onAbandoned:b};let[l]=O(()=>R().inAppBrowser);return D(()=>{let a=!0,k,c=new I(y,{telemetry:f}),g={userId:m,email:P};return(async()=>{try{let n=await x({clientId:u,currency:d.toUpperCase(),components:"buttons",...o==="sandbox"||o==="production"?{environment:o}:{}}),M=w.current;if(!a||!M)return;if(!n?.Buttons)throw new p("PayPal could not be loaded.","api_error",{code:"paypal_unavailable"});let E=n.Buttons({createVaultSetupToken:async()=>{t.current.onSubmitting();let e=await c.createSessionIntent(s,i,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:B,paymentMethodId:null,intentKind:"setup"});if(e.provider!=="paypal"||e.providerObjectType!=="setup_token")throw new p("The billing API did not return a PayPal setup token.","api_error",{code:"InvalidSessionIntentResponse"});return e.providerObjectId},onApprove:async e=>{let r=e.vaultSetupToken;if(!r)throw new p("PayPal approved without a setup token.","api_error",{code:"paypal_setup_token_missing"});let S=await c.processPayment(g.userId,{sessionId:s,nonce:i,paymentMethodCategory:"paypal",tokenizedData:{id:r,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:B},accountData:g});if(!S.ok)throw new p("PayPal could not be saved.","api_error",{code:"paypal_setup_failed",statusCode:S.status});a&&t.current.onConfirmed()},onCancel:()=>{a&&t.current.onAbandoned()},onError:e=>{if(!a)return;let{popupBlocked:r}=A(e,{inAppBrowser:l,handoffObserved:!1});t.current.onFailed(r?new Error(T("PayPal",!0,l)):e,{code:r?"popup_blocked":"paypal_setup_failed",retryable:!0})}});k=()=>E.close(),await E.render(M)}catch(n){if(!a)return;t.current.onFailed(n,{code:"paypal_unavailable",retryable:!0})}})(),()=>{a=!1,k?.().catch(()=>{}),c.destroy()}},[y,u,d,P,o,l,i,s,f,m]),F("div",{ref:w,"data-flopay-paypal-setup":""})}export{z as a};
@@ -1 +0,0 @@
1
- import{a}from"./chunk-U3PMJDD4.mjs";import"./chunk-M7R46EDF.mjs";export{a as PayPalSetupMethod};