@flopay/js 1.17.1 → 1.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as Y,b as G,c as J,d as ne,e as Q,f as Oe,g as Ue,h as X,i as ie,j as se,k as ae,l as le,m as ce,n as z,o as E,p as Le,q as Be,r as de,s as Z,t as ue}from"./chunk-H4BJFWDW.mjs";import{dropThirdPartyOnlyError as Kt}from"@flopay/shared";import{assertCaptureMethodEligible as Ne,buildProductPayload as qe,classifyTelemetryFailure as ze,FloPayError as O,foldIntoProducts as je,IDEMPOTENCY_IN_PROGRESS_CODE as Ve,IDEMPOTENCY_KEY_HEADER as $e,resolveIdempotencyKey as me,resolveSessionCurrency as Ke,SDK_VERSION as pe,telemetryStatusClass as ye,withTelemetryHttpDiagnostics as He}from"@flopay/shared";var te=5,fe=new WeakSet;function We(e){(typeof e=="object"&&e!==null||typeof e=="function")&&fe.add(e)}function Ye(e){return(typeof e=="object"&&e!==null||typeof e=="function")&&fe.has(e)}function Ge(e,t){let r=t?.error,o=Y(t?.code)??Y(r?.code)??`http_${e}`,a=G(t?.message)??G(r?.message)??Je(o,e);return new O(a,"api_error",{code:o,statusCode:e})}function Je(e,t){switch(e){case"CouponLimitExceeded":return`Too many coupon codes \u2014 a checkout session accepts at most ${te}.`;case"CouponCurrencyUnsupported":return"One of the applied coupons has no price configured for the cart currency.";default:return`Failed to create checkout session (HTTP ${t}).`}}async function ge(e,t,r){let{billingApiUrl:o,checkoutBaseUrl:a,items:i=[],subscriptions:d=[],products:s,account:c,successUrl:n,cancelUrl:l,checkoutMode:m="confirm",captureMethod:h,couponCodes:w=[],checkoutMetadata:p,tagsData:g,redirectParams:I={},setCookie:f=!0,clientId:x,currency:k,utmMetadata:R,idempotencyKey:U}=e,F=me(U);if(w.length>te)throw new O(`Too many coupon codes \u2014 a checkout session accepts at most ${te}.`,"validation_error",{code:"CouponLimitExceeded",param:"couponCodes"});let S=s??je(i,d);Ne({captureMethod:h,products:S});let _=Ke(k,i,d,S);if(!_)throw new O("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});let C={clientId:x,checkoutVersion:pe,successUrl:n,cancelUrl:l,currency:_,checkoutMode:m,products:S.map(v=>qe(v,_)),accountData:{userId:c.userId,firstName:c.firstName??null,lastName:c.lastName??null,email:c.email,country:c.country??null,gender:c.gender??null,city:c.city??null,state:c.state??null,zip:c.zip??null,addressLine1:c.addressLine1??null,addressLine2:c.addressLine2??null},couponCodes:w};h==="manual"&&(C.captureMethod=h),p!==void 0&&(C.checkoutMetadata=p),g&&(C.tagsData=g),R&&R.length>0&&(C.utmMetadata=R);let q=`${o.replace(/\/+$/,"")}/v1/checkouts/sessions`,L={"Content-Type":"application/json"};F&&(L[$e]=F);let b,T,B={method:"POST",headers:L,body:JSON.stringify(C),signal:t},P;try{r?.startAttempt(),P=await fetch(q,B)}catch(v){throw We(v),v}try{r?.record(P.status)}catch{}b=P.status;try{T=await P.json()}catch{}if(b>=400)throw He(Ge(b,T),P);if(b===201){let v=T?.data?.uuid,D=T?.data?.nonce;if(!v)throw new Error("Checkout session created but no UUID was returned by the billing API");if(!D)throw new O("Checkout session created but no `nonce` was returned by the billing API. Upgrade the billing service to TeamFloPay/backend#640 or later.","api_error",{code:"MissingCheckoutSessionToken"});(S.length>0||_)&&Q(v,{currency:_,products:S.map(u=>({code:u.code??u.providerItemId??u.providerPlanId,type:u.type,name:u.name??u.itemName??u.providerItemName??u.subscriptionName??u.providerPlanName??null,totalAmount:u.totalAmount,overrideAmount:u.overrideAmount,currency:u.currency??_}))});let y=new URL(`${a.replace(/\/+$/,"")}/secure`);y.searchParams.set("id",v);for(let[u,A]of Object.entries(I))y.searchParams.set(u,A);if(f&&typeof window<"u"&&typeof document<"u"){let u=JSON.stringify({origin_url:l}),A=window.location.hostname.split(".").slice(-2).join(".");document.cookie=`checkout_data=${encodeURIComponent(u)}; domain=.${A}; path=/; max-age=3600; SameSite=Lax; Secure;`,document.cookie=`flopay_checkout_token=${encodeURIComponent(D)}; domain=.${A}; path=/; max-age=3600; SameSite=Lax; Secure;`}return typeof window<"u"&&(window.location.href=y.toString()),{status:201,redirectUrl:y.toString(),nonce:D}}return b===204?(typeof window<"u"&&(window.location.href=n),{status:204}):{status:b}}async function Qe(e){let t=Ce(e),r=he(t),o=J(e.timeoutMs);try{let a=await ge(e,o.signal,r);return r.commit(),ve(t,a),a}catch(a){throw r.commit(),j(t,a),a}finally{o.clear(),M(t.reporter)}}function he(e){let t=!1,r=e.startedAt,o;return{startAttempt(){r=e.reporter.now()},record(a){o={status:a,durationMs:Math.max(0,e.reporter.now()-r),attempt:e.attempt}},commit(){if(t||!o)return;t=!0;let a=ye(o.status);e.reporter.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:a,attempt:o.attempt}),e.reporter.performance({stage:"session_first_byte",durationMs:o.durationMs,durationMode:"machine",requestCategory:"session_create",statusClass:a,attempt:o.attempt})}}}function Ce(e){let t=new E({billingApiUrl:e.billingApiUrl,sdkVersion:pe,enabled:e.telemetry!==!1}),r=t.now();return t.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"}),{reporter:t,startedAt:r,attempt:0}}function ve(e,t){let r=ye(t.status);e.reporter.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:r}),e.reporter.performance({stage:"session_create",durationMs:e.reporter.now()-e.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:r,attempt:e.attempt})}function j(e,t){let{reporter:r}=e,o=ze(t,"CHECKOUT_SESSION_CREATE_FAILED");if(r.performance({stage:"session_create",durationMs:r.now()-e.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:o.statusClass,attempt:e.attempt}),t instanceof O&&t.type==="validation_error"){r.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"});return}if(o.statusClass==="4xx"){r.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create",statusClass:"4xx"});return}r.error({...o,stage:"session_create",requestCategory:"session_create"})}function M(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}async function Xe(e){let{maxRetries:t=2,...r}=e,o=Ce(e),a=he(o);if(!Number.isFinite(t)||!Number.isInteger(t)||t<0||t>=3)throw o.reporter.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),M(o.reporter),new Error(`Number of retries must be an integer between 0 and ${2}`);let i={...r,idempotencyKey:me(r.idempotencyKey)},d=J(r.timeoutMs),s;for(let c=0;c<=t;c++){o.attempt=c;try{let n=await ge(i,d.signal,a);return a.commit(),ve(o,n),d.clear(),M(o.reporter),n}catch(n){s=n;let l=n instanceof Error&&n.name==="AbortError",m=Ye(n),h=n instanceof O&&n.code===Ve;if((l||m||h)&&!d.signal.aborted&&c<t){o.reporter.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:c+1});try{await ne(c,d.signal)}catch(w){throw a.commit(),j(o,w),d.clear(),M(o.reporter),w}continue}throw a.commit(),j(o,n),d.clear(),M(o.reporter),n}}throw a.commit(),j(o,s),d.clear(),M(o.reporter),s??new Error("Unknown error during checkout session creation")}import{classifyTelemetryFailure as Ze,FloPayError as V,resolveBillingApiUrl as Se,SDK_VERSION as et}from"@flopay/shared";var we=Symbol.for("@flopay/js.telemetry.bridge.v1");function _e(e,t,r){let o=()=>t?.now()??r();Object.defineProperty(e,we,{configurable:!1,enumerable:!1,writable:!1,value:{error:i=>t?.error(i),log:i=>t?.log(i),performance:i=>t?.performance(i),terminal:i=>t?.terminal(i),now:o,elapsed:i=>Math.max(0,o()-i),setCheckoutContext:i=>t?.setCheckoutContext(i),beginCheckout:(i={})=>t?.beginCheckout(i)??o(),disable:()=>t?.disable(),subscribe:i=>t?.subscribe(i)??(()=>{}),flush:()=>t?.flush()??Promise.resolve()}})}function be(e){return e[we]}var $=class{now(){return this.telemetryReporter?.now?.()??z()}constructor(t,r,o){this.provider=t,this.config=r,this.telemetryReporter=o??new E({billingApiUrl:Se(r.billingApiUrl),sdkVersion:et,enabled:r.telemetry!==!1}),_e(this,this.telemetryReporter,z)}cardCapture(t){return this.telemetryReporter?.log({name:"vault.capture.requested",stage:"vault_request",provider:"pcivault",paymentMethodCategory:"card"}),this.telemetryReporter?ue({sessionId:t?.sessionId,captureMethod:t?.captureMethod,cardFieldsTimeoutMs:t?.cardFieldsTimeoutMs},this.telemetryReporter):new Z({sessionId:t?.sessionId,captureMethod:t?.captureMethod,cardFieldsTimeoutMs:t?.cardFieldsTimeoutMs,telemetry:!1})}async retrieveSession(t,r){if(!t)throw new V("sessionId is required to retrieve a session.","validation_error",{param:"sessionId"});let o=await this.retrieveUnifiedSession(t,r);if(!o.data.session)throw new V("Session not found","api_error");return o.data.session}async retrieveUnifiedSession(t,r){if(!t)throw new V("sessionId is required.","validation_error",{param:"sessionId"});let o=Se(r??this.config.billingApiUrl),a=this.now();this.telemetryReporter?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let i,d,s=n=>{if(i===void 0)return;let l=i,m=d;i=void 0,d=void 0,this.telemetryReporter?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:n,attempt:m}),this.telemetryReporter?.performance({stage:"session_first_byte",durationMs:l,durationMode:"machine",requestCategory:"session_read",statusClass:n,attempt:m})},c=de(o,{now:()=>this.telemetryReporter?.now()??z(),onFirstByte:(n,l)=>{i=n,d=l},onRetry:(n,l)=>{this.telemetryReporter?.log({name:"operation.retry",stage:n==="session_read"?"session_read":"processing",requestCategory:n,attempt:l})}});try{let n=await c.getUnifiedCheckoutSession(t);return s("2xx"),this.telemetryReporter?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:"2xx"}),this.telemetryReporter?.log({name:"checkout.data.ready",stage:"checkout_data_ready"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-a,durationMode:"machine",requestCategory:"session_read",statusClass:"2xx"}),n}catch(n){let l=Ze(n,n instanceof V&&n.code==="checkout_processing_timeout"?"REQUEST_TIMEOUT":"NETWORK_REQUEST_FAILED");throw s(l.statusClass),this.telemetryReporter?.error({...l,stage:"session_read",provider:"flo",paymentMethodCategory:"unknown"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-a,durationMode:"machine",requestCategory:"session_read",statusClass:l.statusClass}),n}}getRawProvider(){return this.provider.getRawProvider()}destroy(){this.telemetryReporter?.log({name:"checkout.unmount",stage:"unmount"}),this.telemetryReporter?.destroy(),this.provider.destroy()}};function Pe(e,t,r){let o=$;return new o(e,t,r)}import{FloPayError as nt,resolveBillingApiUrl as re,SDK_VERSION as Te}from"@flopay/shared";import{FloPayError as Ae}from"@flopay/shared";import{loadStripe as tt}from"@stripe/stripe-js";import{toStripeAppearance as rt,toStripeAppearanceTheme as ot}from"@flopay/shared";var ke=new WeakSet;function Re(e){return e instanceof Ae&&ke.has(e)}var N=class{constructor(){this.name="stripe";this.stripe=null}async initialize(t){if(typeof window>"u")return;let r=await tt(t.publishableKey,{locale:t.locale??"auto"});if(!r){let o=new Ae("Failed to initialize Stripe. Check your publishable key.","authentication_error");throw ke.add(o),o}this.stripe=r}getRawProvider(){return this.stripe}destroy(){this.stripe=null}};var Ee=new Map;function oe(e){return Array.isArray(e)?e.map(oe):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,oe(r)])):e}function it(e,t){return JSON.stringify([e,re(t?.billingApiUrl),t?.telemetry!==!1,t?.locale??"auto",t?.apiVersion??null,oe(t?.appearance??null)])}var K=new Map;async function st(e,t){if(!e){let s=new E({billingApiUrl:re(t?.billingApiUrl),sdkVersion:Te,enabled:t?.telemetry!==!1});throw s.error({errorCode:"CONFIGURATION_INVALID",stage:"sdk_initialize",paymentMethodCategory:"unknown"}),s.flush().catch(()=>{}).finally(()=>s.destroy()),new nt("A publishable key is required to initialize FloPay.","validation_error",{param:"publishableKey"})}let r=it(e,t),o=Ee.get(r);if(o)return t?.telemetry!==!1&&be(o)?.log({name:"sdk.cache.hit",stage:"sdk_initialize"}),o;let a=K.get(r);if(a)return a;let i={...t,publishableKey:e},d=(async()=>{let s=new E({billingApiUrl:re(i.billingApiUrl),sdkVersion:Te,enabled:i.telemetry!==!1}),c=s.now();s.log({name:"sdk.initialize.started",stage:"sdk_initialize"}),s.log({name:"sdk.cache.miss",stage:"sdk_initialize"}),s.log({name:"provider.load.started",stage:"provider_load",provider:"stripe"});let n=new N,l=s.now();try{await n.initialize(i)}catch(w){throw s.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:Re(w)?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"unknown"}),s.destroy(),w}let m=s.now();s.log({name:"provider.ready",stage:"provider_ready",provider:"stripe"}),s.log({name:"provider.availability.checked",stage:"provider_ready",provider:"stripe"}),s.log({name:"sdk.initialize.ready",stage:"sdk_initialize"}),s.performance({stage:"sdk_initialize",durationMs:m-c,durationMode:"machine",provider:"stripe"}),s.performance({stage:"provider_ready",durationMs:m-l,durationMode:"machine",provider:"stripe"});let h=Pe(n,i,s);return Ee.set(r,h),h})();K.set(r,d);try{return await d}finally{K.get(r)===d&&K.delete(r)}}import{FloPayError as W,THREE_DS_CHALLENGE_WINDOW_MS as xe}from"@flopay/shared";var at=4,lt=1e3,ct=1e3,dt=15e3;function ut(e){let t=!!e?.gateways?.stripe,r=!!e?.gateways?.worldpayCorporateGateway;return t===r?"unknown":t?"stripe":"worldpay"}function mt(e,t,r){try{return typeof e?.beginThreeDsChallenge!="function"?void 0:e.beginThreeDsChallenge(t,{provider:ut(r)})}catch{return}}function H(e){return new W("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function Fe(){return new W("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function De(e){return e.replace(/\/+$/,"")}function pt(e){return e.status==="succeeded"||e.status==="authorized"||e.status==="declined"}function yt(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",r=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":case"authorized":case"pending":case"timeout":return{status:t,providerIntentId:r};case"declined":return{status:"declined",providerIntentId:r,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:r,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}async function Me(e){if(typeof document>"u"||typeof window>"u")throw new W("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});let t=X(e.telemetry);t.record("handoff_planned");let r=ie(e.nextActionRedirectUrl);r==="missing"?t.record("action_missing",{reason:"missing_url"}):r==="invalid"&&t.record("action_invalid",{reason:"invalid_url"});let o=p=>{let g=se(p);if(g==="buyer_cancel"){t.record("cancel_requested",{reason:g,evidenceBasis:"signal_reason"}),t.terminal("cancel",{reason:g,evidenceBasis:"signal_reason"});return}t.record("abort_observed",{reason:g,evidenceBasis:"signal_reason"}),t.terminal("abort",{reason:g,evidenceBasis:"signal_reason"})},a=p=>{(p.status==="succeeded"||p.status==="authorized"||p.status==="declined"||p.status==="timeout")&&t.reconcile(p.status)};if(e.signal?.aborted)throw o(e.signal.reason),H();let i=`${De(e.billingApiUrl)}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,d=async()=>{let p=new AbortController,g=()=>p.abort();e.signal?.aborted?p.abort():e.signal?.addEventListener("abort",g);let I=window.setTimeout(()=>p.abort(),dt);try{let f=await fetch(i,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json",...t.attemptId?{"x-flopay-challenge-attempt":t.attemptId}:{}},body:"{}",signal:p.signal});if(!f.ok)return{status:"unknown"};let x=await f.json().catch(()=>null),k=yt(x);return a(k),k}catch{return{status:"unknown"}}finally{window.clearTimeout(I),e.signal?.removeEventListener("abort",g)}},s,c=()=>e.pollCompletionEndpoint!==!1?d():(s??(s=d()),s),n=document.activeElement instanceof HTMLElement?document.activeElement:null,l=document.createElement("div");l.setAttribute("data-flopay-auto-3ds-overlay","1"),l.setAttribute("role","dialog"),l.setAttribute("aria-modal","true"),l.setAttribute("aria-label","Card authentication"),l.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let m=document.createElement("iframe");m.setAttribute("title","Card authentication"),m.setAttribute("allow","payment"),m.tabIndex=0,m.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";");let h=null;try{h=new URL(e.billingApiUrl,window.location.href).origin}catch{h=null}let w=ce(e.nextActionRedirectUrl);try{let p=await new Promise((g,I)=>{let f=!1,x=0,k=0,R=0,U=!1,F=!1,S=!1,_=0,C=()=>{window.clearTimeout(x),window.clearInterval(k),window.clearTimeout(R),window.removeEventListener("message",v),window.removeEventListener("pagehide",L),document.removeEventListener("securitypolicyviolation",b),m.removeEventListener("load",T),e.signal?.removeEventListener("abort",B)},q=async()=>{if(!(f||U)){U=!0;try{let y=await c();if(f||!pt(y))return;f=!0,C(),t.terminal("status_poll",{evidenceBasis:"server_status"}),g(y)}finally{U=!1}}},L=()=>{t.record("pagehide_observed",{evidenceBasis:"page_lifecycle_event"})},b=y=>{if(S)return;let u=le(y,w);u&&(S=!0,t.record("policy_violation",{reason:u,evidenceBasis:"parent_csp_event"}))},T=()=>{F||(F=!0,t.record("iframe_load",{evidenceBasis:"iframe_load_event"})),e.pollCompletionEndpoint!==!1&&(window.clearTimeout(R),R=window.setTimeout(()=>{q()},250))},B=()=>{f||(f=!0,C(),o(e.signal?.reason),I(H()))},P=y=>{f||_>=at||(_+=1,t.record("return_rejected",{reason:y,evidenceBasis:"message_origin_check"}))},v=y=>{let u=y.data,A=!!u&&typeof u=="object"&&u.source==="flopay-vault-3ds-return";if(y.source!==m.contentWindow){A&&P("untrusted_source");return}if(h&&y.origin!==h){A&&P("untrusted_origin");return}A&&(f||(f=!0,C(),t.record("trusted_return",{evidenceBasis:"message_origin_check"}),t.terminal("trusted_return",{evidenceBasis:"message_origin_check"}),g(null)))};x=window.setTimeout(()=>{f||(f=!0,C(),F||t.record("load_unconfirmed",{evidenceBasis:"no_load_signal"}),t.record("timer_expired",{reason:"window_elapsed",evidenceBasis:"timer"}),t.terminal("timer",{reason:"window_elapsed",evidenceBasis:"timer"}),I(Fe()))},xe),e.pollCompletionEndpoint!==!1&&(k=window.setInterval(()=>{q()},ct)),m.addEventListener("load",T),window.addEventListener("message",v),window.addEventListener("pagehide",L),document.addEventListener("securitypolicyviolation",b),e.signal?.addEventListener("abort",B),m.src=e.nextActionRedirectUrl,t.record("render_attempted");try{l.appendChild(m),document.body.appendChild(l)}catch(y){throw f=!0,C(),t.record("render_failed"),y}t.record("container_attached"),t.record("navigation_assigned");let D=ae(l);D&&t.record("container_visibility",{reason:D,evidenceBasis:"parent_computed_style"}),m.focus(),e.signal?.aborted&&B()});return p||await c()}finally{l.parentNode?.removeChild(l),t.record("teardown"),n?.isConnected&&n.focus()}}function Ie(e,t){try{let r=t.data.session?.status;r==="complete"?e.reconcile("succeeded"):r==="authorized"&&e.reconcile("authorized")}catch{}}function ft(e){return new W("Card was declined.","api_error",{code:e.declineReason??"authorization_declined",...e.gatewayDeclineReason?{declineCode:e.gatewayDeclineReason}:{}})}async function gt(e,t){let r=`${De(e.billingApiUrl)}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/status`,o=new AbortController,a=new AbortController,i=()=>{o.abort(e.signal?.reason),a.abort(e.signal?.reason)};e.signal?.aborted?i():e.signal?.addEventListener("abort",i,{once:!0});let d=X(e.telemetry),s=Me({billingApiUrl:e.billingApiUrl,sessionId:e.sessionId,nonce:e.nonce,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:o.signal,pollCompletionEndpoint:!1,...e.telemetry?{telemetry:e.telemetry}:{}}),c=t.waitForCheckoutSessionCompletion(e.sessionId,{initialDelayMs:lt,nonce:e.nonce,statusUrl:r,continueAfterActionRequired:!0,timeoutMs:xe+15e3,signal:a.signal,...d.attemptId?{challengeAttemptId:d.attemptId}:{}});c.catch(()=>{}),s.catch(()=>{});try{let n=await Promise.race([s,c]);if("data"in n)return d.terminal("status_poll",{evidenceBasis:"server_status"}),Ie(d,n),n;if(n.status==="declined")throw(e.createDeclineError??ft)(n);if(n.status==="timeout")throw Fe();let l=await c;return Ie(d,l),l}catch(n){throw e.signal?.aborted||n instanceof Error&&n.name==="AbortError"?H(n):n}finally{e.signal?.removeEventListener("abort",i),o.abort(),a.abort()}}export{$ as FloPay,Be as PaymentAPI,Z as PciVaultCardCapture,Le as SESSION_CREATE_TELEMETRY,N as StripeAdapter,mt as beginSavedCardChallengeTelemetry,Q as cacheSessionDisplayData,Ue as clearSessionDisplayData,gt as completeSavedCardNextAction,Qe as createCheckoutSession,Xe as createCheckoutSessionWithRetries,H as createSavedCardActionAbortedError,Kt as dropThirdPartyOnlyError,Oe as getSessionDisplayData,st as loadFloPay,Me as runSavedCardChallenge,rt as toStripeAppearance,ot as toStripeAppearanceTheme};
|
|
1
|
+
import{a as Y,b as G,c as J,d as ne,e as Q,f as Oe,g as Ue,h as X,i as ie,j as se,k as ae,l as le,m as ce,n as z,o as E,p as Le,q as Be,r as de,s as Z,t as ue}from"./chunk-WTVYMDK5.mjs";import{dropThirdPartyOnlyError as Kt}from"@flopay/shared";import{assertCaptureMethodEligible as Ne,buildProductPayload as qe,classifyTelemetryFailure as ze,FloPayError as O,foldIntoProducts as je,IDEMPOTENCY_IN_PROGRESS_CODE as Ve,IDEMPOTENCY_KEY_HEADER as $e,resolveIdempotencyKey as me,resolveSessionCurrency as Ke,SDK_VERSION as pe,telemetryStatusClass as ye,withTelemetryHttpDiagnostics as He}from"@flopay/shared";var te=5,fe=new WeakSet;function We(e){(typeof e=="object"&&e!==null||typeof e=="function")&&fe.add(e)}function Ye(e){return(typeof e=="object"&&e!==null||typeof e=="function")&&fe.has(e)}function Ge(e,t){let r=t?.error,o=Y(t?.code)??Y(r?.code)??`http_${e}`,a=G(t?.message)??G(r?.message)??Je(o,e);return new O(a,"api_error",{code:o,statusCode:e})}function Je(e,t){switch(e){case"CouponLimitExceeded":return`Too many coupon codes \u2014 a checkout session accepts at most ${te}.`;case"CouponCurrencyUnsupported":return"One of the applied coupons has no price configured for the cart currency.";default:return`Failed to create checkout session (HTTP ${t}).`}}async function ge(e,t,r){let{billingApiUrl:o,checkoutBaseUrl:a,items:i=[],subscriptions:d=[],products:s,account:c,successUrl:n,cancelUrl:l,checkoutMode:m="confirm",captureMethod:h,couponCodes:w=[],checkoutMetadata:p,tagsData:g,redirectParams:I={},setCookie:f=!0,clientId:x,currency:k,utmMetadata:R,idempotencyKey:U}=e,F=me(U);if(w.length>te)throw new O(`Too many coupon codes \u2014 a checkout session accepts at most ${te}.`,"validation_error",{code:"CouponLimitExceeded",param:"couponCodes"});let S=s??je(i,d);Ne({captureMethod:h,products:S});let _=Ke(k,i,d,S);if(!_)throw new O("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});let C={clientId:x,checkoutVersion:pe,successUrl:n,cancelUrl:l,currency:_,checkoutMode:m,products:S.map(v=>qe(v,_)),accountData:{userId:c.userId,firstName:c.firstName??null,lastName:c.lastName??null,email:c.email,country:c.country??null,gender:c.gender??null,city:c.city??null,state:c.state??null,zip:c.zip??null,addressLine1:c.addressLine1??null,addressLine2:c.addressLine2??null},couponCodes:w};h==="manual"&&(C.captureMethod=h),p!==void 0&&(C.checkoutMetadata=p),g&&(C.tagsData=g),R&&R.length>0&&(C.utmMetadata=R);let q=`${o.replace(/\/+$/,"")}/v1/checkouts/sessions`,L={"Content-Type":"application/json"};F&&(L[$e]=F);let b,T,B={method:"POST",headers:L,body:JSON.stringify(C),signal:t},P;try{r?.startAttempt(),P=await fetch(q,B)}catch(v){throw We(v),v}try{r?.record(P.status)}catch{}b=P.status;try{T=await P.json()}catch{}if(b>=400)throw He(Ge(b,T),P);if(b===201){let v=T?.data?.uuid,D=T?.data?.nonce;if(!v)throw new Error("Checkout session created but no UUID was returned by the billing API");if(!D)throw new O("Checkout session created but no `nonce` was returned by the billing API. Upgrade the billing service to TeamFloPay/backend#640 or later.","api_error",{code:"MissingCheckoutSessionToken"});(S.length>0||_)&&Q(v,{currency:_,products:S.map(u=>({code:u.code??u.providerItemId??u.providerPlanId,type:u.type,name:u.name??u.itemName??u.providerItemName??u.subscriptionName??u.providerPlanName??null,totalAmount:u.totalAmount,overrideAmount:u.overrideAmount,currency:u.currency??_}))});let y=new URL(`${a.replace(/\/+$/,"")}/secure`);y.searchParams.set("id",v);for(let[u,A]of Object.entries(I))y.searchParams.set(u,A);if(f&&typeof window<"u"&&typeof document<"u"){let u=JSON.stringify({origin_url:l}),A=window.location.hostname.split(".").slice(-2).join(".");document.cookie=`checkout_data=${encodeURIComponent(u)}; domain=.${A}; path=/; max-age=3600; SameSite=Lax; Secure;`,document.cookie=`flopay_checkout_token=${encodeURIComponent(D)}; domain=.${A}; path=/; max-age=3600; SameSite=Lax; Secure;`}return typeof window<"u"&&(window.location.href=y.toString()),{status:201,redirectUrl:y.toString(),nonce:D}}return b===204?(typeof window<"u"&&(window.location.href=n),{status:204}):{status:b}}async function Qe(e){let t=Ce(e),r=he(t),o=J(e.timeoutMs);try{let a=await ge(e,o.signal,r);return r.commit(),ve(t,a),a}catch(a){throw r.commit(),j(t,a),a}finally{o.clear(),M(t.reporter)}}function he(e){let t=!1,r=e.startedAt,o;return{startAttempt(){r=e.reporter.now()},record(a){o={status:a,durationMs:Math.max(0,e.reporter.now()-r),attempt:e.attempt}},commit(){if(t||!o)return;t=!0;let a=ye(o.status);e.reporter.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:a,attempt:o.attempt}),e.reporter.performance({stage:"session_first_byte",durationMs:o.durationMs,durationMode:"machine",requestCategory:"session_create",statusClass:a,attempt:o.attempt})}}}function Ce(e){let t=new E({billingApiUrl:e.billingApiUrl,sdkVersion:pe,enabled:e.telemetry!==!1}),r=t.now();return t.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"}),{reporter:t,startedAt:r,attempt:0}}function ve(e,t){let r=ye(t.status);e.reporter.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:r}),e.reporter.performance({stage:"session_create",durationMs:e.reporter.now()-e.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:r,attempt:e.attempt})}function j(e,t){let{reporter:r}=e,o=ze(t,"CHECKOUT_SESSION_CREATE_FAILED");if(r.performance({stage:"session_create",durationMs:r.now()-e.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:o.statusClass,attempt:e.attempt}),t instanceof O&&t.type==="validation_error"){r.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"});return}if(o.statusClass==="4xx"){r.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create",statusClass:"4xx"});return}r.error({...o,stage:"session_create",requestCategory:"session_create"})}function M(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}async function Xe(e){let{maxRetries:t=2,...r}=e,o=Ce(e),a=he(o);if(!Number.isFinite(t)||!Number.isInteger(t)||t<0||t>=3)throw o.reporter.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),M(o.reporter),new Error(`Number of retries must be an integer between 0 and ${2}`);let i={...r,idempotencyKey:me(r.idempotencyKey)},d=J(r.timeoutMs),s;for(let c=0;c<=t;c++){o.attempt=c;try{let n=await ge(i,d.signal,a);return a.commit(),ve(o,n),d.clear(),M(o.reporter),n}catch(n){s=n;let l=n instanceof Error&&n.name==="AbortError",m=Ye(n),h=n instanceof O&&n.code===Ve;if((l||m||h)&&!d.signal.aborted&&c<t){o.reporter.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:c+1});try{await ne(c,d.signal)}catch(w){throw a.commit(),j(o,w),d.clear(),M(o.reporter),w}continue}throw a.commit(),j(o,n),d.clear(),M(o.reporter),n}}throw a.commit(),j(o,s),d.clear(),M(o.reporter),s??new Error("Unknown error during checkout session creation")}import{classifyTelemetryFailure as Ze,FloPayError as V,resolveBillingApiUrl as Se,SDK_VERSION as et}from"@flopay/shared";var we=Symbol.for("@flopay/js.telemetry.bridge.v1");function _e(e,t,r){let o=()=>t?.now()??r();Object.defineProperty(e,we,{configurable:!1,enumerable:!1,writable:!1,value:{error:i=>t?.error(i),log:i=>t?.log(i),performance:i=>t?.performance(i),terminal:i=>t?.terminal(i),now:o,elapsed:i=>Math.max(0,o()-i),setCheckoutContext:i=>t?.setCheckoutContext(i),beginCheckout:(i={})=>t?.beginCheckout(i)??o(),disable:()=>t?.disable(),subscribe:i=>t?.subscribe(i)??(()=>{}),flush:()=>t?.flush()??Promise.resolve()}})}function be(e){return e[we]}var $=class{now(){return this.telemetryReporter?.now?.()??z()}constructor(t,r,o){this.provider=t,this.config=r,this.telemetryReporter=o??new E({billingApiUrl:Se(r.billingApiUrl),sdkVersion:et,enabled:r.telemetry!==!1}),_e(this,this.telemetryReporter,z)}cardCapture(t){return this.telemetryReporter?.log({name:"vault.capture.requested",stage:"vault_request",provider:"pcivault",paymentMethodCategory:"card"}),this.telemetryReporter?ue({sessionId:t?.sessionId,captureMethod:t?.captureMethod,cardFieldsTimeoutMs:t?.cardFieldsTimeoutMs},this.telemetryReporter):new Z({sessionId:t?.sessionId,captureMethod:t?.captureMethod,cardFieldsTimeoutMs:t?.cardFieldsTimeoutMs,telemetry:!1})}async retrieveSession(t,r){if(!t)throw new V("sessionId is required to retrieve a session.","validation_error",{param:"sessionId"});let o=await this.retrieveUnifiedSession(t,r);if(!o.data.session)throw new V("Session not found","api_error");return o.data.session}async retrieveUnifiedSession(t,r){if(!t)throw new V("sessionId is required.","validation_error",{param:"sessionId"});let o=Se(r??this.config.billingApiUrl),a=this.now();this.telemetryReporter?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let i,d,s=n=>{if(i===void 0)return;let l=i,m=d;i=void 0,d=void 0,this.telemetryReporter?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:n,attempt:m}),this.telemetryReporter?.performance({stage:"session_first_byte",durationMs:l,durationMode:"machine",requestCategory:"session_read",statusClass:n,attempt:m})},c=de(o,{now:()=>this.telemetryReporter?.now()??z(),onFirstByte:(n,l)=>{i=n,d=l},onRetry:(n,l)=>{this.telemetryReporter?.log({name:"operation.retry",stage:n==="session_read"?"session_read":"processing",requestCategory:n,attempt:l})}});try{let n=await c.getUnifiedCheckoutSession(t);return s("2xx"),this.telemetryReporter?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:"2xx"}),this.telemetryReporter?.log({name:"checkout.data.ready",stage:"checkout_data_ready"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-a,durationMode:"machine",requestCategory:"session_read",statusClass:"2xx"}),n}catch(n){let l=Ze(n,n instanceof V&&n.code==="checkout_processing_timeout"?"REQUEST_TIMEOUT":"NETWORK_REQUEST_FAILED");throw s(l.statusClass),this.telemetryReporter?.error({...l,stage:"session_read",provider:"flo",paymentMethodCategory:"unknown"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-a,durationMode:"machine",requestCategory:"session_read",statusClass:l.statusClass}),n}}getRawProvider(){return this.provider.getRawProvider()}destroy(){this.telemetryReporter?.log({name:"checkout.unmount",stage:"unmount"}),this.telemetryReporter?.destroy(),this.provider.destroy()}};function Pe(e,t,r){let o=$;return new o(e,t,r)}import{FloPayError as nt,resolveBillingApiUrl as re,SDK_VERSION as Te}from"@flopay/shared";import{FloPayError as Ae}from"@flopay/shared";import{loadStripe as tt}from"@stripe/stripe-js";import{toStripeAppearance as rt,toStripeAppearanceTheme as ot}from"@flopay/shared";var ke=new WeakSet;function Re(e){return e instanceof Ae&&ke.has(e)}var N=class{constructor(){this.name="stripe";this.stripe=null}async initialize(t){if(typeof window>"u")return;let r=await tt(t.publishableKey,{locale:t.locale??"auto"});if(!r){let o=new Ae("Failed to initialize Stripe. Check your publishable key.","authentication_error");throw ke.add(o),o}this.stripe=r}getRawProvider(){return this.stripe}destroy(){this.stripe=null}};var Ee=new Map;function oe(e){return Array.isArray(e)?e.map(oe):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,oe(r)])):e}function it(e,t){return JSON.stringify([e,re(t?.billingApiUrl),t?.telemetry!==!1,t?.locale??"auto",t?.apiVersion??null,oe(t?.appearance??null)])}var K=new Map;async function st(e,t){if(!e){let s=new E({billingApiUrl:re(t?.billingApiUrl),sdkVersion:Te,enabled:t?.telemetry!==!1});throw s.error({errorCode:"CONFIGURATION_INVALID",stage:"sdk_initialize",paymentMethodCategory:"unknown"}),s.flush().catch(()=>{}).finally(()=>s.destroy()),new nt("A publishable key is required to initialize FloPay.","validation_error",{param:"publishableKey"})}let r=it(e,t),o=Ee.get(r);if(o)return t?.telemetry!==!1&&be(o)?.log({name:"sdk.cache.hit",stage:"sdk_initialize"}),o;let a=K.get(r);if(a)return a;let i={...t,publishableKey:e},d=(async()=>{let s=new E({billingApiUrl:re(i.billingApiUrl),sdkVersion:Te,enabled:i.telemetry!==!1}),c=s.now();s.log({name:"sdk.initialize.started",stage:"sdk_initialize"}),s.log({name:"sdk.cache.miss",stage:"sdk_initialize"}),s.log({name:"provider.load.started",stage:"provider_load",provider:"stripe"});let n=new N,l=s.now();try{await n.initialize(i)}catch(w){throw s.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:Re(w)?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"unknown"}),s.destroy(),w}let m=s.now();s.log({name:"provider.ready",stage:"provider_ready",provider:"stripe"}),s.log({name:"provider.availability.checked",stage:"provider_ready",provider:"stripe"}),s.log({name:"sdk.initialize.ready",stage:"sdk_initialize"}),s.performance({stage:"sdk_initialize",durationMs:m-c,durationMode:"machine",provider:"stripe"}),s.performance({stage:"provider_ready",durationMs:m-l,durationMode:"machine",provider:"stripe"});let h=Pe(n,i,s);return Ee.set(r,h),h})();K.set(r,d);try{return await d}finally{K.get(r)===d&&K.delete(r)}}import{FloPayError as W,THREE_DS_CHALLENGE_WINDOW_MS as xe}from"@flopay/shared";var at=4,lt=1e3,ct=1e3,dt=15e3;function ut(e){let t=!!e?.gateways?.stripe,r=!!e?.gateways?.worldpayCorporateGateway;return t===r?"unknown":t?"stripe":"worldpay"}function mt(e,t,r){try{return typeof e?.beginThreeDsChallenge!="function"?void 0:e.beginThreeDsChallenge(t,{provider:ut(r)})}catch{return}}function H(e){return new W("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function Fe(){return new W("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function De(e){return e.replace(/\/+$/,"")}function pt(e){return e.status==="succeeded"||e.status==="authorized"||e.status==="declined"}function yt(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",r=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":case"authorized":case"pending":case"timeout":return{status:t,providerIntentId:r};case"declined":return{status:"declined",providerIntentId:r,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:r,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}async function Me(e){if(typeof document>"u"||typeof window>"u")throw new W("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});let t=X(e.telemetry);t.record("handoff_planned");let r=ie(e.nextActionRedirectUrl);r==="missing"?t.record("action_missing",{reason:"missing_url"}):r==="invalid"&&t.record("action_invalid",{reason:"invalid_url"});let o=p=>{let g=se(p);if(g==="buyer_cancel"){t.record("cancel_requested",{reason:g,evidenceBasis:"signal_reason"}),t.terminal("cancel",{reason:g,evidenceBasis:"signal_reason"});return}t.record("abort_observed",{reason:g,evidenceBasis:"signal_reason"}),t.terminal("abort",{reason:g,evidenceBasis:"signal_reason"})},a=p=>{(p.status==="succeeded"||p.status==="authorized"||p.status==="declined"||p.status==="timeout")&&t.reconcile(p.status)};if(e.signal?.aborted)throw o(e.signal.reason),H();let i=`${De(e.billingApiUrl)}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,d=async()=>{let p=new AbortController,g=()=>p.abort();e.signal?.aborted?p.abort():e.signal?.addEventListener("abort",g);let I=window.setTimeout(()=>p.abort(),dt);try{let f=await fetch(i,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json",...t.attemptId?{"x-flopay-challenge-attempt":t.attemptId}:{}},body:"{}",signal:p.signal});if(!f.ok)return{status:"unknown"};let x=await f.json().catch(()=>null),k=yt(x);return a(k),k}catch{return{status:"unknown"}}finally{window.clearTimeout(I),e.signal?.removeEventListener("abort",g)}},s,c=()=>e.pollCompletionEndpoint!==!1?d():(s??(s=d()),s),n=document.activeElement instanceof HTMLElement?document.activeElement:null,l=document.createElement("div");l.setAttribute("data-flopay-auto-3ds-overlay","1"),l.setAttribute("role","dialog"),l.setAttribute("aria-modal","true"),l.setAttribute("aria-label","Card authentication"),l.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let m=document.createElement("iframe");m.setAttribute("title","Card authentication"),m.setAttribute("allow","payment"),m.tabIndex=0,m.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";");let h=null;try{h=new URL(e.billingApiUrl,window.location.href).origin}catch{h=null}let w=ce(e.nextActionRedirectUrl);try{let p=await new Promise((g,I)=>{let f=!1,x=0,k=0,R=0,U=!1,F=!1,S=!1,_=0,C=()=>{window.clearTimeout(x),window.clearInterval(k),window.clearTimeout(R),window.removeEventListener("message",v),window.removeEventListener("pagehide",L),document.removeEventListener("securitypolicyviolation",b),m.removeEventListener("load",T),e.signal?.removeEventListener("abort",B)},q=async()=>{if(!(f||U)){U=!0;try{let y=await c();if(f||!pt(y))return;f=!0,C(),t.terminal("status_poll",{evidenceBasis:"server_status"}),g(y)}finally{U=!1}}},L=()=>{t.record("pagehide_observed",{evidenceBasis:"page_lifecycle_event"})},b=y=>{if(S)return;let u=le(y,w);u&&(S=!0,t.record("policy_violation",{reason:u,evidenceBasis:"parent_csp_event"}))},T=()=>{F||(F=!0,t.record("iframe_load",{evidenceBasis:"iframe_load_event"})),e.pollCompletionEndpoint!==!1&&(window.clearTimeout(R),R=window.setTimeout(()=>{q()},250))},B=()=>{f||(f=!0,C(),o(e.signal?.reason),I(H()))},P=y=>{f||_>=at||(_+=1,t.record("return_rejected",{reason:y,evidenceBasis:"message_origin_check"}))},v=y=>{let u=y.data,A=!!u&&typeof u=="object"&&u.source==="flopay-vault-3ds-return";if(y.source!==m.contentWindow){A&&P("untrusted_source");return}if(h&&y.origin!==h){A&&P("untrusted_origin");return}A&&(f||(f=!0,C(),t.record("trusted_return",{evidenceBasis:"message_origin_check"}),t.terminal("trusted_return",{evidenceBasis:"message_origin_check"}),g(null)))};x=window.setTimeout(()=>{f||(f=!0,C(),F||t.record("load_unconfirmed",{evidenceBasis:"no_load_signal"}),t.record("timer_expired",{reason:"window_elapsed",evidenceBasis:"timer"}),t.terminal("timer",{reason:"window_elapsed",evidenceBasis:"timer"}),I(Fe()))},xe),e.pollCompletionEndpoint!==!1&&(k=window.setInterval(()=>{q()},ct)),m.addEventListener("load",T),window.addEventListener("message",v),window.addEventListener("pagehide",L),document.addEventListener("securitypolicyviolation",b),e.signal?.addEventListener("abort",B),m.src=e.nextActionRedirectUrl,t.record("render_attempted");try{l.appendChild(m),document.body.appendChild(l)}catch(y){throw f=!0,C(),t.record("render_failed"),y}t.record("container_attached"),t.record("navigation_assigned");let D=ae(l);D&&t.record("container_visibility",{reason:D,evidenceBasis:"parent_computed_style"}),m.focus(),e.signal?.aborted&&B()});return p||await c()}finally{l.parentNode?.removeChild(l),t.record("teardown"),n?.isConnected&&n.focus()}}function Ie(e,t){try{let r=t.data.session?.status;r==="complete"?e.reconcile("succeeded"):r==="authorized"&&e.reconcile("authorized")}catch{}}function ft(e){return new W("Card was declined.","api_error",{code:e.declineReason??"authorization_declined",...e.gatewayDeclineReason?{declineCode:e.gatewayDeclineReason}:{}})}async function gt(e,t){let r=`${De(e.billingApiUrl)}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/status`,o=new AbortController,a=new AbortController,i=()=>{o.abort(e.signal?.reason),a.abort(e.signal?.reason)};e.signal?.aborted?i():e.signal?.addEventListener("abort",i,{once:!0});let d=X(e.telemetry),s=Me({billingApiUrl:e.billingApiUrl,sessionId:e.sessionId,nonce:e.nonce,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:o.signal,pollCompletionEndpoint:!1,...e.telemetry?{telemetry:e.telemetry}:{}}),c=t.waitForCheckoutSessionCompletion(e.sessionId,{initialDelayMs:lt,nonce:e.nonce,statusUrl:r,continueAfterActionRequired:!0,timeoutMs:xe+15e3,signal:a.signal,...d.attemptId?{challengeAttemptId:d.attemptId}:{}});c.catch(()=>{}),s.catch(()=>{});try{let n=await Promise.race([s,c]);if("data"in n)return d.terminal("status_poll",{evidenceBasis:"server_status"}),Ie(d,n),n;if(n.status==="declined")throw(e.createDeclineError??ft)(n);if(n.status==="timeout")throw Fe();let l=await c;return Ie(d,l),l}catch(n){throw e.signal?.aborted||n instanceof Error&&n.name==="AbortError"?H(n):n}finally{e.signal?.removeEventListener("abort",i),o.abort(),a.abort()}}export{$ as FloPay,Be as PaymentAPI,Z as PciVaultCardCapture,Le as SESSION_CREATE_TELEMETRY,N as StripeAdapter,mt as beginSavedCardChallengeTelemetry,Q as cacheSessionDisplayData,Ue as clearSessionDisplayData,gt as completeSavedCardNextAction,Qe as createCheckoutSession,Xe as createCheckoutSessionWithRetries,H as createSavedCardActionAbortedError,Kt as dropThirdPartyOnlyError,Oe as getSessionDisplayData,st as loadFloPay,Me as runSavedCardChallenge,rt as toStripeAppearance,ot as toStripeAppearanceTheme};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { CaptureMethod, CardCaptureAdapter, CardCaptureEventType, CardCaptureMountOptions, CardCaptureOutcomeEvent, CardCaptureProviderId, CardFieldsEvent, VaultCardFieldKey, VaultCardThemeColors } from '@flopay/shared';
|
|
1
|
+
import type { CaptureMethod, CardCaptureAdapter, CardCaptureEventType, CardCaptureMountOptions, CardCaptureOutcomeEvent, CardCaptureProviderId, CardFieldPlaceholders, CardFieldsEvent, VaultCardFieldKey, VaultCardThemeColors } from '@flopay/shared';
|
|
2
2
|
import { TelemetryReporter } from './telemetry-reporter.js';
|
|
3
3
|
/** Browser operation hosted by the PCIVault card-capture adapter. */
|
|
4
4
|
export type CardCaptureOperation = 'checkout' | 'card_setup';
|
|
@@ -104,6 +104,12 @@ export declare class PciVaultCardCapture implements CardCaptureAdapter {
|
|
|
104
104
|
* one — nothing is posted then, so the widget keeps its own default.
|
|
105
105
|
*/
|
|
106
106
|
private submitLabel;
|
|
107
|
+
/**
|
|
108
|
+
* Latest merchant placeholder text for the hosted card fields, or
|
|
109
|
+
* `undefined` when the host has never set any — nothing is posted then, so
|
|
110
|
+
* the widget keeps its own wording.
|
|
111
|
+
*/
|
|
112
|
+
private cardFieldPlaceholders;
|
|
107
113
|
/** Monotonic start of the current widget mount-to-ready machine interval. */
|
|
108
114
|
private mountStartedAt;
|
|
109
115
|
private vaultReadyReported;
|
|
@@ -183,6 +189,25 @@ export declare class PciVaultCardCapture implements CardCaptureAdapter {
|
|
|
183
189
|
* `ready` re-pushes it; an older hosted form ignores the directive.
|
|
184
190
|
*/
|
|
185
191
|
setCardBrandIcons(show: boolean): void;
|
|
192
|
+
/**
|
|
193
|
+
* Set the placeholder text of the hosted card number, expiry, CVV and name
|
|
194
|
+
* fields (live, no remount). Only the fields given are sent; the hosted form
|
|
195
|
+
* keeps its own wording for the rest. The text is forwarded verbatim (an
|
|
196
|
+
* empty string means "no placeholder"): the hosted form owns its limits.
|
|
197
|
+
* A later call replaces the earlier one. Stored so `ready` re-pushes it.
|
|
198
|
+
*
|
|
199
|
+
* `undefined` means nothing is set: nothing is posted. Called with
|
|
200
|
+
* `undefined` after text was set, it posts one empty set so the mounted
|
|
201
|
+
* form returns to its own wording.
|
|
202
|
+
*/
|
|
203
|
+
setCardFieldPlaceholders(placeholders: CardFieldPlaceholders | undefined): void;
|
|
204
|
+
/**
|
|
205
|
+
* postMessage placeholder text to the widget's document. Like the submit
|
|
206
|
+
* label it carries merchant text, so it is sent only with the session +
|
|
207
|
+
* message-token binding and only to the vault block's exact origin — never
|
|
208
|
+
* to `'*'`.
|
|
209
|
+
*/
|
|
210
|
+
private postCardFieldPlaceholders;
|
|
186
211
|
/** postMessage the current card brand icons flag to the widget's document. */
|
|
187
212
|
private postCardBrandIcons;
|
|
188
213
|
/**
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@flopay/js",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.18.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"sideEffects": false,
|
|
6
6
|
"publishConfig": {
|
|
@@ -31,7 +31,7 @@
|
|
|
31
31
|
"dist"
|
|
32
32
|
],
|
|
33
33
|
"dependencies": {
|
|
34
|
-
"@flopay/shared": "1.
|
|
34
|
+
"@flopay/shared": "1.18.0",
|
|
35
35
|
"@stripe/stripe-js": "^10.3.0"
|
|
36
36
|
},
|
|
37
37
|
"devDependencies": {
|